8380307: Refactor miscellaneous JAXP tests in javax/xml/jaxp/unittest to JUnit

Reviewed-by: liach, joehw
This commit is contained in:
David Beaumont 2026-03-31 10:00:03 +00:00
parent 46306d38ed
commit f45b48ba98
42 changed files with 1457 additions and 1922 deletions

View File

@ -26,8 +26,6 @@ package javax.xml.parsers.ptests;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
@ -44,7 +42,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
* @library /javax/xml/jaxp/libs
* @run junit/othervm javax.xml.parsers.ptests.FactoryConfErrorTest
*/
@Execution(ExecutionMode.SAME_THREAD)
public class FactoryConfErrorTest {
/**

View File

@ -26,8 +26,6 @@ package javax.xml.transform.ptests;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.w3c.dom.Document;
@ -77,7 +75,6 @@ import static javax.xml.transform.ptests.TransformerTestConst.XML_DIR;
* @summary Tests for variable combination of Transformer.transform(Source, Result)
*/
@TestInstance(Lifecycle.PER_CLASS)
@Execution(ExecutionMode.SAME_THREAD)
public class TransformTest {
/*

View File

@ -22,13 +22,10 @@
*/
package javax.xml.validation.ptests;
import jaxp.library.JAXPDataProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.w3c.dom.Document;
@ -78,7 +75,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
* @run junit/othervm javax.xml.validation.ptests.SchemaFactoryTest
* @summary Class containing the test cases for SchemaFactory
*/
@Execution(ExecutionMode.SAME_THREAD)
@TestInstance(Lifecycle.PER_CLASS)
public class SchemaFactoryTest {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -24,14 +24,15 @@
package bcel;
import com.sun.org.apache.bcel.internal.classfile.Utility;
import org.junit.jupiter.api.Test;
import java.util.Base64;
import org.testng.annotations.Test;
/*
* @test
* @bug 8256919
* @modules java.xml/com.sun.org.apache.bcel.internal.classfile
* @run testng bcel.UtilityTest
* @run junit bcel.UtilityTest
* @summary Tests the Utility.
*/
public class UtilityTest {
@ -42,7 +43,7 @@ public class UtilityTest {
*/
@Test
public void test() throws Exception {
/**
/*
* public class Hello {
* public void hello(){
* System.out.println("Hello,world");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,6 +23,24 @@
package catalog;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import jdk.test.lib.net.URIBuilder;
import jdk.test.lib.util.JarUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.xml.sax.InputSource;
import javax.xml.catalog.Catalog;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
@ -41,32 +59,18 @@ import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.xml.catalog.Catalog;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import jdk.test.lib.net.URIBuilder;
import jdk.test.lib.util.JarUtils;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 8151154 8171243
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest /test/lib
* @run testng/othervm catalog.CatalogFileInputTest
* @run junit/othervm catalog.CatalogFileInputTest
* @summary Verifies that the Catalog API accepts valid URIs only;
* Verifies that the CatalogFeatures' builder throws
* IllegalArgumentException on invalid file inputs.
@ -74,11 +78,12 @@ import org.xml.sax.InputSource;
* JDK-8168968, it has to only run without SecurityManager
* because an ACE will be thrown for invalid path.
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogFileInputTest extends CatalogSupportBase {
static final CatalogFeatures FEATURES = CatalogFeatures.builder().
with(CatalogFeatures.Feature.PREFER, "system").build();
static String CLS_DIR = getSystemProperty("test.classes");
static String CLS_DIR = System.getProperty("test.classes");
static String SRC_DIR = System.getProperty("test.src");
static String JAR_CONTENT = "META-INF";
final static String SCHEME_JARFILE = "jar:";
@ -91,7 +96,7 @@ public class CatalogFileInputTest extends CatalogSupportBase {
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
super.setUp();
// set up HttpServer
@ -107,7 +112,7 @@ public class CatalogFileInputTest extends CatalogSupportBase {
.build().toString() + REMOTE_FILE_LOCATION;
}
@AfterClass
@AfterAll
protected void tearDown() {
if (httpserver != null) {
httpserver.stop(0);
@ -119,87 +124,86 @@ public class CatalogFileInputTest extends CatalogSupportBase {
* Verifies that the Catalog can be created with file system paths including JAR
* and http URL, and used to resolve a systemId as expected.
*/
@Test(dataProvider = "acceptedURI")
public void testMatch(final String uri, final String sysId, final String pubId,
final String expectedId, final String msg) {
@ParameterizedTest
@MethodSource("acceptedURI")
public void testMatch(String uri, String sysId, String pubId, String expectedId, String msg) {
CatalogResolver cr = CatalogManager.catalogResolver(FEATURES, URI.create(uri));
InputSource is = cr.resolveEntity(pubId, sysId);
Assert.assertNotNull(is, msg);
Assert.assertEquals(expectedId, is.getSystemId(), msg);
assertNotNull(is, msg);
assertEquals(expectedId, is.getSystemId(), msg);
}
@Test(dataProvider = "invalidCatalog")
public void testEmptyCatalog(final String uri, final String publicId, final String msg) {
@ParameterizedTest
@MethodSource("invalidCatalog")
public void testEmptyCatalog(String uri, String publicId, String msg) {
Catalog c = CatalogManager.catalog(FEATURES, uri != null ? URI.create(uri) : null);
Assert.assertNull(c.matchSystem(publicId), msg);
assertNull(c.matchSystem(publicId), msg);
}
@Test(dataProvider = "invalidCatalog", expectedExceptions = CatalogException.class)
public void testCatalogResolverWEmptyCatalog(final String uri, final String publicId, final String msg) {
@ParameterizedTest
@MethodSource("invalidCatalog")
public void testCatalogResolverWEmptyCatalog(String uri, String publicId, String msg) {
CatalogResolver cr = CatalogManager.catalogResolver(
CatalogFeatures.builder().with(CatalogFeatures.Feature.RESOLVE, "strict").build(),
uri != null ? URI.create(uri) : null);
InputSource is = cr.resolveEntity(publicId, "");
assertThrows(CatalogException.class, () -> cr.resolveEntity(publicId, ""));
}
@Test(dataProvider = "invalidCatalog")
public void testCatalogResolverWEmptyCatalog1(final String uri, final String publicId, final String msg) {
@ParameterizedTest
@MethodSource("invalidCatalog")
public void testCatalogResolverWEmptyCatalog1(String uri, String publicId, String msg) {
CatalogResolver cr = CatalogManager.catalogResolver(
CatalogFeatures.builder().with(CatalogFeatures.Feature.RESOLVE, "continue").build(),
uri != null ? URI.create(uri) : null);
Assert.assertNull(cr.resolveEntity(publicId, ""), msg);
assertNull(cr.resolveEntity(publicId, ""), msg);
}
@Test(dataProvider = "invalidInput", expectedExceptions = IllegalArgumentException.class)
public void testFileInput(final String file) {
CatalogFeatures features = CatalogFeatures.builder()
.with(CatalogFeatures.Feature.FILES, file)
.build();
@ParameterizedTest
@MethodSource("invalidInput")
public void testFileInput(String file) {
assertThrows(
IllegalArgumentException.class,
() -> CatalogFeatures.builder().with(CatalogFeatures.Feature.FILES, file));
}
@Test(dataProvider = "invalidInput", expectedExceptions = IllegalArgumentException.class)
public void testInvalidUri(final String file) {
CatalogResolver cr = CatalogManager.catalogResolver(FEATURES, file != null ? URI.create(file) : null);
@ParameterizedTest
@MethodSource("invalidInput")
public void testInvalidUri(String file) {
URI uri = file != null ? URI.create(file) : null;
assertThrows(IllegalArgumentException.class, () -> CatalogManager.catalogResolver(FEATURES, uri));
}
@Test(dataProvider = "invalidInput", expectedExceptions = IllegalArgumentException.class)
public void testInvalidUri1(final String file) {
Catalog c = CatalogManager.catalog(FEATURES, file != null ? URI.create(file) : null);
System.err.println("Catalog =" + c);
@ParameterizedTest
@MethodSource("invalidInput")
public void testInvalidUri1(String file) {
URI uri = file != null ? URI.create(file) : null;
assertThrows(IllegalArgumentException.class, () -> CatalogManager.catalog(FEATURES, uri));
}
@Test(expectedExceptions = NullPointerException.class)
public void testNullFileInput() {
CatalogFeatures features = CatalogFeatures.builder()
.with(CatalogFeatures.Feature.FILES, null)
.build();
@Test
public void testNull() {
assertThrows(
NullPointerException.class,
() -> CatalogFeatures.builder().with(CatalogFeatures.Feature.FILES, null));
}
@Test(expectedExceptions = NullPointerException.class)
@Test
public void testNullUri() {
URI uri = null;
CatalogResolver cr = CatalogManager.catalogResolver(FEATURES, uri);
assertThrows(NullPointerException.class, () -> CatalogManager.catalogResolver(FEATURES, (URI) null));
assertThrows(NullPointerException.class, () -> CatalogManager.catalog(FEATURES, (URI) null));
}
@Test(expectedExceptions = NullPointerException.class)
public void testNullUri1() {
URI uri = null;
Catalog c = CatalogManager.catalog(FEATURES, uri);
}
private String systemId = "http://www.sys00test.com/rewrite.dtd";
private String publicId = "PUB-404";
private String expected = "http://www.groupxmlbase.com/dtds/rewrite.dtd";
private String errMsg = "Relative rewriteSystem with xml:base at group level failed";
private static final String systemId = "http://www.sys00test.com/rewrite.dtd";
private static final String publicId = "PUB-404";
private static final String expected = "http://www.groupxmlbase.com/dtds/rewrite.dtd";
private static final String errMsg = "Relative rewriteSystem with xml:base at group level failed";
/*
DataProvider: used to verify CatalogResolver's resolveEntity function.
Data columns:
catalog, systemId, publicId, expectedUri, msg
*/
@DataProvider(name = "acceptedURI")
Object[][] getData() throws Exception {
Object[][] acceptedURI() throws IOException {
String filename = "rewriteSystem_id.xml";
String urlFile = getClass().getResource(filename).toExternalForm();
String urlHttp = remoteFilePath + "/jax-ws-catalog.xml";
@ -209,12 +213,7 @@ public class CatalogFileInputTest extends CatalogSupportBase {
String xsd = jarPath.substring(0, jarPath.lastIndexOf("/")) + "/catalog/ws-addr.xsd";
// create JAR file
try {
JarUtils.createJarFile(Paths.get(CLS_DIR + "/JDK8171243.jar"),
Paths.get(SRC_DIR + "/jar"), JAR_CONTENT);
} catch (IOException ex) {
Assert.fail("Failed to create JAR: " + ex.getMessage());
}
JarUtils.createJarFile(Paths.get(CLS_DIR + "/JDK8171243.jar"), Paths.get(SRC_DIR + "/jar"), JAR_CONTENT);
return new Object[][]{
// URL
@ -230,8 +229,7 @@ public class CatalogFileInputTest extends CatalogSupportBase {
* Note: the difference from invalidInput is that invalidInput is syntactically
* rejected with an IAE.
*/
@DataProvider(name = "invalidCatalog")
public Object[][] getInvalidCatalog() {
public Object[][] invalidCatalog() {
String catalogUri = getClass().getResource("catalog_invalid.xml").toExternalForm();
return new Object[][]{
{catalogUri, "-//W3C//DTD XHTML 1.0 Strict//EN",
@ -245,38 +243,24 @@ public class CatalogFileInputTest extends CatalogSupportBase {
* DataProvider: a list of invalid inputs, expects IAE
* Note: exclude null since NPE would have been expected
*/
@DataProvider(name = "invalidInput")
public Object[][] getFiles() throws Exception {
public Object[][] invalidInput() throws Exception {
String filename = "rewriteSystem_id.xml";
copyFile(Paths.get(SRC_DIR + "/" + filename), Paths.get(filename));
String absolutePath = getClass().getResource(filename).getFile();
return new Object[][]{
{""},
{"file:a/b\\c"},
{"c:/te:t"},
{"c:/te?t"},
{"c/te*t"},
{"in|valid.txt"},
{"shema:invalid.txt"},
// relative file path
{filename},
// absolute file path
{absolutePath}
return new Object[][] {
{ "c:/te:t" },
{ "c:/te?t" },
{ "c/te*t" },
{ "shema:invalid.txt" },
// relative file path
{ filename },
// absolute file path
{ absolutePath }
};
}
/*
DataProvider: a list of invalid inputs
*/
@DataProvider(name = "nullTest")
public Object[][] getNull() {
return new Object[][]{
{null},
};
}
void copyFile(final Path src, final Path target) throws Exception {
private static void copyFile(final Path src, final Path target) throws Exception {
try (InputStream in = Files.newInputStream(src);
BufferedReader reader
= new BufferedReader(new InputStreamReader(in));

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -22,36 +22,41 @@
*/
package catalog;
import java.net.URI;
import java.nio.file.Paths;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.xml.sax.InputSource;
import javax.xml.catalog.Catalog;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import javax.xml.catalog.CatalogResolver.NotFoundAction;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
import java.net.URI;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 8316996
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm catalog.CatalogResolverTest
* @run junit/othervm catalog.CatalogResolverTest
* @summary Tests CatalogResolver functions. See CatalogTest for existing basic
* functional tests.
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogResolverTest extends CatalogSupportBase {
static final String KEY_FILES = "javax.xml.catalog.files";
static final String SYSTEM_ID = "http://openjdk_java_net/xml/catalog/dtd/system.dtd";
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
super.setUp();
}
@ -63,7 +68,6 @@ public class CatalogResolverTest extends CatalogSupportBase {
resolve property for the Catalog, resolve property for the CatalogResolver,
system ID to be resolved, expected result, expected exception
*/
@DataProvider(name = "factoryMethodInput")
public Object[][] getInputs() throws Exception {
return new Object[][]{
@ -80,7 +84,6 @@ public class CatalogResolverTest extends CatalogSupportBase {
};
}
@DataProvider(name = "NPETest")
public Object[][] getNPETest() throws Exception {
return new Object[][]{
{null, null},
@ -104,22 +107,22 @@ public class CatalogResolverTest extends CatalogSupportBase {
* @param expectedThrow the expected exception
* @throws Exception if the test fails
*/
@Test(dataProvider = "factoryMethodInput")
@ParameterizedTest
@MethodSource("getInputs")
public void testResolveProperty(String cResolve, NotFoundAction action,
String systemId, String expectedResult, Class<Throwable> expectedThrow)
throws Exception {
Catalog c = getCatalog(cResolve);
if (expectedThrow != null) {
Assert.assertThrows(expectedThrow,
() -> resolveRef(c, action, systemId));
assertThrows(expectedThrow, () -> resolveRef(c, action, systemId));
} else {
String sysId = resolveRef(c, action, systemId);
System.out.println(sysId);
Assert.assertEquals(sysId,
(expectedResult == null) ? null : Paths.get(filepath + expectedResult).toUri().toString().replace("///", "/"),
"System ID match not right");
String expected = (expectedResult == null)
? null
: Paths.get(filepath + expectedResult).toUri().toString().replace("///", "/");
assertEquals(expected, sysId, "System ID match not right");
}
}
@ -127,9 +130,10 @@ public class CatalogResolverTest extends CatalogSupportBase {
* Verifies that the catalogResolver method throws NullPointerException if
* any of the parameters is null.
*/
@Test(dataProvider = "NPETest", expectedExceptions = NullPointerException.class)
@ParameterizedTest
@MethodSource("getNPETest")
public void testCatalogProperty(Catalog c, NotFoundAction action) {
CatalogManager.catalogResolver(c, action);
assertThrows(NullPointerException.class, () -> CatalogManager.catalogResolver(c, action));
}
private String resolveRef(Catalog c, NotFoundAction action, String systemId) throws Exception {
@ -140,9 +144,8 @@ public class CatalogResolverTest extends CatalogSupportBase {
private Catalog getCatalog(String cResolve) throws Exception {
URI catalogFile = getClass().getResource("catalog.xml").toURI();
Catalog c = CatalogManager.catalog(
return CatalogManager.catalog(
CatalogFeatures.builder().with(CatalogFeatures.Feature.RESOLVE, cResolve).build(),
catalogFile);
return c;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -22,22 +22,27 @@
*/
package catalog;
import java.net.URI;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import javax.xml.catalog.Catalog;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.net.URI;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @bug 8253569
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng catalog.CatalogReuseTest
* @run junit catalog.CatalogReuseTest
* @summary Verifies that a catalog can be reused.
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogReuseTest extends CatalogSupportBase {
static final CatalogFeatures FEATURES_STRICT = CatalogFeatures.builder().
with(CatalogFeatures.Feature.RESOLVE, "strict").build();
@ -46,7 +51,6 @@ public class CatalogReuseTest extends CatalogSupportBase {
DataProvider: reuses a catalog. The length of the URIs is in descending order.
Data columns: catalog, uri, expected
*/
@DataProvider(name = "dataWithCatalogD")
public Object[][] dataWithCatalogD() {
Catalog c = getCatalog();
return new Object[][]{
@ -59,7 +63,6 @@ public class CatalogReuseTest extends CatalogSupportBase {
DataProvider: reuses a catalog. The length of the URIs is in ascending order.
Data columns: catalog, uri, expected
*/
@DataProvider(name = "dataWithCatalogA")
public Object[][] dataWithCatalogA() {
Catalog c = getCatalog();
return new Object[][]{
@ -72,18 +75,17 @@ public class CatalogReuseTest extends CatalogSupportBase {
DataProvider: provides no catalog. A new catalog will be created for each test.
Data columns: uri, expected
*/
@DataProvider(name = "dataWithoutCatalog")
public Object[][] dataWithoutCatalog() {
return new Object[][]{
{"http://entailments/example.org/A/B/derived.ttl", "derived/A/B/derived.ttl"},
{"http://example.org/A/B.owl", "sources/A/B.owl"},
};
return new Object[][] {
{ "http://entailments/example.org/A/B/derived.ttl", "derived/A/B/derived.ttl" },
{ "http://example.org/A/B.owl", "sources/A/B.owl" },
};
}
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
super.setUp();
}
@ -91,36 +93,38 @@ public class CatalogReuseTest extends CatalogSupportBase {
/*
* Verifies that a Catalog object can be reused, that no state data are
* in the way of a subsequent matching attempt.
*/
@Test(dataProvider = "dataWithCatalogD")
*/
@ParameterizedTest
@MethodSource("dataWithCatalogD")
public void testD(Catalog c, String uri, String expected) throws Exception {
String m = c.matchURI(uri);
Assert.assertTrue(m.endsWith(expected), "Expected: " + expected);
assertTrue(m.endsWith(expected), "Expected: " + expected);
}
/*
* Verifies that a Catalog object can be reused.
*/
@Test(dataProvider = "dataWithCatalogA")
*/
@ParameterizedTest
@MethodSource("dataWithCatalogA")
public void testA(Catalog c, String uri, String expected) throws Exception {
String m = c.matchURI(uri);
Assert.assertTrue(m.endsWith(expected), "Expected: " + expected);
assertTrue(m.endsWith(expected), "Expected: " + expected);
}
/*
* Verifies that a match is found in a newly created Catalog.
*/
@Test(dataProvider = "dataWithoutCatalog")
*/
@ParameterizedTest
@MethodSource("dataWithoutCatalog")
public void testNew(String uri, String expected) throws Exception {
Catalog c = getCatalog();
String m = c.matchURI(uri);
Assert.assertTrue(m.endsWith(expected), "Expected: " + expected);
assertTrue(m.endsWith(expected), "Expected: " + expected);
}
private Catalog getCatalog() {
String uri = "file://" + slash + filepath + "/catalogReuse.xml";
Catalog c = CatalogManager.catalog(FEATURES_STRICT, uri != null? URI.create(uri) : null);
return c;
return CatalogManager.catalog(FEATURES_STRICT, URI.create(uri));
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,8 +23,14 @@
package catalog;
import java.io.File;
import java.io.StringReader;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import javax.xml.stream.XMLResolver;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
@ -32,17 +38,14 @@ import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import java.io.File;
import java.io.StringReader;
/**
/*
* @test
* @bug 8158084 8162438 8162442 8166220 8166398 8290740
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm catalog.CatalogSupport
* @run junit/othervm catalog.CatalogSupport
* @summary verifies the use of Catalog in SAX/DOM/StAX/Validation/Transform.
* The two main scenarios for all processors are:
* A custom resolver is used whether or not there's a Catalog;
@ -51,12 +54,12 @@ import org.xml.sax.InputSource;
*/
/**
* Support Catalog:
* <h3>Support Catalog:</h3>
* With this patch, the Catalog features are supported by all of the JAXP processors.
* The support is enabled by default. Using Catalog is as simple as setting a
* path to a catalog, through the API, or System property, or jaxp.properties.
*
* Test notes:
* <h3>Test notes:</h3>
* For all DataProviders, the 1st and 2nd columns determine whether to set USE_CATALOG
* through the API and to use Catalog. When a custom resolver is specified, these
* settings should not affect the operation, thus the tests are repeated for both
@ -64,11 +67,12 @@ import org.xml.sax.InputSource;
*
* @author huizhe.wang@oracle.com
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogSupport extends CatalogSupportBase {
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
setUp();
}
@ -76,7 +80,8 @@ public class CatalogSupport extends CatalogSupportBase {
/*
Verifies the Catalog support on SAXParser.
*/
@Test(dataProvider = "data_SAXA")
@ParameterizedTest
@MethodSource("getDataSAX")
public void testSAXA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@ -85,7 +90,8 @@ public class CatalogSupport extends CatalogSupportBase {
/*
Verifies the Catalog support on XMLReader.
*/
@Test(dataProvider = "data_SAXA")
@ParameterizedTest
@MethodSource("getDataSAX")
public void testXMLReaderA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@ -94,7 +100,8 @@ public class CatalogSupport extends CatalogSupportBase {
/*
Verifies the Catalog support on XInclude.
*/
@Test(dataProvider = "data_XIA")
@ParameterizedTest
@MethodSource("getDataXI")
public void testXIncludeA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@ -104,7 +111,8 @@ public class CatalogSupport extends CatalogSupportBase {
Verifies that the Catalog is used when the handler is null. The test shall
run through without an Exception (that was thrown before the fix).
*/
@Test(dataProvider = "data_XIA")
@ParameterizedTest
@MethodSource("getDataXI")
public void testXIncludeA_NullHandler(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
handler = null;
@ -114,7 +122,8 @@ public class CatalogSupport extends CatalogSupportBase {
/*
Verifies the Catalog support on DOM parser.
*/
@Test(dataProvider = "data_DOMA")
@ParameterizedTest
@MethodSource("getDataDOM")
public void testDOMA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@ -123,7 +132,8 @@ public class CatalogSupport extends CatalogSupportBase {
/*
Verifies the Catalog support on XMLStreamReader.
*/
@Test(dataProvider = "data_StAXA")
@ParameterizedTest
@MethodSource("getDataStAX")
public void testStAXA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, XMLResolver resolver, String expected) throws Exception {
testStAX(setUseCatalog, useCatalog, catalog, xml, resolver, expected);
@ -133,7 +143,8 @@ public class CatalogSupport extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsd import and include in
Schema files.
*/
@Test(dataProvider = "data_SchemaA")
@ParameterizedTest
@MethodSource("getDataSchema")
public void testValidationA(boolean setUseCatalog, boolean useCatalog,
String catalog, String xsd, LSResourceResolver resolver)
throws Exception {
@ -145,7 +156,8 @@ public class CatalogSupport extends CatalogSupportBase {
@bug 8158084 8162438 these tests also verifies the fix for 8162438
Verifies the Catalog support on the Schema Validator.
*/
@Test(dataProvider = "data_ValidatorA")
@ParameterizedTest
@MethodSource("getDataValidator")
public void testValidatorA(boolean setUseCatalog1, boolean setUseCatalog2, boolean useCatalog,
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2)
@ -158,7 +170,8 @@ public class CatalogSupport extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLA")
@ParameterizedTest
@MethodSource("getDataXSL")
public void testXSLImportA(boolean setUseCatalog, boolean useCatalog, String catalog,
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected)
throws Exception {
@ -171,7 +184,8 @@ public class CatalogSupport extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLA")
@ParameterizedTest
@MethodSource("getDataXSL")
public void testXSLImportWTemplatesA(boolean setUseCatalog, boolean useCatalog,
String catalog, SAXSource xsl, StreamSource xml, URIResolver resolver, String expected)
throws Exception {
@ -182,7 +196,6 @@ public class CatalogSupport extends CatalogSupportBase {
DataProvider: for testing the SAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_SAXA")
public Object[][] getDataSAX() {
String[] systemIds = {"system.dtd"};
return new Object[][]{
@ -198,7 +211,6 @@ public class CatalogSupport extends CatalogSupportBase {
DataProvider: for testing XInclude
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_XIA")
public Object[][] getDataXI() {
String[] systemIds = {"XI_simple.xml"};
InputSource[] returnValues = {new InputSource(xml_xIncludeSimple)};
@ -214,7 +226,6 @@ public class CatalogSupport extends CatalogSupportBase {
DataProvider: for testing DOM parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_DOMA")
public Object[][] getDataDOM() {
String[] systemIds = {"system.dtd"};
InputSource[] returnValues = {new InputSource(new StringReader(dtd_systemResolved))};
@ -232,7 +243,6 @@ public class CatalogSupport extends CatalogSupportBase {
DataProvider: for testing the StAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_StAXA")
public Object[][] getDataStAX() {
return new Object[][]{
@ -250,7 +260,6 @@ public class CatalogSupport extends CatalogSupportBase {
DataProvider: for testing Schema validation
Data: set use_catalog, use_catalog, catalog file, xsd file, a LSResourceResolver
*/
@DataProvider(name = "data_SchemaA")
public Object[][] getDataSchema() {
String[] systemIds = {"pathto/XMLSchema.dtd", "datatypes.dtd"};
XmlInput[] returnValues = {new XmlInput(null, dtd_xmlSchema, null), new XmlInput(null, dtd_datatypes, null)};
@ -285,7 +294,6 @@ public class CatalogSupport extends CatalogSupportBase {
DataProvider: for testing Schema Validator
Data: source, resolver1, resolver2, catalog1, a catalog2
*/
@DataProvider(name = "data_ValidatorA")
public Object[][] getDataValidator() {
DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);
@ -325,7 +333,6 @@ public class CatalogSupport extends CatalogSupportBase {
DataProvider: for testing XSL import and include
Data: set use_catalog, use_catalog, catalog file, xsl file, xml file, a URIResolver, expected result
*/
@DataProvider(name = "data_XSLA")
public Object[][] getDataXSL() {
// XSLInclude.xsl has one import XSLImport_html.xsl and two includes,
// XSLInclude_header.xsl and XSLInclude_footer.xsl;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,11 +23,14 @@
package catalog;
import static jaxp.library.JAXPTestUtilities.clearSystemProperty;
import static jaxp.library.JAXPTestUtilities.setSystemProperty;
import java.io.File;
import java.io.StringReader;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import javax.xml.catalog.CatalogFeatures.Feature;
import javax.xml.stream.XMLResolver;
@ -37,19 +40,14 @@ import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import java.io.File;
import java.io.StringReader;
/*
* @test
* @bug 8158084 8162438 8162442 8166220
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm catalog.CatalogSupport1
* @run junit/othervm catalog.CatalogSupport1
* @summary extends CatalogSupport, verifies that the catalog file can be set
* using the System property.
*/
@ -60,25 +58,27 @@ import org.xml.sax.InputSource;
*
* @author huizhe.wang@oracle.com
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogSupport1 extends CatalogSupportBase {
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
setUp();
setSystemProperty(Feature.FILES.getPropertyName(), xml_catalog);
System.setProperty(Feature.FILES.getPropertyName(), xml_catalog);
}
@AfterClass
@AfterAll
public void tearDownClass() throws Exception {
clearSystemProperty(Feature.FILES.getPropertyName());
System.clearProperty(Feature.FILES.getPropertyName());
}
/*
Verifies the Catalog support on SAXParser.
*/
@Test(dataProvider = "data_SAXC")
@ParameterizedTest
@MethodSource("getDataSAXC")
public void testSAXC(boolean setUseCatalog, boolean useCatalog, String catalog, String xml, MyHandler handler, String expected) throws Exception {
testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected);
}
@ -86,7 +86,8 @@ public class CatalogSupport1 extends CatalogSupportBase {
/*
Verifies the Catalog support on XMLReader.
*/
@Test(dataProvider = "data_SAXC")
@ParameterizedTest
@MethodSource("getDataSAXC")
public void testXMLReaderC(boolean setUseCatalog, boolean useCatalog, String catalog, String xml, MyHandler handler, String expected) throws Exception {
testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected);
}
@ -94,7 +95,8 @@ public class CatalogSupport1 extends CatalogSupportBase {
/*
Verifies the Catalog support on XInclude.
*/
@Test(dataProvider = "data_XIC")
@ParameterizedTest
@MethodSource("getDataXIC")
public void testXIncludeC(boolean setUseCatalog, boolean useCatalog, String catalog, String xml, MyHandler handler, String expected) throws Exception {
testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected);
}
@ -102,7 +104,8 @@ public class CatalogSupport1 extends CatalogSupportBase {
/*
Verifies the Catalog support on DOM parser.
*/
@Test(dataProvider = "data_DOMC")
@ParameterizedTest
@MethodSource("getDataDOMC")
public void testDOMC(boolean setUseCatalog, boolean useCatalog, String catalog, String xml, MyHandler handler, String expected) throws Exception {
testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected);
}
@ -110,7 +113,8 @@ public class CatalogSupport1 extends CatalogSupportBase {
/*
Verifies the Catalog support on XMLStreamReader.
*/
@Test(dataProvider = "data_StAXC")
@ParameterizedTest
@MethodSource("getDataStAX")
public void testStAXC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, XMLResolver resolver, String expected) throws Exception {
testStAX(setUseCatalog, useCatalog, catalog, xml, resolver, expected);
@ -120,7 +124,8 @@ public class CatalogSupport1 extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsd import and include in
Schema files.
*/
@Test(dataProvider = "data_SchemaC")
@ParameterizedTest
@MethodSource("getDataSchemaC")
public void testValidationC(boolean setUseCatalog, boolean useCatalog, String catalog, String xsd, LSResourceResolver resolver)
throws Exception {
@ -131,7 +136,8 @@ public class CatalogSupport1 extends CatalogSupportBase {
@bug 8158084 8162438 these tests also verifies the fix for 8162438
Verifies the Catalog support on the Schema Validator.
*/
@Test(dataProvider = "data_ValidatorC")
@ParameterizedTest
@MethodSource("getDataValidator")
public void testValidatorA(boolean setUseCatalog1, boolean setUseCatalog2, boolean useCatalog,
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2)
@ -144,7 +150,8 @@ public class CatalogSupport1 extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC")
@ParameterizedTest
@MethodSource("getDataXSLC")
public void testXSLImportC(boolean setUseCatalog, boolean useCatalog, String catalog, SAXSource xsl, StreamSource xml,
URIResolver resolver, String expected) throws Exception {
@ -156,7 +163,8 @@ public class CatalogSupport1 extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC")
@ParameterizedTest
@MethodSource("getDataXSLC")
public void testXSLImportWTemplatesC(boolean setUseCatalog, boolean useCatalog, String catalog, SAXSource xsl, StreamSource xml,
URIResolver resolver, String expected) throws Exception {
testXSLImportWTemplates(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected);
@ -166,7 +174,6 @@ public class CatalogSupport1 extends CatalogSupportBase {
DataProvider: for testing the SAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_SAXC")
public Object[][] getDataSAXC() {
return new Object[][]{
{false, true, null, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
@ -178,7 +185,6 @@ public class CatalogSupport1 extends CatalogSupportBase {
DataProvider: for testing XInclude
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_XIC")
public Object[][] getDataXIC() {
return new Object[][]{
{false, true, null, xml_xInclude, new MyHandler(elementInXISimple), contentInUIutf8Catalog},
@ -189,7 +195,6 @@ public class CatalogSupport1 extends CatalogSupportBase {
DataProvider: for testing DOM parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_DOMC")
public Object[][] getDataDOMC() {
return new Object[][]{
{false, true, null, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
@ -200,7 +205,6 @@ public class CatalogSupport1 extends CatalogSupportBase {
DataProvider: for testing the StAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_StAXC")
public Object[][] getDataStAX() {
return new Object[][]{
@ -212,7 +216,6 @@ public class CatalogSupport1 extends CatalogSupportBase {
DataProvider: for testing Schema validation
Data: set use_catalog, use_catalog, catalog file, xsd file, a LSResourceResolver
*/
@DataProvider(name = "data_SchemaC")
public Object[][] getDataSchemaC() {
return new Object[][]{
@ -230,7 +233,6 @@ public class CatalogSupport1 extends CatalogSupportBase {
DataProvider: for testing Schema Validator
Data: source, resolver1, resolver2, catalog1, a catalog2
*/
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, false, true, null);
@ -270,7 +272,6 @@ public class CatalogSupport1 extends CatalogSupportBase {
DataProvider: for testing XSL import and include
Data: set use_catalog, use_catalog, catalog file, xsl file, xml file, a URIResolver, expected
*/
@DataProvider(name = "data_XSLC")
public Object[][] getDataXSLC() {
SAXSource xslSourceDTD = new SAXSource(new InputSource(new StringReader(xsl_includeDTD)));
StreamSource xmlSourceDTD = new StreamSource(new StringReader(xml_xslDTD));

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,13 +23,17 @@
package catalog;
import static jaxp.library.JAXPTestUtilities.clearSystemProperty;
import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import static jaxp.library.JAXPTestUtilities.setSystemProperty;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.stream.XMLResolver;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Source;
@ -39,21 +43,16 @@ import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.StringReader;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 8158084 8162438 8162442 8163535 8166220 8344800
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm catalog.CatalogSupport2
* @run junit/othervm catalog.CatalogSupport2
* @summary extends CatalogSupport tests, verifies that the use of the Catalog may
* be disabled through the System property.
*/
@ -65,108 +64,130 @@ import org.xml.sax.SAXParseException;
*
* @author huizhe.wang@oracle.com
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogSupport2 extends CatalogSupportBase {
static final String TTIMEOUTREAD = "sun.net.client.defaultReadTimeout";
static final String TIMEOUTCONNECT = "sun.net.client.defaultConnectTimeout";
static String timeoutRead = getSystemProperty(TTIMEOUTREAD);
static String timeoutConnect = getSystemProperty(TIMEOUTCONNECT);
static String timeoutRead = System.getProperty(TTIMEOUTREAD);
static String timeoutConnect = System.getProperty(TIMEOUTCONNECT);
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
setUp();
setSystemProperty(SP_USE_CATALOG, "false");
setSystemProperty(SP_ACCESS_EXTERNAL_DTD, "file");
timeoutRead = getSystemProperty(TTIMEOUTREAD);
timeoutConnect = getSystemProperty(TIMEOUTCONNECT);
setSystemProperty(TTIMEOUTREAD, "1000");
setSystemProperty(TIMEOUTCONNECT, "1000");
System.setProperty(SP_USE_CATALOG, "false");
System.setProperty(SP_ACCESS_EXTERNAL_DTD, "file");
timeoutRead = System.getProperty(TTIMEOUTREAD);
timeoutConnect = System.getProperty(TIMEOUTCONNECT);
System.setProperty(TTIMEOUTREAD, "1000");
System.setProperty(TIMEOUTCONNECT, "1000");
}
@AfterClass
public void tearDownClass() throws Exception {
clearSystemProperty(SP_USE_CATALOG);
clearSystemProperty(SP_ACCESS_EXTERNAL_DTD);
setSystemProperty(TIMEOUTCONNECT, "-1");
setSystemProperty(TTIMEOUTREAD, "-1");
@AfterAll
public void tearDownClass() {
System.clearProperty(SP_USE_CATALOG);
System.clearProperty(SP_ACCESS_EXTERNAL_DTD);
System.setProperty(TIMEOUTCONNECT, "-1");
System.setProperty(TTIMEOUTREAD, "-1");
}
/*
Verifies the Catalog support on SAXParser.
*/
@Test(dataProvider = "data_SAXC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataSAXC")
public void testSAXC(boolean setUseCatalog, boolean useCatalog, String catalog, String
xml, MyHandler handler, String expected) throws Exception {
testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected);
assertThrows(
SAXParseException.class,
() -> testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on XMLReader.
*/
@Test(dataProvider = "data_SAXC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataSAXC")
public void testXMLReaderC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) throws Exception {
assertThrows(
SAXParseException.class,
() -> testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on XInclude.
*/
@Test(dataProvider = "data_XIC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataXIC")
public void testXIncludeC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) throws Exception {
assertThrows(
SAXParseException.class,
() -> testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on DOM parser.
*/
@Test(dataProvider = "data_DOMC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataDOMC")
public void testDOMC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) throws Exception {
assertThrows(
SAXParseException.class,
() -> testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on XMLStreamReader.
*/
@Test(dataProvider = "data_StAXC", expectedExceptions = XMLStreamException.class)
@ParameterizedTest
@MethodSource("getDataStAX")
public void testStAXC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, XMLResolver resolver, String expected) throws Exception {
testStAXNegative(setUseCatalog, useCatalog, catalog, xml, resolver, expected);
String xml, XMLResolver resolver, String expected) throws Exception {
assertThrows(
XMLStreamException.class,
() -> testStAXNegative(setUseCatalog, useCatalog, catalog, xml, resolver, expected));
}
/*
Verifies the Catalog support on resolving DTD, xsd import and include in
Schema files.
*/
@Test(dataProvider = "data_SchemaC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataSchemaC")
public void testValidationC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xsd, LSResourceResolver resolver)
throws Exception {
testValidation(setUseCatalog, useCatalog, catalog, xsd, resolver) ;
String xsd, LSResourceResolver resolver) {
assertThrows(
SAXParseException.class,
() -> testValidation(setUseCatalog, useCatalog, catalog, xsd, resolver));
}
@Test(dataProvider = "data_ValidatorC", expectedExceptions = {SAXException.class, IOException.class})
@ParameterizedTest
@MethodSource("getDataValidator")
public void testValidatorC(boolean setUseCatalog1, boolean setUseCatalog2, boolean useCatalog,
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2)
throws Exception {
testValidator(setUseCatalog1, setUseCatalog2, useCatalog, source,
resolver1, resolver2, catalog1, catalog2);
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2) {
assertThrows(
SAXException.class,
() -> testValidator(setUseCatalog1, setUseCatalog2, useCatalog, source, resolver1, resolver2, catalog1, catalog2));
}
/*
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC", expectedExceptions = TransformerException.class)
@ParameterizedTest
@MethodSource("getDataXSLC")
public void testXSLImportC(boolean setUseCatalog, boolean useCatalog, String catalog,
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception {
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) {
testXSLImport(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected);
assertThrows(
TransformerException.class,
() -> testXSLImport(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected));
}
/*
@ -174,17 +195,19 @@ public class CatalogSupport2 extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC", expectedExceptions = TransformerException.class)
@ParameterizedTest
@MethodSource("getDataXSLC")
public void testXSLImportWTemplatesC(boolean setUseCatalog, boolean useCatalog, String catalog,
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception {
testXSLImportWTemplates(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected);
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) {
assertThrows(
TransformerException.class,
() -> testXSLImportWTemplates(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected));
}
/*
DataProvider: for testing the SAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_SAXC")
public Object[][] getDataSAXC() {
return new Object[][]{
{false, true, xml_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
@ -196,7 +219,6 @@ public class CatalogSupport2 extends CatalogSupportBase {
DataProvider: for testing XInclude
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_XIC")
public Object[][] getDataXIC() {
return new Object[][]{
{false, true, xml_catalog, xml_xInclude, new MyHandler(elementInXISimple), contentInUIutf8Catalog},
@ -207,7 +229,6 @@ public class CatalogSupport2 extends CatalogSupportBase {
DataProvider: for testing DOM parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_DOMC")
public Object[][] getDataDOMC() {
return new Object[][]{
{false, true, xml_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
@ -218,7 +239,6 @@ public class CatalogSupport2 extends CatalogSupportBase {
DataProvider: for testing the StAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_StAXC")
public Object[][] getDataStAX() {
return new Object[][]{
{false, true, xml_catalog, xml_system, null, "null"},
@ -229,7 +249,6 @@ public class CatalogSupport2 extends CatalogSupportBase {
DataProvider: for testing Schema validation
Data: set use_catalog, use_catalog, catalog file, xsd file, a LSResourceResolver
*/
@DataProvider(name = "data_SchemaC")
public Object[][] getDataSchemaC() {
return new Object[][]{
@ -247,7 +266,6 @@ public class CatalogSupport2 extends CatalogSupportBase {
DataProvider: for testing Schema Validator
Data: source, resolver1, resolver2, catalog1, a catalog2
*/
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);
@ -276,7 +294,6 @@ public class CatalogSupport2 extends CatalogSupportBase {
DataProvider: for testing XSL import and include
Data: set use_catalog, use_catalog, catalog file, xsl file, xml file, a URIResolver, expected
*/
@DataProvider(name = "data_XSLC")
public Object[][] getDataXSLC() {
SAXSource xslSourceDTD = new SAXSource(new InputSource(new StringReader(xsl_includeDTD)));
StreamSource xmlSourceDTD = new StreamSource(new StringReader(xml_xslDTD));

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,13 +23,17 @@
package catalog;
import static jaxp.library.JAXPTestUtilities.clearSystemProperty;
import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import static jaxp.library.JAXPTestUtilities.setSystemProperty;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.stream.XMLResolver;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Source;
@ -39,21 +43,16 @@ import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.StringReader;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 8158084 8162438 8162442 8163535 8166220 8344800
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm catalog.CatalogSupport3
* @run junit/othervm catalog.CatalogSupport3
* @summary extends CatalogSupport tests, verifies that the use of the Catalog may
* be disabled through the API property.
*/
@ -65,109 +64,131 @@ import org.xml.sax.SAXParseException;
*
* @author huizhe.wang@oracle.com
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogSupport3 extends CatalogSupportBase {
static final String TTIMEOUTREAD = "sun.net.client.defaultReadTimeout";
static final String TIMEOUTCONNECT = "sun.net.client.defaultConnectTimeout";
static String timeoutRead = getSystemProperty(TTIMEOUTREAD);
static String timeoutConnect = getSystemProperty(TIMEOUTCONNECT);
static String timeoutRead = System.getProperty(TTIMEOUTREAD);
static String timeoutConnect = System.getProperty(TIMEOUTCONNECT);
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
setUp();
timeoutRead = getSystemProperty(TTIMEOUTREAD);
timeoutConnect = getSystemProperty(TIMEOUTCONNECT);
setSystemProperty(TTIMEOUTREAD, "1000");
setSystemProperty(TIMEOUTCONNECT, "1000");
setSystemProperty(SP_ACCESS_EXTERNAL_DTD, "file");
timeoutRead = System.getProperty(TTIMEOUTREAD);
timeoutConnect = System.getProperty(TIMEOUTCONNECT);
System.setProperty(TTIMEOUTREAD, "1000");
System.setProperty(TIMEOUTCONNECT, "1000");
System.setProperty(SP_ACCESS_EXTERNAL_DTD, "file");
}
@AfterClass
public void tearDownClass() throws Exception {
setSystemProperty(TIMEOUTCONNECT, "-1");
setSystemProperty(TTIMEOUTREAD, "-1");
clearSystemProperty(SP_ACCESS_EXTERNAL_DTD);
@AfterAll
public void tearDownClass() {
System.setProperty(TIMEOUTCONNECT, "-1");
System.setProperty(TTIMEOUTREAD, "-1");
System.clearProperty(SP_ACCESS_EXTERNAL_DTD);
}
/*
Verifies the Catalog support on SAXParser.
*/
@Test(dataProvider = "data_SAXC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataSAXC")
public void testSAXC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) {
assertThrows(
SAXParseException.class,
() -> testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on XMLReader.
*/
@Test(dataProvider = "data_SAXC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataSAXC")
public void testXMLReaderC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) {
assertThrows(
SAXParseException.class,
() -> testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on XInclude.
*/
@Test(dataProvider = "data_XIC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataXIC")
public void testXIncludeC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) {
assertThrows(
SAXParseException.class,
() -> testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on DOM parser.
*/
@Test(dataProvider = "data_DOMC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataDOMC")
public void testDOMC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) {
assertThrows(
SAXParseException.class,
() -> testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on XMLStreamReader.
*/
@Test(dataProvider = "data_StAXC", expectedExceptions = XMLStreamException.class)
@ParameterizedTest
@MethodSource("getDataStAX")
public void testStAXC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, XMLResolver resolver, String expected) throws Exception {
testStAXNegative(setUseCatalog, useCatalog, catalog, xml, resolver, expected);
String xml, XMLResolver resolver, String expected) {
assertThrows(
XMLStreamException.class,
() -> testStAXNegative(setUseCatalog, useCatalog, catalog, xml, resolver, expected));
}
/*
Verifies the Catalog support on resolving DTD, xsd import and include in
Schema files.
*/
@Test(dataProvider = "data_SchemaC", expectedExceptions = SAXParseException.class)
@ParameterizedTest
@MethodSource("getDataSchemaC")
public void testValidationC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xsd, LSResourceResolver resolver)
throws Exception {
testValidation(setUseCatalog, useCatalog, catalog, xsd, resolver) ;
String xsd, LSResourceResolver resolver) {
assertThrows(
SAXParseException.class,
() -> testValidation(setUseCatalog, useCatalog, catalog, xsd, resolver));
}
/*
@bug 8158084 8162438 these tests also verifies the fix for 8162438
Verifies the Catalog support on the Schema Validator.
*/
@Test(dataProvider = "data_ValidatorC", expectedExceptions = {SAXException.class, IOException.class})
@ParameterizedTest
@MethodSource("getDataValidator")
public void testValidatorC(boolean setUseCatalog1, boolean setUseCatalog2, boolean useCatalog,
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2)
throws Exception {
testValidator(setUseCatalog1, setUseCatalog2, useCatalog, source,
resolver1, resolver2, catalog1, catalog2);
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2) {
assertThrows(
SAXException.class,
() -> testValidator(setUseCatalog1, setUseCatalog2, useCatalog, source, resolver1, resolver2, catalog1, catalog2));
}
/*
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC", expectedExceptions = TransformerException.class)
@ParameterizedTest
@MethodSource("getDataXSLC")
public void testXSLImportC(boolean setUseCatalog, boolean useCatalog, String catalog, SAXSource xsl, StreamSource xml,
URIResolver resolver, String expected) throws Exception {
testXSLImport(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected);
assertThrows(
TransformerException.class,
() -> testXSLImport(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected));
}
/*
@ -175,18 +196,20 @@ public class CatalogSupport3 extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC", expectedExceptions = TransformerException.class)
@ParameterizedTest
@MethodSource("getDataXSLC")
public void testXSLImportWTemplatesC(boolean setUseCatalog, boolean useCatalog, String catalog,
SAXSource xsl, StreamSource xml,
URIResolver resolver, String expected) throws Exception {
testXSLImportWTemplates(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected);
SAXSource xsl, StreamSource xml,
URIResolver resolver, String expected) throws Exception {
assertThrows(
TransformerException.class,
() -> testXSLImportWTemplates(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected));
}
/*
DataProvider: for testing the SAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_SAXC")
public Object[][] getDataSAXC() {
return new Object[][]{
{true, false, xml_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
@ -198,7 +221,6 @@ public class CatalogSupport3 extends CatalogSupportBase {
DataProvider: for testing XInclude
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_XIC")
public Object[][] getDataXIC() {
return new Object[][]{
{true, false, xml_catalog, xml_xInclude, new MyHandler(elementInXISimple), contentInUIutf8Catalog},
@ -209,7 +231,6 @@ public class CatalogSupport3 extends CatalogSupportBase {
DataProvider: for testing DOM parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_DOMC")
public Object[][] getDataDOMC() {
return new Object[][]{
{true, false, xml_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
@ -220,7 +241,6 @@ public class CatalogSupport3 extends CatalogSupportBase {
DataProvider: for testing the StAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_StAXC")
public Object[][] getDataStAX() {
return new Object[][]{
{true, false, xml_catalog, xml_system, null, "null"},
@ -231,7 +251,6 @@ public class CatalogSupport3 extends CatalogSupportBase {
DataProvider: for testing Schema validation
Data: set use_catalog, use_catalog, catalog file, xsd file, a LSResourceResolver
*/
@DataProvider(name = "data_SchemaC")
public Object[][] getDataSchemaC() {
return new Object[][]{
@ -249,7 +268,6 @@ public class CatalogSupport3 extends CatalogSupportBase {
DataProvider: for testing Schema Validator
Data: source, resolver1, resolver2, catalog1, a catalog2
*/
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);
@ -287,7 +305,6 @@ public class CatalogSupport3 extends CatalogSupportBase {
DataProvider: for testing XSL import and include
Data: set use_catalog, use_catalog, catalog file, xsl file, xml file, a URIResolver, expected
*/
@DataProvider(name = "data_XSLC")
public Object[][] getDataXSLC() {
SAXSource xslSourceDTD = new SAXSource(new InputSource(new StringReader(xsl_includeDTD)));
StreamSource xmlSourceDTD = new StreamSource(new StringReader(xml_xslDTD));

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,11 +23,15 @@
package catalog;
import static jaxp.library.JAXPTestUtilities.clearSystemProperty;
import static jaxp.library.JAXPTestUtilities.setSystemProperty;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import java.io.File;
import java.io.StringReader;
import javax.xml.stream.XMLResolver;
import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
@ -35,19 +39,14 @@ import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.StringReader;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
/**
/*
* @test
* @bug 8158084 8162438 8162442 8166220
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm catalog.CatalogSupport4
* @run junit/othervm catalog.CatalogSupport4
* @summary verifies the overriding over of the USE_CATALOG feature. Extending
* CatalogSupport tests, the USE_CATALOG is turned off system-wide, however,
* a JAXP processor may decide to use Catalog by enabling it through the factory
@ -62,26 +61,28 @@ import org.xml.sax.InputSource;
*
* @author huizhe.wang@oracle.com
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogSupport4 extends CatalogSupportBase {
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
setUp();
//turn off USE_CATALOG system-wide
setSystemProperty(SP_USE_CATALOG, "false");
System.setProperty(SP_USE_CATALOG, "false");
}
@AfterClass
@AfterAll
public void tearDownClass() throws Exception {
clearSystemProperty(SP_USE_CATALOG);
System.clearProperty(SP_USE_CATALOG);
}
/*
Verifies the Catalog support on SAXParser.
*/
@Test(dataProvider = "data_SAXA")
@ParameterizedTest
@MethodSource("getDataSAX")
public void testSAXA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@ -90,7 +91,8 @@ public class CatalogSupport4 extends CatalogSupportBase {
/*
Verifies the Catalog support on XMLReader.
*/
@Test(dataProvider = "data_SAXA")
@ParameterizedTest
@MethodSource("getDataSAX")
public void testXMLReaderA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@ -99,7 +101,8 @@ public class CatalogSupport4 extends CatalogSupportBase {
/*
Verifies the Catalog support on XInclude.
*/
@Test(dataProvider = "data_XIA")
@ParameterizedTest
@MethodSource("getDataXI")
public void testXIncludeA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@ -108,7 +111,8 @@ public class CatalogSupport4 extends CatalogSupportBase {
/*
Verifies the Catalog support on DOM parser.
*/
@Test(dataProvider = "data_DOMA")
@ParameterizedTest
@MethodSource("getDataDOM")
public void testDOMA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected);
@ -117,7 +121,8 @@ public class CatalogSupport4 extends CatalogSupportBase {
/*
Verifies the Catalog support on XMLStreamReader.
*/
@Test(dataProvider = "data_StAXA")
@ParameterizedTest
@MethodSource("getDataStAX")
public void testStAXA(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, XMLResolver resolver, String expected) throws Exception {
testStAX(setUseCatalog, useCatalog, catalog, xml, resolver, expected);
@ -127,7 +132,8 @@ public class CatalogSupport4 extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsd import and include in
Schema files.
*/
@Test(dataProvider = "data_SchemaA")
@ParameterizedTest
@MethodSource("getDataSchema")
public void testValidationA(boolean setUseCatalog, boolean useCatalog,
String catalog, String xsd, LSResourceResolver resolver)
throws Exception {
@ -139,7 +145,8 @@ public class CatalogSupport4 extends CatalogSupportBase {
@bug 8158084 8162438 these tests also verifies the fix for 8162438
Verifies the Catalog support on the Schema Validator.
*/
@Test(dataProvider = "data_ValidatorA")
@ParameterizedTest
@MethodSource("getDataValidator")
public void testValidatorA(boolean setUseCatalog1, boolean setUseCatalog2, boolean useCatalog,
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2)
@ -152,7 +159,8 @@ public class CatalogSupport4 extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLA")
@ParameterizedTest
@MethodSource("getDataXSL")
public void testXSLImportA(boolean setUseCatalog, boolean useCatalog, String catalog,
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected)
throws Exception {
@ -165,7 +173,8 @@ public class CatalogSupport4 extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLA")
@ParameterizedTest
@MethodSource("getDataXSL")
public void testXSLImportWTemplatesA(boolean setUseCatalog, boolean useCatalog,
String catalog, SAXSource xsl, StreamSource xml, URIResolver resolver, String expected)
throws Exception {
@ -176,7 +185,6 @@ public class CatalogSupport4 extends CatalogSupportBase {
DataProvider: for testing the SAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_SAXA")
public Object[][] getDataSAX() {
return new Object[][]{
{true, true, xml_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog},
@ -187,7 +195,6 @@ public class CatalogSupport4 extends CatalogSupportBase {
DataProvider: for testing XInclude
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_XIA")
public Object[][] getDataXI() {
return new Object[][]{
{true, true, xml_catalog, xml_xInclude, new MyHandler(elementInXISimple), contentInUIutf8Catalog},
@ -198,7 +205,6 @@ public class CatalogSupport4 extends CatalogSupportBase {
DataProvider: for testing DOM parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_DOMA")
public Object[][] getDataDOM() {
return new Object[][]{
{true, true, xml_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog},
@ -209,7 +215,6 @@ public class CatalogSupport4 extends CatalogSupportBase {
DataProvider: for testing the StAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_StAXA")
public Object[][] getDataStAX() {
return new Object[][]{
@ -217,15 +222,10 @@ public class CatalogSupport4 extends CatalogSupportBase {
};
}
MyEntityHandler getMyEntityHandler(String elementName, String[] systemIds, InputSource... returnValues) {
return new MyEntityHandler(systemIds, returnValues, elementName);
}
/*
DataProvider: for testing Schema validation
Data: set use_catalog, use_catalog, catalog file, xsd file, a LSResourceResolver
*/
@DataProvider(name = "data_SchemaA")
public Object[][] getDataSchema() {
return new Object[][]{
// for resolving DTD in xsd
@ -241,7 +241,6 @@ public class CatalogSupport4 extends CatalogSupportBase {
DataProvider: for testing Schema Validator
Data: source, resolver1, resolver2, catalog1, a catalog2
*/
@DataProvider(name = "data_ValidatorA")
public Object[][] getDataValidator() {
DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);
@ -270,7 +269,6 @@ public class CatalogSupport4 extends CatalogSupportBase {
DataProvider: for testing XSL import and include
Data: set use_catalog, use_catalog, catalog file, xsl file, xml file, a URIResolver, expected result
*/
@DataProvider(name = "data_XSLA")
public Object[][] getDataXSL() {
// XSLInclude.xsl has one import XSLImport_html.xsl and two includes,
// XSLInclude_header.xsl and XSLInclude_footer.xsl;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,8 +23,15 @@
package catalog;
import java.io.File;
import java.io.StringReader;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.stream.XMLResolver;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Source;
@ -34,19 +41,16 @@ import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.StringReader;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 8158084 8163232 8166220
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm catalog.CatalogSupport5
* @run junit/othervm catalog.CatalogSupport5
* @summary extends CatalogSupport tests, verifies that when errors occur,
* relevant checked Exceptions are returned.
*/
@ -58,12 +62,13 @@ import org.xml.sax.SAXException;
*
* @author huizhe.wang@oracle.com
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogSupport5 extends CatalogSupportBase {
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
setUp();
}
@ -72,77 +77,98 @@ public class CatalogSupport5 extends CatalogSupportBase {
/*
Verifies the Catalog support on SAXParser.
*/
@Test(dataProvider = "data_SAXC", expectedExceptions = SAXException.class)
@ParameterizedTest
@MethodSource("getDataSAXC")
public void testSAXC(boolean setUseCatalog, boolean useCatalog, String catalog, String
xml, MyHandler handler, String expected) throws Exception {
testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected);
xml, MyHandler handler, String expected) {
assertThrows(
SAXException.class,
() -> testSAX(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on XMLReader.
*/
@Test(dataProvider = "data_SAXC", expectedExceptions = SAXException.class)
@ParameterizedTest
@MethodSource("getDataSAXC")
public void testXMLReaderC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) {
assertThrows(
SAXException.class,
() -> testXMLReader(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on XInclude.
*/
@Test(dataProvider = "data_XIC", expectedExceptions = SAXException.class)
@ParameterizedTest
@MethodSource("getDataXIC")
public void testXIncludeC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) {
assertThrows(
SAXException.class,
() -> testXInclude(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on DOM parser.
*/
@Test(dataProvider = "data_DOMC", expectedExceptions = SAXException.class)
@ParameterizedTest
@MethodSource("getDataDOMC")
public void testDOMC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, MyHandler handler, String expected) throws Exception {
testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected);
String xml, MyHandler handler, String expected) {
assertThrows(
SAXException.class,
() -> testDOM(setUseCatalog, useCatalog, catalog, xml, handler, expected));
}
/*
Verifies the Catalog support on XMLStreamReader.
*/
@Test(dataProvider = "data_StAXC", expectedExceptions = XMLStreamException.class)
@ParameterizedTest
@MethodSource("getDataStAX")
public void testStAXC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, XMLResolver resolver, String expected) throws Exception {
testStAX(setUseCatalog, useCatalog, catalog, xml, resolver, expected);
String xml, XMLResolver resolver, String expected) {
assertThrows(
XMLStreamException.class,
() -> testStAX(setUseCatalog, useCatalog, catalog, xml, resolver, expected));
}
/*
Verifies the Catalog support on resolving DTD, xsd import and include in
Schema files.
*/
@Test(dataProvider = "data_SchemaC", expectedExceptions = SAXException.class)
@ParameterizedTest
@MethodSource("getDataSchemaC")
public void testValidationC(boolean setUseCatalog, boolean useCatalog, String catalog,
String xsd, LSResourceResolver resolver)
throws Exception {
testValidation(setUseCatalog, useCatalog, catalog, xsd, resolver) ;
String xsd, LSResourceResolver resolver) {
assertThrows(
SAXException.class,
() -> testValidation(setUseCatalog, useCatalog, catalog, xsd, resolver));
}
@Test(dataProvider = "data_ValidatorC", expectedExceptions = SAXException.class)
@ParameterizedTest
@MethodSource("getDataValidator")
public void testValidatorC(boolean setUseCatalog1, boolean setUseCatalog2, boolean useCatalog,
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2)
throws Exception {
testValidator(setUseCatalog1, setUseCatalog2, useCatalog, source,
resolver1, resolver2, catalog1, catalog2);
Source source, LSResourceResolver resolver1, LSResourceResolver resolver2,
String catalog1, String catalog2) {
assertThrows(
SAXException.class,
() -> testValidator(setUseCatalog1, setUseCatalog2, useCatalog, source, resolver1, resolver2, catalog1, catalog2));
}
/*
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC", expectedExceptions = TransformerException.class)
@ParameterizedTest
@MethodSource("getDataXSLC")
public void testXSLImportC(boolean setUseCatalog, boolean useCatalog, String catalog,
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception {
testXSLImport(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected);
assertThrows(
TransformerException.class,
() -> testXSLImport(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected));
}
/*
@ -150,17 +176,19 @@ public class CatalogSupport5 extends CatalogSupportBase {
Verifies the Catalog support on resolving DTD, xsl import and include in
XSL files.
*/
@Test(dataProvider = "data_XSLC", expectedExceptions = TransformerException.class)
@ParameterizedTest
@MethodSource("getDataXSLC")
public void testXSLImportWTemplatesC(boolean setUseCatalog, boolean useCatalog, String catalog,
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception {
testXSLImportWTemplates(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected);
SAXSource xsl, StreamSource xml, URIResolver resolver, String expected) throws Exception {
assertThrows(
TransformerException.class,
() -> testXSLImportWTemplates(setUseCatalog, useCatalog, catalog, xsl, xml, resolver, expected));
}
/*
DataProvider: for testing the SAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_SAXC")
public Object[][] getDataSAXC() {
return new Object[][]{
{false, true, xml_bogus_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
@ -172,7 +200,6 @@ public class CatalogSupport5 extends CatalogSupportBase {
DataProvider: for testing XInclude
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_XIC")
public Object[][] getDataXIC() {
return new Object[][]{
{false, true, xml_bogus_catalog, xml_xInclude, new MyHandler(elementInXISimple), contentInUIutf8Catalog},
@ -183,7 +210,6 @@ public class CatalogSupport5 extends CatalogSupportBase {
DataProvider: for testing DOM parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_DOMC")
public Object[][] getDataDOMC() {
return new Object[][]{
{false, true, xml_bogus_catalog, xml_system, new MyHandler(elementInSystem), expectedWCatalog}
@ -194,7 +220,6 @@ public class CatalogSupport5 extends CatalogSupportBase {
DataProvider: for testing the StAX parser
Data: set use_catalog, use_catalog, catalog file, xml file, handler, expected result string
*/
@DataProvider(name = "data_StAXC")
public Object[][] getDataStAX() {
return new Object[][]{
@ -206,7 +231,6 @@ public class CatalogSupport5 extends CatalogSupportBase {
DataProvider: for testing Schema validation
Data: set use_catalog, use_catalog, catalog file, xsd file, a LSResourceResolver
*/
@DataProvider(name = "data_SchemaC")
public Object[][] getDataSchemaC() {
return new Object[][]{
@ -224,7 +248,6 @@ public class CatalogSupport5 extends CatalogSupportBase {
Data: setUseCatalog1, setUseCatalog2, useCatalog, source, resolver1, resolver2,
catalog1, catalog2
*/
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);
@ -253,7 +276,6 @@ public class CatalogSupport5 extends CatalogSupportBase {
DataProvider: for testing XSL import and include
Data: set use_catalog, use_catalog, catalog file, xsl file, xml file, a URIResolver, expected
*/
@DataProvider(name = "data_XSLC")
public Object[][] getDataXSLC() {
SAXSource xslSourceDTD = new SAXSource(new InputSource(new StringReader(xsl_includeDTD)));
StreamSource xmlSourceDTD = new StreamSource(new StringReader(xml_xslDTD));

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,25 +23,17 @@
package catalog;
import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DefaultHandler2;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.ProtectionDomain;
import javax.xml.XMLConstants;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogResolver;
@ -68,17 +60,26 @@ import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.testng.Assert;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DefaultHandler2;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.ProtectionDomain;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Base class:
@ -99,7 +100,7 @@ public class CatalogSupportBase {
protected void setUp() {
String file1 = getClass().getResource("CatalogSupport.xml").getFile();
if (getSystemProperty("os.name").contains("Windows")) {
if (System.getProperty("os.name").contains("Windows")) {
filepath = file1.substring(1, file1.lastIndexOf("/") + 1);
slash = "/";
} else {
@ -285,7 +286,7 @@ public class CatalogSupportBase {
SAXParser parser = getSAXParser(setUseCatalog, useCatalog, catalog);
parser.parse(xml, handler);
Assert.assertEquals(handler.getResult().trim(), expected);
assertEquals(expected, handler.getResult().trim());
}
/*
@ -298,7 +299,7 @@ public class CatalogSupportBase {
reader.setContentHandler(handler);
reader.setEntityResolver(handler);
reader.parse(xml);
Assert.assertEquals(handler.getResult().trim(), expected);
assertEquals(expected, handler.getResult().trim());
}
/*
@ -312,7 +313,7 @@ public class CatalogSupportBase {
// is thrown if handler == null.
if (handler != null) {
debugPrint("handler.result:" + handler.getResult());
Assert.assertEquals(handler.getResult().trim(), expected);
assertEquals(expected, handler.getResult().trim());
}
}
@ -327,7 +328,7 @@ public class CatalogSupportBase {
Node node = doc.getElementsByTagName(elementInSystem).item(0);
String result = node.getFirstChild().getTextContent();
Assert.assertEquals(result.trim(), expected);
assertEquals(expected, result.trim());
}
/*
@ -336,10 +337,10 @@ public class CatalogSupportBase {
public void testStAX(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, XMLResolver resolver, String expected) throws Exception {
XMLStreamReader streamReader = getStreamReader(
setUseCatalog, useCatalog, catalog, xml, resolver);
String text = getText(streamReader, XMLStreamConstants.CHARACTERS);
Assert.assertEquals(text.trim(), expected);
XMLStreamReader streamReader = getStreamReader(
setUseCatalog, useCatalog, catalog, xml, resolver);
String text = getText(streamReader, XMLStreamConstants.CHARACTERS);
assertEquals(expected, text.trim());
}
/*
@ -349,10 +350,10 @@ public class CatalogSupportBase {
public void testStAXNegative(boolean setUseCatalog, boolean useCatalog, String catalog,
String xml, XMLResolver resolver, String expected) throws Exception {
XMLStreamReader streamReader = getStreamReader(
setUseCatalog, useCatalog, catalog, xml, resolver);
String text = getText(streamReader, XMLStreamConstants.ENTITY_REFERENCE);
Assert.assertEquals(text.trim(), expected);
XMLStreamReader streamReader = getStreamReader(
setUseCatalog, useCatalog, catalog, xml, resolver);
String text = getText(streamReader, XMLStreamConstants.ENTITY_REFERENCE);
assertEquals(expected, text.trim());
}
/*
@ -381,7 +382,6 @@ public class CatalogSupportBase {
} else {
Schema schema = factory.newSchema(new StreamSource(new StringReader(xsd)));
}
success("XMLSchema.dtd and datatypes.dtd are resolved.");
}
/**
@ -439,8 +439,7 @@ public class CatalogSupportBase {
StringWriter out = new StringWriter();
transformer.transform(xml, new StreamResult(out));
debugPrint("out:\n" + out.toString());
Assert.assertTrue(out.toString().contains(expected), "testXSLImport");
assertTrue(out.toString().contains(expected), "Output did not contain '" + expected + "':\n" + out);
}
/*
@ -455,7 +454,7 @@ public class CatalogSupportBase {
Transformer transformer = factory.newTemplates(xsl).newTransformer();
StringWriter out = new StringWriter();
transformer.transform(xml, new StreamResult(out));
Assert.assertTrue(out.toString().contains(expected), "testXSLImportWTemplates");
assertTrue(out.toString().contains(expected), "Output did not contain '" + expected + "':\n" + out);
}
/**
@ -688,16 +687,6 @@ public class CatalogSupportBase {
return factory;
}
void fail(String msg) {
System.out.println("Test failed:");
System.out.println(msg);
}
void success(String msg) {
System.out.println("Test succeded:");
System.out.println(msg);
}
void debugPrint(String msg) {
if (debug) {
System.out.println(msg);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -22,14 +22,19 @@
*/
package catalog;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.nio.file.Paths;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DefaultHandler2;
import javax.xml.XMLConstants;
import javax.xml.catalog.Catalog;
import javax.xml.catalog.CatalogException;
@ -52,26 +57,29 @@ import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import static jaxp.library.JAXPTestUtilities.clearSystemProperty;
import static jaxp.library.JAXPTestUtilities.setSystemProperty;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DefaultHandler2;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @bug 8081248 8144966 8146606 8146237 8150969 8151162 8152527 8154220 8163232
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm catalog.CatalogTest
* @run junit/othervm catalog.CatalogTest
* @summary Tests basic Catalog functions.
*/
@TestInstance(Lifecycle.PER_CLASS)
public class CatalogTest extends CatalogSupportBase {
static final String KEY_FILES = "javax.xml.catalog.files";
@ -79,7 +87,7 @@ public class CatalogTest extends CatalogSupportBase {
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
super.setUp();
}
@ -98,8 +106,9 @@ public class CatalogTest extends CatalogSupportBase {
/*
* Verifies the support for org.xml.sax.EntityResolver.
* Expected: the parser returns the expected string.
*/
@Test(dataProvider = "supportXMLResolver")
*/
@ParameterizedTest
@MethodSource("supportXMLResolver")
public void supportEntityResolver(URI catalogFile, String xml, String expected) throws Exception {
String xmlSource = getClass().getResource(xml).getFile();
@ -108,14 +117,15 @@ public class CatalogTest extends CatalogSupportBase {
SAXParser parser = getSAXParser(false, true, null);
parser.parse(xmlSource, handler);
Assert.assertEquals(handler.getResult().trim(), expected);
assertEquals(expected, handler.getResult().trim());
}
/*
* Verifies the support for javax.xml.stream.XMLResolver.
* Expected: the parser returns the expected string.
*/
@Test(dataProvider = "supportXMLResolver")
*/
@ParameterizedTest
@MethodSource("supportXMLResolver")
public void supportXMLResolver(URI catalogFile, String xml, String expected) throws Exception {
String xmlSource = getClass().getResource(xml).getFile();
@ -140,15 +150,16 @@ public class CatalogTest extends CatalogSupportBase {
}
System.out.println(": expected [" + expected + "] <> actual [" + result.trim() + "]");
Assert.assertEquals(result.trim(), expected);
assertEquals(expected, result.trim());
}
/*
* Verifies the support for org.w3c.dom.ls.LSResourceResolver by ShemaFactory.
* Success: parsing goes through with no error
* Fail: throws Exception if references are not resolved (by the CatalogResolver)
*/
@Test(dataProvider = "supportLSResourceResolver")
*/
@ParameterizedTest
@MethodSource("supportLSResourceResolver")
public void supportLSResourceResolver(URI catalogFile, Source schemaSource) throws SAXException {
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
@ -163,8 +174,9 @@ public class CatalogTest extends CatalogSupportBase {
* Verifies the support for org.w3c.dom.ls.LSResourceResolver by Validator.
* Success: parsing goes through with no error
* Fail: throws Exception if references are not resolved (by the CatalogResolver)
*/
@Test(dataProvider = "supportLSResourceResolver1")
*/
@ParameterizedTest
@MethodSource("supportLSResourceResolver1")
public void supportLSResourceResolver1(URI catalogFile, Source source) throws Exception {
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
@ -179,20 +191,21 @@ public class CatalogTest extends CatalogSupportBase {
* Verifies the support for javax.xml.transform.URIResolver.
* Success: parsing goes through with no error
* Fail: throws Exception if references are not resolved (by the CatalogResolver)
*/
@Test(dataProvider = "supportURIResolver")
*/
@ParameterizedTest
@MethodSource("supportURIResolver")
public void supportURIResolver(URI catalogFile, Source xsl, Source xml, String expected) throws Exception {
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
TransformerFactory factory = TransformerFactory.newInstance();
factory.setURIResolver(cr);
Transformer transformer = factory.newTransformer(xsl);
StringWriter out = new StringWriter();
transformer.transform(xml, new StreamResult(out));
if (expected != null) {
Assert.assertTrue(out.toString().contains(expected), "supportURIResolver");
}
TransformerFactory factory = TransformerFactory.newInstance();
factory.setURIResolver(cr);
Transformer transformer = factory.newTransformer(xsl);
StringWriter out = new StringWriter();
transformer.transform(xml, new StreamResult(out));
if (expected != null) {
assertTrue(out.toString().contains(expected), "supportURIResolver");
}
}
/*
@ -200,7 +213,6 @@ public class CatalogTest extends CatalogSupportBase {
Data columns:
catalog filepath, xml source file, expected result
*/
@DataProvider(name = "supportXMLResolver")
public Object[][] supportXMLResolver() throws Exception {
URI catalogFile = getClass().getResource("catalog.xml").toURI();
URI catalogFileUri = getClass().getResource("catalog_uri.xml").toURI();
@ -228,7 +240,6 @@ public class CatalogTest extends CatalogSupportBase {
Data columns:
catalog filepath, schema source file
*/
@DataProvider(name = "supportLSResourceResolver")
public Object[][] supportLSResourceResolver() throws Exception {
URI catalogFile = getClass().getResource("CatalogSupport.xml").toURI();
URI catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").toURI();
@ -252,7 +263,6 @@ public class CatalogTest extends CatalogSupportBase {
Data columns:
catalog filepath, source file
*/
@DataProvider(name = "supportLSResourceResolver1")
public Object[][] supportLSResourceResolver1() throws Exception {
URI catalogFile = getClass().getResource("CatalogSupport.xml").toURI();
URI catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").toURI();
@ -275,7 +285,6 @@ public class CatalogTest extends CatalogSupportBase {
Data columns:
catalog filepath, xsl source, xml source file
*/
@DataProvider(name = "supportURIResolver")
public Object[][] supportURIResolver() throws Exception {
URI catalogFile = getClass().getResource("CatalogSupport.xml").toURI();
URI catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").toURI();
@ -303,10 +312,12 @@ public class CatalogTest extends CatalogSupportBase {
* requires a system identifier on all external entities, so this value is
* always specified.
*/
@Test(expectedExceptions = NullPointerException.class)
@Test
public void sysIdCantBeNull() {
CatalogResolver catalogResolver = CatalogManager.catalogResolver(CatalogFeatures.defaults());
InputSource is = catalogResolver.resolveEntity("-//FOO//DTD XML Dummy V0.0//EN", null);
assertThrows(
NullPointerException.class,
() -> catalogResolver.resolveEntity("-//FOO//DTD XML Dummy V0.0//EN", null));
}
/*
@ -318,14 +329,15 @@ public class CatalogTest extends CatalogSupportBase {
* copying the JCK test and its dataProvider. This test may be reused for
* other cases in that test.
*/
@Test(dataProvider = "resolveUri")
@ParameterizedTest
@MethodSource("getDataForUriResolver")
public void testMatch1(String cFile, String href, String expectedFile,
String expectedUri, String msg) throws Exception {
URI catalogFile = getClass().getResource(cFile).toURI();
CatalogResolver cur = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
Source source = cur.resolve(href, null);
Assert.assertNotNull(source, "Source returned is null");
Assert.assertEquals(expectedUri, source.getSystemId(), msg);
assertNotNull(source, "Source returned is null");
assertEquals(expectedUri, source.getSystemId(), msg);
}
/*
@ -333,20 +345,21 @@ public class CatalogTest extends CatalogSupportBase {
* Verifies that the file input is validated properly. Valid input includes
* multiple file paths separated by semicolon.
*/
@Test(dataProvider = "hierarchyOfCatFilesData")
@ParameterizedTest
@MethodSource("getHierarchyOfCatFilesData")
public void hierarchyOfCatFiles2(String systemId, String expectedUri) {
String file1 = getClass().getResource("first_cat.xml").toExternalForm();
String file2 = getClass().getResource("second_cat.xml").toExternalForm();
String files = file1 + ";" + file2;
try {
setSystemProperty(KEY_FILES, files);
System.setProperty(KEY_FILES, files);
CatalogResolver catalogResolver = CatalogManager.catalogResolver(CatalogFeatures.defaults());
String sysId = catalogResolver.resolveEntity(null, systemId).getSystemId();
Assert.assertEquals(sysId, Paths.get(filepath + expectedUri).toUri().toString().replace("///", "/"),
"System ID match not right");
String actualSysId = catalogResolver.resolveEntity(null, systemId).getSystemId();
String expectedSysId = Paths.get(filepath + expectedUri).toUri().toString().replace("///", "/");
assertEquals(expectedSysId, actualSysId, "System ID match not right");
} finally {
clearSystemProperty(KEY_FILES);
System.clearProperty(KEY_FILES);
}
}
@ -357,16 +370,17 @@ public class CatalogTest extends CatalogSupportBase {
* Verifies that the CatalogResolver resolves a publicId and/or systemId as
* expected.
*/
@Test(dataProvider = "resolveEntity")
@ParameterizedTest
@MethodSource("getDataForMatchingBothIds")
public void testMatch1(String cfile, String prefer, String sysId, String pubId,
String expectedUri, String expectedFile, String msg) throws Exception {
URI catalogFile = getClass().getResource(cfile).toURI();
CatalogFeatures features = CatalogFeatures.builder().with(CatalogFeatures.Feature.PREFER, prefer).build();
CatalogResolver catalogResolver = CatalogManager.catalogResolver(features, catalogFile);
InputSource is = catalogResolver.resolveEntity(pubId, sysId);
Assert.assertNotNull(is, msg);
assertNotNull(is, msg);
String expected = (expectedUri == null) ? expectedFile : expectedUri;
Assert.assertEquals(expected, is.getSystemId(), msg);
assertEquals(expected, is.getSystemId(), msg);
}
/*
@ -374,7 +388,8 @@ public class CatalogTest extends CatalogSupportBase {
* Verifies that the Catalog matches specified publicId or systemId and returns
* results as expected.
*/
@Test(dataProvider = "matchWithPrefer")
@ParameterizedTest
@MethodSource("getDataForMatch")
public void matchWithPrefer(String prefer, String cfile, String publicId,
String systemId, String expected) throws Exception {
URI catalogFile = getClass().getResource(cfile).toURI();
@ -387,7 +402,7 @@ public class CatalogTest extends CatalogSupportBase {
} else {
result = c.matchSystem(systemId);
}
Assert.assertEquals(expected, result);
assertEquals(expected, result);
}
/*
@ -401,7 +416,8 @@ public class CatalogTest extends CatalogSupportBase {
* attempts to resolve with a public entry if no matching
* system entry is found.
*/
@Test(dataProvider = "resolveWithPrefer")
@ParameterizedTest
@MethodSource("getDataForResolve")
public void resolveWithPrefer(String prefer, String cfile, String publicId,
String systemId, String expected) throws Exception {
URI catalogFile = getClass().getResource(cfile).toURI();
@ -411,7 +427,7 @@ public class CatalogTest extends CatalogSupportBase {
.build();
CatalogResolver catalogResolver = CatalogManager.catalogResolver(f, catalogFile);
String result = catalogResolver.resolveEntity(publicId, systemId).getSystemId();
Assert.assertEquals(expected, result);
assertEquals(expected, result);
}
/**
@ -420,7 +436,8 @@ public class CatalogTest extends CatalogSupportBase {
* over other settings, in which case, whether next and delegate Catalogs will
* be loaded is determined by the defer attribute.
*/
@Test(dataProvider = "invalidAltCatalogs", expectedExceptions = CatalogException.class)
@ParameterizedTest
@MethodSource("getInvalidAltCatalogs")
public void testDeferAltCatalogs(String file) throws Exception {
URI catalogFile = getClass().getResource(file).toURI();
CatalogFeatures features = CatalogFeatures.builder().
@ -431,7 +448,7 @@ public class CatalogTest extends CatalogSupportBase {
the parent catalog will try to load the alt catalog, which will fail
since it points to an invalid catalog.
*/
Catalog catalog = CatalogManager.catalog(features, catalogFile);
assertThrows(CatalogException.class, () -> CatalogManager.catalog(features, catalogFile));
}
@ -443,22 +460,17 @@ public class CatalogTest extends CatalogSupportBase {
public void testJDK8146237() throws Exception {
URI catalogFile = getClass().getResource("JDK8146237_catalog.xml").toURI();
try {
CatalogFeatures features = CatalogFeatures.builder()
.with(CatalogFeatures.Feature.PREFER, "system")
.build();
Catalog catalog = CatalogManager.catalog(features, catalogFile);
CatalogResolver catalogResolver = CatalogManager.catalogResolver(catalog);
String actualSystemId = catalogResolver.resolveEntity(
"-//FOO//DTD XML Dummy V0.0//EN",
"http://www.oracle.com/alt1sys.dtd")
.getSystemId();
Assert.assertTrue(actualSystemId.contains("dummy.dtd"),
"Resulting id should contain dummy.dtd, indicating a match by publicId");
} catch (Exception e) {
Assert.fail(e.getMessage());
}
CatalogFeatures features = CatalogFeatures.builder()
.with(CatalogFeatures.Feature.PREFER, "system")
.build();
Catalog catalog = CatalogManager.catalog(features, catalogFile);
CatalogResolver catalogResolver = CatalogManager.catalogResolver(catalog);
String actualSystemId = catalogResolver.resolveEntity(
"-//FOO//DTD XML Dummy V0.0//EN",
"http://www.oracle.com/alt1sys.dtd")
.getSystemId();
assertTrue(actualSystemId.contains("dummy.dtd"),
"Resulting id should contain dummy.dtd, indicating a match by publicId");
}
/*
@ -469,14 +481,9 @@ public class CatalogTest extends CatalogSupportBase {
public void testRewriteSystem() throws Exception {
URI catalog = getClass().getResource("rewriteCatalog.xml").toURI();
try {
CatalogResolver resolver = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalog);
String actualSystemId = resolver.resolveEntity(null, "http://remote.com/dtd/book.dtd").getSystemId();
Assert.assertTrue(!actualSystemId.contains("//"), "result contains duplicate slashes");
} catch (Exception e) {
Assert.fail(e.getMessage());
}
CatalogResolver resolver = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalog);
String actualSystemId = resolver.resolveEntity(null, "http://remote.com/dtd/book.dtd").getSystemId();
assertFalse(actualSystemId.contains("//"), "result contains duplicate slashes");
}
/*
@ -487,23 +494,18 @@ public class CatalogTest extends CatalogSupportBase {
public void testRewriteUri() throws Exception {
URI catalog = getClass().getResource("rewriteCatalog.xml").toURI();
try {
CatalogResolver resolver = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalog);
String actualSystemId = resolver.resolve("http://remote.com/import/import.xsl", null).getSystemId();
Assert.assertTrue(!actualSystemId.contains("//"), "result contains duplicate slashes");
} catch (Exception e) {
Assert.fail(e.getMessage());
}
CatalogResolver resolver = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalog);
String actualSystemId = resolver.resolve("http://remote.com/import/import.xsl", null).getSystemId();
assertFalse(actualSystemId.contains("//"), "result contains duplicate slashes");
}
/*
@bug 8144966
Verifies that passing null as CatalogFeatures will result in a NPE.
*/
@Test(expectedExceptions = NullPointerException.class)
@Test
public void testFeatureNull() {
CatalogResolver resolver = CatalogManager.catalogResolver((CatalogFeatures)null, (URI)null);
assertThrows(NullPointerException.class, () -> CatalogManager.catalogResolver((CatalogFeatures) null, (URI) null));
}
@ -511,10 +513,11 @@ public class CatalogTest extends CatalogSupportBase {
@bug 8144966
Verifies that passing null as the URI will result in a NPE.
*/
@Test(expectedExceptions = NullPointerException.class)
@Test
public void testPathNull() {
URI uri = null;
CatalogResolver resolver = CatalogManager.catalogResolver(CatalogFeatures.defaults(), uri);
assertThrows(
NullPointerException.class,
() -> CatalogManager.catalogResolver(CatalogFeatures.defaults(), (URI) null));
}
/*
@ -523,7 +526,8 @@ public class CatalogTest extends CatalogSupportBase {
is successful, the Handler shall return the value of the entity reference
that matches the expected value.
*/
@Test(dataProvider = "catalog")
@ParameterizedTest
@MethodSource("getCatalog")
public void testCatalogResolver(String test, String expected, String catalogFile,
String xml, SAXParser saxParser) throws Exception {
URI catalog = null;
@ -531,18 +535,14 @@ public class CatalogTest extends CatalogSupportBase {
catalog = getClass().getResource(catalogFile).toURI();
}
String url = getClass().getResource(xml).getFile();
try {
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalog);
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(cr);
MyHandler handler = new MyHandler(saxParser);
reader.setContentHandler(handler);
reader.parse(url);
System.out.println(test + ": expected [" + expected + "] <> actual [" + handler.getResult() + "]");
Assert.assertEquals(handler.getResult(), expected);
} catch (SAXException | IOException e) {
Assert.fail(e.getMessage());
}
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalog);
XMLReader reader = saxParser.getXMLReader();
reader.setEntityResolver(cr);
MyHandler handler = new MyHandler(saxParser);
reader.setContentHandler(handler);
reader.parse(url);
System.out.println(test + ": expected [" + expected + "] <> actual [" + handler.getResult() + "]");
assertEquals(expected, handler.getResult());
}
/*
@ -564,7 +564,7 @@ public class CatalogTest extends CatalogSupportBase {
} catch (Exception e) {
String msg = e.getMessage();
if (msg != null) {
Assert.assertTrue(msg.contains(expectedMsgId),
assertTrue(msg.contains(expectedMsgId),
"Message shall contain the corrent message ID " + expectedMsgId);
}
}
@ -585,19 +585,15 @@ public class CatalogTest extends CatalogSupportBase {
.build();
String test = "testInvalidCatalog";
try {
CatalogResolver resolver = CatalogManager.catalogResolver(f);
String actualSystemId = resolver.resolveEntity(
null,
"http://remote/xml/dtd/sys/alice/docAlice.dtd")
.getSystemId();
System.out.println("testIgnoreInvalidCatalog: expected [null]");
System.out.println("testIgnoreInvalidCatalog: expected [null]");
System.out.println("actual [" + actualSystemId + "]");
Assert.assertEquals(actualSystemId, null);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
CatalogResolver resolver = CatalogManager.catalogResolver(f);
String actualSystemId = resolver.resolveEntity(
null,
"http://remote/xml/dtd/sys/alice/docAlice.dtd")
.getSystemId();
System.out.println("testIgnoreInvalidCatalog: expected [null]");
System.out.println("testIgnoreInvalidCatalog: expected [null]");
System.out.println("actual [" + actualSystemId + "]");
assertNull(actualSystemId);
}
@ -608,7 +604,6 @@ public class CatalogTest extends CatalogSupportBase {
This DataProvider is copied from JCK ResolveTests' dataMatch1
*/
@DataProvider(name = "resolveUri")
public Object[][] getDataForUriResolver() {
return new Object[][]{
{"uri.xml",
@ -623,7 +618,6 @@ public class CatalogTest extends CatalogSupportBase {
DataProvider: used to verify hierarchical catalogs. Refer to JCK test
hierarchyOfCatFiles2.
*/
@DataProvider(name = "hierarchyOfCatFilesData")
public Object[][] getHierarchyOfCatFilesData() {
return new Object[][]{
{"http://www.oracle.com/sequence.dtd", "first.dtd"},
@ -637,7 +631,6 @@ public class CatalogTest extends CatalogSupportBase {
Data columns:
catalog, prefer, systemId, publicId, expectedUri, expectedFile, msg
*/
@DataProvider(name = "resolveEntity")
public Object[][] getDataForMatchingBothIds() {
String expected = "http://www.groupxmlbase.com/dtds/rewrite.dtd";
return new Object[][]{
@ -658,7 +651,6 @@ public class CatalogTest extends CatalogSupportBase {
Data columns:
prefer, catalog, publicId, systemId, expected result
*/
@DataProvider(name = "matchWithPrefer")
public Object[][] getDataForMatch() {
return new Object[][]{
{"public", "pubOnly.xml", id, "", "http://local/base/dtd/public.dtd"},
@ -682,7 +674,6 @@ public class CatalogTest extends CatalogSupportBase {
Data columns:
prefer, catalog, publicId, systemId, expected result
*/
@DataProvider(name = "resolveWithPrefer")
public Object[][] getDataForResolve() {
return new Object[][]{
{"system", "pubOnly.xml", id, "", "http://local/base/dtd/public.dtd"},
@ -709,11 +700,10 @@ public class CatalogTest extends CatalogSupportBase {
DataProvider: catalogs that contain invalid next or delegate catalogs.
The defer attribute is set to false.
*/
@DataProvider(name = "invalidAltCatalogs")
public Object[][] getCatalogs() {
return new Object[][]{
{"defer_false_2.xml"},
{"defer_del_false.xml"}
public Object[][] getInvalidAltCatalogs() {
return new Object[][] {
{ "defer_false_2.xml" },
{ "defer_del_false.xml" }
};
}
@ -722,7 +712,6 @@ public class CatalogTest extends CatalogSupportBase {
DataProvider: provides test name, expected string, the catalog, and XML
document.
*/
@DataProvider(name = "catalog")
public Object[][] getCatalog() {
return new Object[][]{
{"testSystem", "Test system entry", "catalog.xml", "system.xml", getParser()},

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -22,31 +22,36 @@
*/
package catalog;
import java.net.URI;
import java.nio.file.Paths;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import javax.xml.transform.Source;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.net.URI;
import java.nio.file.Paths;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @bug 8215330
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng catalog.GroupTest
* @run junit catalog.GroupTest
* @summary Tests catalog with Group entries.
*/
@TestInstance(Lifecycle.PER_CLASS)
public class GroupTest extends CatalogSupportBase {
String catalogGroup;
/*
* Initializing fields
*/
@BeforeClass
@BeforeAll
public void setUpClass() throws Exception {
super.setUp();
catalogGroup = Paths.get(filepath + "GroupTest.xml").toUri().toASCIIString();
@ -60,13 +65,14 @@ public class GroupTest extends CatalogSupportBase {
* @param expected the expected result string
* @throws Exception
*/
@Test(dataProvider = "data_group")
@ParameterizedTest
@MethodSource("getDataDOM")
public void testGroup(String catalog, String uri, String expected) throws Exception {
CatalogResolver resolver = CatalogManager.catalogResolver(
CatalogFeatures.defaults(), URI.create(catalog));
Source src = resolver.resolve(uri, null);
Assert.assertTrue(src.getSystemId().endsWith(expected), "uriSuffix match");
assertTrue(src.getSystemId().endsWith(expected), "uriSuffix match");
}
@ -74,7 +80,6 @@ public class GroupTest extends CatalogSupportBase {
DataProvider: for testing catalogs with group entries
Data: catalog file, uri, expected result string
*/
@DataProvider(name = "data_group")
public Object[][] getDataDOM() {
return new Object[][]{
{catalogGroup, "http://openjdk_java_net/xml/catalog/A/CommonFileA1.xml", "LocalFileA1.xml"},

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,26 +23,28 @@
package datatype;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 6320118
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm datatype.Bug6320118
* @run junit/othervm datatype.Bug6320118
* @summary Test xml datatype XMLGregorianCalendar.
*/
public class Bug6320118 {
DatatypeFactory df;
@BeforeClass
@BeforeEach
public void createDataTypeFactory() throws DatatypeConfigurationException {
df = DatatypeFactory.newInstance();
}
@ -50,30 +52,30 @@ public class Bug6320118 {
@Test
public void test1() {
XMLGregorianCalendar calendar = df.newXMLGregorianCalendar(1970, 1, 1, 24, 0, 0, 0, 0);
Assert.assertEquals(calendar.getYear(), 1970);
Assert.assertEquals(calendar.getMonth(), 1);
Assert.assertEquals(calendar.getDay(), 2);
Assert.assertEquals(calendar.getHour(), 0, "hour 24 needs to be treated as hour 0 of next day");
assertEquals(1970, calendar.getYear());
assertEquals(1, calendar.getMonth());
assertEquals(2, calendar.getDay());
assertEquals(0, calendar.getHour(), "hour 24 needs to be treated as hour 0 of next day");
}
@Test
public void test2() {
XMLGregorianCalendar calendar = df.newXMLGregorianCalendarTime(24, 0, 0, 0);
Assert.assertEquals(calendar.getHour(), 0, "hour 24 needs to be treated as hour 0 of next day");
assertEquals(0, calendar.getHour(), "hour 24 needs to be treated as hour 0 of next day");
}
@Test(expectedExceptions = IllegalArgumentException.class)
@Test
public void test3() {
XMLGregorianCalendar calendar = df.newXMLGregorianCalendar();
// Must fail as other params are not 0 but undefined
calendar.setHour(24);
assertThrows(IllegalArgumentException.class, () -> calendar.setHour(24));
}
@Test
public void test4() {
XMLGregorianCalendar calendar = df.newXMLGregorianCalendar();
calendar.setTime(24, 0, 0, 0);
Assert.assertEquals(calendar.getHour(), 0, "hour 24 needs to be treated as hour 0 of next day");
assertEquals(0, calendar.getHour(), "hour 24 needs to be treated as hour 0 of next day");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,18 +23,19 @@
package datatype;
import org.junit.jupiter.api.Test;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/*
* @test
* @bug 6937951
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm datatype.Bug6937951Test
* @run junit/othervm datatype.Bug6937951Test
* @summary Test midnight is same as the start of the next day in XMLGregorianCalendar.
*/
public class Bug6937951Test {
@ -44,13 +45,10 @@ public class Bug6937951Test {
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");
assertEquals(2000, c1.getYear());
assertEquals(0, c1.getHour());
assertEquals(c1, c2, "hour 24 should treated as equal to hour 0 of the next day");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,31 +23,29 @@
package datatype;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.namespace.QName;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/*
* @test
* @bug 6937964
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm datatype.Bug6937964Test
* @run junit/othervm datatype.Bug6937964Test
* @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.
*/
@ -57,7 +55,7 @@ public class Bug6937964Test {
public void test() throws DatatypeConfigurationException {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationYearMonth("P20Y15M");
System.out.println(d.getYears() == 21 ? "pass" : "fail");
assertEquals(21, d.getYears());
}
@Test
@ -65,7 +63,7 @@ public class Bug6937964Test {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationYearMonth("P20Y15M");
int years = d.getYears();
Assert.assertEquals(years, 21, "Return value should be normalized");
assertEquals(21, years, "Return value should be normalized");
}
@Test
@ -73,8 +71,7 @@ public class Bug6937964Test {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationYearMonth(671976000000L);
int years = d.getYears();
System.out.println("Years: " + years);
Assert.assertEquals(years, 21, "Return value should be normalized");
assertEquals(21, years, "Return value should be normalized");
}
@Test
@ -84,7 +81,7 @@ public class Bug6937964Test {
BigInteger mon = new BigInteger("15");
Duration d = dtf.newDurationYearMonth(true, year, mon);
int years = d.getYears();
Assert.assertEquals(years, 21, "Return value should be normalized");
assertEquals(21, years, "Return value should be normalized");
}
@Test
@ -92,7 +89,7 @@ public class Bug6937964Test {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationYearMonth(true, 20, 15);
int years = d.getYears();
Assert.assertEquals(years, 21, "Return value should be normalized");
assertEquals(21, years, "Return value should be normalized");
}
@Test
@ -100,7 +97,7 @@ public class Bug6937964Test {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationDayTime("P1DT23H59M65S");
int days = d.getDays();
Assert.assertEquals(days, 2, "Return value should be normalized");
assertEquals(2, days, "Return value should be normalized");
}
@Test
@ -108,7 +105,7 @@ public class Bug6937964Test {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationDayTime(172805000L);
int days = d.getDays();
Assert.assertEquals(days, 2, "Return value should be normalized");
assertEquals(2, days, "Return value should be normalized");
}
@Test
@ -120,8 +117,7 @@ public class Bug6937964Test {
BigInteger sec = new BigInteger("65");
Duration d = dtf.newDurationDayTime(true, day, hour, min, sec);
int days = d.getDays();
System.out.println("Days: " + days);
Assert.assertEquals(days, 2, "Return value should be normalized");
assertEquals(2, days, "Return value should be normalized");
}
@Test
@ -129,117 +125,88 @@ public class Bug6937964Test {
DatatypeFactory dtf = DatatypeFactory.newInstance();
Duration d = dtf.newDurationDayTime(true, 1, 23, 59, 65);
int days = d.getDays();
System.out.println("Days: " + days);
Assert.assertEquals(days, 2, "Return value should be normalized");
assertEquals(2, days, "Return value should be normalized");
}
@DataProvider(name = "lexicalvalues")
public Object[][] actualAndExpectedLexicals() {
Object actualAndExpected [][] = {
{"P13M", "P1Y1M"},
{"-P13M", "-P1Y1M"},
{"P1Y", "P1Y"},
{"-P1Y", "-P1Y"},
{"P1Y25M", "P3Y1M"},
{"-P1Y25M", "-P3Y1M"}
public static Object[][] lexicalvalues() {
return new Object[][] {
{ "P13M", "P1Y1M" },
{ "-P13M", "-P1Y1M" },
{ "P1Y", "P1Y" },
{ "-P1Y", "-P1Y" },
{ "P1Y25M", "P3Y1M" },
{ "-P1Y25M", "-P3Y1M" }
};
return actualAndExpected;
}
@Test(dataProvider = "lexicalvalues")
public void testNewDurationYearMonthLexicalRepresentation1(String actualLex, String expectedLex) {
/**
* Lexical test values to test.
*/
DatatypeFactory datatypeFactory = null;
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
System.err.println("DatatypeFactory created: " + datatypeFactory.toString());
}
if (DEBUG) {
System.err.println("testing value: \"" + actualLex + "\", expecting: \"" + expectedLex + "\"");
}
@ParameterizedTest
@MethodSource("lexicalvalues")
public void testNewDurationYearMonthLexicalRepresentation1(String actualLex, String expectedLex)
throws DatatypeConfigurationException {
DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
try {
Duration duration = datatypeFactory.newDurationYearMonth(actualLex);
if (DEBUG) {
System.err.println("Duration created: \"" + duration.toString() + "\"");
}
// was this expected to fail?
Assert.assertNotEquals(expectedLex, TEST_VALUE_FAIL, "the value \"" + actualLex + "\" is invalid " +
"yet it created the Duration \"" + duration.toString() + "\"" );
assertNotEquals(TEST_VALUE_FAIL, expectedLex, "the value \"" + actualLex + "\" 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();
Assert.assertEquals(xmlSchemaType, DatatypeConstants.DURATION_YEARMONTH, "Duration created with " +
assertEquals(DatatypeConstants.DURATION_YEARMONTH, xmlSchemaType, "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?
Assert.assertEquals(duration.toString(), expectedLex, "Duration created with \"" + actualLex +
"\" was expected to be \"" + expectedLex + "\" 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?
Assert.assertEquals(TEST_VALUE_FAIL, expectedLex, "the value \"" + actualLex + "\" is valid yet " +
"it failed with \"" + exception.toString() + "\"");
// expected failure
+ DatatypeConstants.DURATION_YEARMONTH + "\" and has the value \"" + duration + "\"");
} 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?
assertEquals(expectedLex, duration.toString(), "Duration created with \"" + actualLex +
"\" was expected to be \"" + expectedLex + "\" and has the value \"" + duration + "\"");
// Duration created with correct value
} catch (Exception exception) {
// was this expected to succed?
assertEquals(TEST_VALUE_FAIL, expectedLex, "the value \"" + actualLex + "\" is valid yet " +
"it failed with \"" + exception + "\"");
// expected failure
}
}
@DataProvider(name = "lexDayTime")
public Object[][] lexDayTimeData() {
public static Object[][] lexDayTimeData() {
BigInteger one = new BigInteger("1");
BigInteger zero = new BigInteger("0");
BigDecimal bdZero = new BigDecimal("0");
BigDecimal bdOne = new BigDecimal("1");
Object[][] values = {
return new Object[][] {
// 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 },
{ "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 }, };
return values;
}
/**
* TCK test failure
*/
@Test(dataProvider = "lexDayTime")
@ParameterizedTest
@MethodSource("lexDayTimeData")
public void testNewDurationDayTime005(String lex, boolean isPositive, BigInteger year, BigInteger month, BigInteger days,
BigInteger hour, BigInteger minutes, BigDecimal seconds) {
StringBuffer result = new StringBuffer();
DatatypeFactory df = null;
try {
df = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException e) {
Assert.fail(e.toString());
}
BigInteger hour, BigInteger minutes, BigDecimal seconds)
throws DatatypeConfigurationException {
StringBuilder result = new StringBuilder();
DatatypeFactory df = DatatypeFactory.newInstance();
Duration duration = null;
try {
duration = df.newDurationDayTime(isPositive, days, hour, minutes, seconds.toBigInteger());
} catch (IllegalArgumentException e) {
result.append("; unexpected " + e + " trying to create duration \'" + lex + "\'");
result.append("; unexpected " + e + " trying to create duration '" + lex + "'");
}
if (duration != null) {
if ((duration.getSign() == 1) != isPositive) {
@ -248,43 +215,39 @@ public class Bug6937964Test {
Number value = duration.getField(DatatypeConstants.YEARS);
if ((value != null && year == null) || (value == null && year != null) || (value != null && !value.equals(year))) {
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.YEARS + ": \'" + value + "\'" + ", expected \'"
+ year + "\'");
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.YEARS + ": '" + value + "'" + ", expected '"
+ year + "'");
}
value = duration.getField(DatatypeConstants.MONTHS);
if ((value != null && month == null) || (value == null && month != null) || (value != null && !value.equals(month))) {
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.MONTHS + ": \'" + value + "\'" + ", expected \'"
+ month + "\'");
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.MONTHS + ": '" + value + "'" + ", expected '"
+ month + "'");
}
value = duration.getField(DatatypeConstants.DAYS);
if ((value != null && days == null) || (value == null && days != null) || (value != null && !value.equals(days))) {
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.DAYS + ": \'" + value + "\'" + ", expected \'"
+ days + "\'");
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.DAYS + ": '" + value + "'" + ", expected '"
+ days + "'");
}
value = duration.getField(DatatypeConstants.HOURS);
if ((value != null && hour == null) || (value == null && hour != null) || (value != null && !value.equals(hour))) {
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.HOURS + ": \'" + value + "\'" + ", expected \'"
+ hour + "\'");
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.HOURS + ": '" + value + "'" + ", expected '"
+ hour + "'");
}
value = duration.getField(DatatypeConstants.MINUTES);
if ((value != null && minutes == null) || (value == null && minutes != null) || (value != null && !value.equals(minutes))) {
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.MINUTES + ": \'" + value + "\'" + ", expected \'"
+ minutes + "\'");
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.MINUTES + ": '" + value + "'" + ", expected '"
+ minutes + "'");
}
value = duration.getField(DatatypeConstants.SECONDS);
if ((value != null && seconds == null) || (value == null && seconds != null) || (value != null && !value.equals(seconds))) {
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.SECONDS + ": \'" + value + "\'" + ", expected \'"
+ seconds + "\'");
if (value == null || !value.equals(seconds)) {
result.append("; " + lex + ": wrong value of the field " + DatatypeConstants.SECONDS + ": '" + value + "'" + ", expected '"
+ seconds + "'");
}
}
if(result.length() > 0) {
Assert.fail(result.substring(2));
}
System.out.println("OK");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,21 +23,21 @@
package datatype;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/*
* @test
* @bug 7042647
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm datatype.Bug7042647Test
* @run junit/othervm datatype.Bug7042647Test
* @summary Test getFirstDayOfWeek is correct after converting XMLGregorianCalendar to a GregorianCalendar.
*/
public class Bug7042647Test {
@ -49,11 +49,7 @@ public class Bug7042647Test {
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);
}
assertEquals(defaultFirstDayOfWeek, firstDayOfWeek);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,8 +23,7 @@
package datatype;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.Test;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
@ -32,14 +31,15 @@ import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.fail;
/*
* @test
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm datatype.DatatypeFactoryTest
* @run junit/othervm datatype.DatatypeFactoryTest
* @summary Test DatatypeFactory.
*/
public class DatatypeFactoryTest {
@ -120,7 +120,7 @@ public class DatatypeFactoryTest {
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
@ -144,20 +144,20 @@ public class DatatypeFactoryTest {
// 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()
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
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 \""
fail("Duration created with \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\" and has the value \"" + duration.toString() + "\"");
}
@ -170,7 +170,7 @@ public class DatatypeFactoryTest {
// 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() + "\"");
fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
@ -195,7 +195,7 @@ public class DatatypeFactoryTest {
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
@ -218,7 +218,7 @@ public class DatatypeFactoryTest {
// 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() + "\"");
fail("the value \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" is invalid yet it created the Duration \"" + duration.toString() + "\"");
}
// right XMLSchemaType?
@ -227,7 +227,7 @@ public class DatatypeFactoryTest {
try {
QName xmlSchemaType = duration.getXMLSchemaType();
if (!xmlSchemaType.equals(DatatypeConstants.DURATION_YEARMONTH)) {
Assert.fail("Duration created with XMLSchemaType of\"" + xmlSchemaType + "\" was expected to be \""
fail("Duration created with XMLSchemaType of\"" + xmlSchemaType + "\" was expected to be \""
+ DatatypeConstants.DURATION_YEARMONTH + "\" and has the value \"" + duration.toString() + "\"");
}
} catch (IllegalStateException illegalStateException) {
@ -237,7 +237,7 @@ public class DatatypeFactoryTest {
// 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 \""
fail("Duration created with \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_LEXICAL[onTestValue + 1] + "\" and has the value \"" + duration.toString() + "\"");
}
@ -250,7 +250,7 @@ public class DatatypeFactoryTest {
// 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() + "\"");
fail("the value \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
@ -287,7 +287,7 @@ public class DatatypeFactoryTest {
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
@ -311,20 +311,20 @@ public class DatatypeFactoryTest {
// 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()
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
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 \""
fail("Duration created with \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_MILLISECONDS_RESULTS[onTestValue] + "\" and has the value \"" + duration.toString() + "\"");
}
@ -333,7 +333,7 @@ public class DatatypeFactoryTest {
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
fail("xdt:yearMonthDuration created without discarding remaining milliseconds: " + " days = " + days + ", hours = " + hours
+ ", minutess = " + minutes);
}
@ -346,7 +346,7 @@ public class DatatypeFactoryTest {
// 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() + "\"");
fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
@ -382,7 +382,7 @@ public class DatatypeFactoryTest {
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
@ -406,7 +406,7 @@ public class DatatypeFactoryTest {
// 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()
fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is invalid yet it created the Duration \"" + duration.toString()
+ "\"");
}
@ -414,7 +414,7 @@ public class DatatypeFactoryTest {
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 \""
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]
@ -431,7 +431,7 @@ public class DatatypeFactoryTest {
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
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: "
@ -448,7 +448,7 @@ public class DatatypeFactoryTest {
// 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() + "\"");
fail("the value \"" + TEST_VALUES_MILLISECONDS[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
@ -482,7 +482,7 @@ public class DatatypeFactoryTest {
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
@ -505,13 +505,13 @@ public class DatatypeFactoryTest {
// 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 \""
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 \""
fail("XMLGregorianCalendar created with \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" was expected to be \""
+ TEST_VALUES_LEXICAL[onTestValue + 1] + "\" and has the value \"" + xmlGregorianCalendar.toString() + "\"");
}
@ -524,7 +524,7 @@ public class DatatypeFactoryTest {
// 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() + "\"");
fail("the value \"" + TEST_VALUES_LEXICAL[onTestValue] + "\" is valid yet it failed with \"" + exception.toString() + "\"");
}
// expected failure
}
@ -563,7 +563,7 @@ public class DatatypeFactoryTest {
try {
datatypeFactory = DatatypeFactory.newInstance();
} catch (DatatypeConfigurationException datatypeConfigurationException) {
Assert.fail(datatypeConfigurationException.toString());
fail(datatypeConfigurationException.toString());
}
if (DEBUG) {
@ -591,7 +591,7 @@ public class DatatypeFactoryTest {
}
// unexpected success, should have failed
Assert.fail("expected IllegalArgumentException " + "for DatatypeFactory.newXMLGregorianCalendar(" + invalidDates[valueIndex][0] + ", "
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.");
@ -624,7 +624,7 @@ public class DatatypeFactoryTest {
}
// unexpected success, should have failed
Assert.fail("expected IllegalArgumentException " + "for DatatypeFactory.newXMLGregorianCalendar(" + invalidDates[valueIndex][0] + ", "
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.");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,6 +23,16 @@
package datatype;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.namespace.QName;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
@ -30,47 +40,37 @@ import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.namespace.QName;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/*
* @test
* @bug 8190835
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm datatype.DurationTest
* @run junit/othervm datatype.DurationTest
* @summary Test Duration.
*/
public class DurationTest {
private final static boolean DEBUG = true;
protected Duration duration = null;
private DatatypeFactory factory = null;
private Duration duration = null;
@BeforeMethod
public void setUp() {
try {
duration = DatatypeFactory.newInstance().newDuration(100);
} catch (DatatypeConfigurationException dce) {
dce.printStackTrace();
Assert.fail("Failed to create instance of DatatypeFactory " + dce.getMessage());
}
@BeforeEach
public void setUp() throws DatatypeConfigurationException {
factory = DatatypeFactory.newInstance();
duration = factory.newDuration(100);
}
/*
DataProvider: for testDurationSubtract1
Data: minuend, subtrahend, expected result
*/
@DataProvider(name = "DurationSubtract1")
public Object[][] getSubtract1() {
public static Object[][] getSubtract1() {
return new Object[][]{
{"P2Y2M", "P1Y5M", "P9M"},
@ -84,8 +84,7 @@ public class DurationTest {
};
}
@DataProvider(name = "DurationSubtract2")
public Object[][] getSubtract2() {
public static Object[][] getSubtract2() {
return new Object[][]{
{"P2Y20D", "P1Y125D"},
@ -96,67 +95,60 @@ public class DurationTest {
/*
* Verifies valid substraction operations.
*/
@Test(dataProvider = "DurationSubtract1")
public void testDurationSubtract1(String t1, String t2, String e) throws Exception {
DatatypeFactory factory = DatatypeFactory.newInstance();
@ParameterizedTest
@MethodSource("getSubtract1")
public void testDurationSubtract1(String t1, String t2, String e) {
Duration dt1 = factory.newDuration(t1);
Duration dt2 = factory.newDuration(t2);
Duration result = dt1.subtract(dt2);
Duration expected = factory.newDuration(e);
Assert.assertTrue(result.equals(expected), "The result should be " + e);
assertEquals(factory.newDuration(e), result, "The result should be " + e);
}
/*
* Verifies invalid substraction operations. These operations are invalid
* since days in a month are indeterminate.
*/
@Test(dataProvider = "DurationSubtract2", expectedExceptions = IllegalStateException.class)
public void testDurationSubtract2(String t1, String t2) throws Exception {
DatatypeFactory factory = DatatypeFactory.newInstance();
*/
@ParameterizedTest
@MethodSource("getSubtract2")
public void testDurationSubtract2(String t1, String t2) {
Duration dt1 = factory.newDuration(t1);
Duration dt2 = factory.newDuration(t2);
Duration result = dt1.subtract(dt2);
assertThrows(IllegalStateException.class, () -> dt1.subtract(dt2));
}
@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();
Duration bigDur = factory.newDuration(20000);
Duration smallDur = factory.newDuration(10000);
if (smallDur.subtract(bigDur).getSign() != -1) {
fail("smallDur.subtract(bigDur).getSign() is not -1");
}
if (bigDur.subtract(smallDur).getSign() != 1) {
fail("bigDur.subtract(smallDur).getSign() is not 1");
}
if (smallDur.subtract(smallDur).getSign() != 0) {
fail("smallDur.subtract(smallDur).getSign() is not 0");
}
}
@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();
Duration dur = factory.newDuration(num);
if (dur.multiply(factor).getSeconds() != 10) {
fail("duration.multiply() return wrong value");
}
// factor is 2*10^(-1)
if (dur.multiply(new BigDecimal(new BigInteger("2"), 1)).getSeconds() != 1) {
fail("duration.multiply() return wrong value");
}
if (dur.subtract(factory.newDuration(1000)).multiply(new BigDecimal(new BigInteger("2"), 1)).getSeconds() != 0) {
fail("duration.multiply() return wrong value");
}
}
@ -169,73 +161,55 @@ public class DurationTest {
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();
}
Duration dur = factory.newDuration(lexicalRepresentation);
System.out.println(dur.toString());
assertEquals(year, dur.getYears(), "year should be 1");
assertEquals(month, dur.getMonths(), "month should be 2");
assertEquals(day, dur.getDays(), "day should be 3");
assertEquals(hour, dur.getHours(), "hour should be 4");
assertEquals(min, dur.getMinutes(), "minute should be 5");
assertEquals(sec, dur.getSeconds(), "second should be 6");
}
@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();
}
assertEquals(10000, factory.newDuration("PT10.00099S")
.getTimeInMillis(new Date()), "10.00099S means 10 sec since it will be rounded to zero");
assertEquals(-10000, factory.newDuration("-PT10.00099S")
.getTimeInMillis(new Date()), "10.00099S means 10 sec since it will be rounded to zero");
assertEquals(10000, factory.newDuration("PT10.00099S")
.getTimeInMillis(new GregorianCalendar()), "10.00099S means 10 sec since it will be rounded to zero");
assertEquals(-10000, factory.newDuration("-PT10.00099S")
.getTimeInMillis(new GregorianCalendar()), "10.00099S means 10 sec since it will be rounded to zero");
}
@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);
Calendar cal = new GregorianCalendar();
cal.set(Calendar.SECOND, 59);
factory.newDuration(10000).addTo(cal);
assertEquals(9, cal.get(Calendar.SECOND), "sec will be 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();
}
Date date = new Date();
date.setSeconds(59);
factory.newDuration(10000).addTo(date);
assertEquals(9, date.getSeconds(), "sec will be 9");
}
@Test
public void testEqualsWithDifferentObjectParam() {
AssertJUnit.assertFalse("equals method should return false for any object other than Duration", duration.equals(new Integer(0)));
assertFalse(duration.equals(new Integer(0)), "equals method should return false for any object other than Duration");
}
@Test
public void testEqualsWithNullObjectParam() {
AssertJUnit.assertFalse("equals method should return false for null parameter", duration.equals(null));
assertFalse(duration.equals(null), "equals method should return false for null parameter");
}
@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());
}
assertTrue(duration.equals(factory.newDuration(100)), "equals method is expected to return true");
}
/**
@ -250,13 +224,7 @@ public class DurationTest {
{ "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());
}
DatatypeFactory df = factory;
boolean compareErrors = false;
@ -272,7 +240,7 @@ public class DurationTest {
// tested
if (expected != cmp) {
compareErrors = true;
System.err.println("returned " + cmp2str(cmp) + " for durations \'" + duration1 + "\' and " + duration2 + "\', but expected "
System.err.println("returned " + cmp2str(cmp) + " for durations '" + duration1 + "' and " + duration2 + "', but expected "
+ cmp2str(expected));
}
}
@ -280,7 +248,7 @@ public class DurationTest {
if (compareErrors) {
// TODO; fix bug, these tests should pass
if (false) {
Assert.fail("Errors in comparing indeterminate relations, see Stderr");
fail("Errors in comparing indeterminate relations, see Stderr");
} else {
System.err.println("Please fix this bug: " + "Errors in comparing indeterminate relations, see Stderr");
}
@ -297,7 +265,7 @@ public class DurationTest {
* description concerning return values range.
*/
@Test
public void testNormalizedReturnValues() throws Exception {
public void testNormalizedReturnValues() {
final Object[] TEST_VALUES = {
// test 61 seconds -> 1 minute, 1 second
@ -348,9 +316,9 @@ public class DurationTest {
};
for (int onValue = 0; onValue < TEST_VALUES.length; onValue += 9) {
newDurationTester(((Boolean) TEST_VALUES[onValue]).booleanValue(), // isPositive,
((Boolean) NORM_VALUES[onValue]).booleanValue(), // normalized
// isPositive,
newDurationTester((Boolean) TEST_VALUES[onValue], // isPositive,
(Boolean) NORM_VALUES[onValue], // normalized
// isPositive,
(BigInteger) TEST_VALUES[onValue + 1], // years,
(BigInteger) NORM_VALUES[onValue + 1], // normalized years,
(BigInteger) TEST_VALUES[onValue + 2], // months
@ -363,16 +331,16 @@ public class DurationTest {
(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,
(Long) TEST_VALUES[onValue + 7], // durationInMilliSeconds,
(Long) NORM_VALUES[onValue + 7], // 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,
newDurationDayTimeTester((Boolean) TEST_VALUES[onValue], // isPositive,
(Boolean) NORM_VALUES[onValue], // normalized
// isPositive,
BigInteger.ZERO, // years,
BigInteger.ZERO, // normalized years,
BigInteger.ZERO, // months
@ -385,9 +353,9 @@ public class DurationTest {
(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,
(Long) TEST_VALUES[onValue + 7], // durationInMilliSeconds,
(Long) NORM_VALUES[onValue + 7], // normalized
// durationInMilliSeconds,
(String) TEST_VALUES[onValue + 8], // lexicalRepresentation
(String) NORM_VALUES[onValue + 8]); // normalized
// lexicalRepresentation
@ -399,33 +367,24 @@ public class DurationTest {
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);
Duration durationBigInteger = factory.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(),
Duration durationInt = factory.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);
Duration durationMilliseconds = factory.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);
Duration durationLexical = factory.newDuration(lexicalRepresentation);
durationAssertEquals(durationLexical, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);
@ -436,17 +395,8 @@ public class DurationTest {
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());
Duration durationDayTimeBigInteger = factory.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);
@ -482,7 +432,7 @@ public class DurationTest {
// sign
if (DEBUG) {
boolean actual = (duration.getSign() == 1) ? true : false;
boolean actual = duration.getSign() == 1;
System.out.println("sign:");
System.out.println(" expected: \"" + isPositive + "\"");
System.out.println(" actual: \"" + actual + "\"");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,48 +23,48 @@
package datatype;
import org.junit.jupiter.api.Test;
import javax.xml.datatype.DatatypeFactory;
import java.net.URL;
import java.net.URLClassLoader;
import javax.xml.datatype.DatatypeFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm datatype.FactoryFindTest
* @run junit/othervm datatype.FactoryFindTest
* @summary Test Classloader for DatatypeFactory.
*/
public class FactoryFindTest {
boolean myClassLoaderUsed = false;
@Test
public void testFactoryFind() throws Exception {
DatatypeFactory factory = DatatypeFactory.newInstance();
Assert.assertTrue(factory.getClass().getClassLoader() == null);
assertNull(factory.getClass().getClassLoader());
Thread.currentThread().setContextClassLoader(null);
factory = DatatypeFactory.newInstance();
Assert.assertTrue(factory.getClass().getClassLoader() == null);
assertNull(factory.getClass().getClassLoader());
Thread.currentThread().setContextClassLoader(new MyClassLoader());
factory = DatatypeFactory.newInstance();
if (System.getSecurityManager() == null)
Assert.assertTrue(myClassLoaderUsed);
else
Assert.assertFalse(myClassLoaderUsed);
MyClassLoader customLoader = new MyClassLoader();
Thread.currentThread().setContextClassLoader(customLoader);
assertNotNull(DatatypeFactory.newInstance());
assertTrue(customLoader.wasUsed);
}
class MyClassLoader extends URLClassLoader {
static class MyClassLoader extends URLClassLoader {
boolean wasUsed = false;
public MyClassLoader() {
super(new URL[0]);
}
public Class loadClass(String name) throws ClassNotFoundException {
myClassLoaderUsed = true;
public Class<?> loadClass(String name) throws ClassNotFoundException {
wasUsed = true;
return super.loadClass(name);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,16 +23,19 @@
package datatype;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.testng.annotations.Test;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/*
* @test
* @bug 8246816
* @run testng datatype.HashCodeTest
* @run junit datatype.HashCodeTest
* @summary Test hashCode generation.
*/
public class HashCodeTest {
@ -40,26 +43,26 @@ public class HashCodeTest {
DataProvider: for testHashCode
Data: datetime1, datetime2, flag indicating if their hashCodes are equal
*/
@DataProvider(name = "testHashCode")
public Object[][] getData() {
public static Object[][] getData() {
return new Object[][]{
// the reported case: identical hash codes before the patch
{"2020-04-24T12:53:00+02:00", "2020-06-04T06:58:17.727Z", false},
// a case mentioned in the dev note of hashCode() implementation
{"2000-01-15T12:00:00-05:00", "2000-01-15T13:00:00-04:00", true},
/**
* Comparing with a datetime that needs to be normalized.
* Before the patch, XMLGregorianCalendarImpl called the normalizeToTimezone
* method that will set UNDEFINED fractional second to zero.
*/
{"2000-01-01T03:19:04Z", "1999-12-31T23:49:04-03:30", true},
// another case mentioned in the javadoc of XMLGregorianCalendar::normalize()
{"2000-03-04T23:00:00+03:00", "2000-03-04T20:00:00Z", true},
return new Object[][] {
// the reported case: identical hash codes before the patch
{ "2020-04-24T12:53:00+02:00", "2020-06-04T06:58:17.727Z", false },
// a case mentioned in the dev note of hashCode() implementation
{ "2000-01-15T12:00:00-05:00", "2000-01-15T13:00:00-04:00", true },
/*
* Comparing with a datetime that needs to be normalized.
* Before the patch, XMLGregorianCalendarImpl called the normalizeToTimezone
* method that will set UNDEFINED fractional second to zero.
*/
{ "2000-01-01T03:19:04Z", "1999-12-31T23:49:04-03:30", true },
// another case mentioned in the javadoc of XMLGregorianCalendar::normalize()
{ "2000-03-04T23:00:00+03:00", "2000-03-04T20:00:00Z", true },
};
}
@Test(dataProvider = "testHashCode")
@ParameterizedTest
@MethodSource("getData")
public final void testHashCode(String dt1, String dt2, boolean equal) throws Exception {
DatatypeFactory dataTypeFactory = DatatypeFactory.newInstance();
XMLGregorianCalendar cal1 = dataTypeFactory.newXMLGregorianCalendar(dt1);
@ -70,11 +73,11 @@ public class HashCodeTest {
int hashCode2 = cal2.hashCode();
if (equal) {
Assert.assertTrue(cal1.equals(cal2));
Assert.assertEquals(hashCode1, hashCode2);
assertEquals(cal1, cal2);
assertEquals(hashCode1, hashCode2);
} else {
Assert.assertFalse(cal1.equals(cal2));
Assert.assertNotEquals(hashCode1, hashCode2);
assertNotEquals(cal1, cal2);
assertNotEquals(hashCode1, hashCode2);
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -22,18 +22,19 @@
*/
package datatype;
import org.junit.jupiter.api.Test;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/*
* @test
* @bug 8068839
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm datatype.JDK8068839Test
* @run junit/othervm datatype.JDK8068839Test
* @summary Verifies that Duration's edge cases
*/
public class JDK8068839Test {
@ -42,9 +43,9 @@ public class JDK8068839Test {
public void test() throws DatatypeConfigurationException {
DatatypeFactory df = DatatypeFactory.newInstance();
Duration durationx = df.newDuration(Long.MIN_VALUE);
Assert.assertEquals(durationx.toString(), "-P292277024Y7M16DT7H12M55.808S");
assertEquals("-P292277024Y7M16DT7H12M55.808S", durationx.toString());
durationx = df.newDuration(Long.MAX_VALUE);
Assert.assertEquals(durationx.toString(), "P292277024Y7M16DT7H12M55.807S");
assertEquals("P292277024Y7M16DT7H12M55.807S", durationx.toString());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,19 +23,23 @@
package datatype;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/*
* @test
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm datatype.XMLGregorianCalendarTest
* @run junit/othervm datatype.XMLGregorianCalendarTest
* @summary Test XMLGregorianCalendar.
*/
public class XMLGregorianCalendarTest {
@ -46,41 +50,26 @@ public class XMLGregorianCalendarTest {
private static final int TEST_VALUE_PASS = 1;
private DatatypeFactory factory;
private XMLGregorianCalendar calendar;
@BeforeMethod
public void setUp() {
try {
calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar();
} catch (DatatypeConfigurationException dce) {
dce.printStackTrace();
Assert.fail("Failed to create instance of DatatypeFactory " + dce.getMessage());
}
@BeforeEach
public void setUp() throws DatatypeConfigurationException {
factory = DatatypeFactory.newInstance();
calendar = factory.newXMLGregorianCalendar();
}
@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();
XMLGregorianCalendar xmlGregorianCalendar = factory.newXMLGregorianCalendar();
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES.length; onTestValue = onTestValue + 4) {
@ -95,24 +84,24 @@ public class XMLGregorianCalendarTest {
xmlGregorianCalendar.setTime(TEST_VALUES[onTestValue], TEST_VALUES[onTestValue + 1], TEST_VALUES[onTestValue + 2]);
if (DEBUG) {
System.err.println("XMLGregorianCalendar created: \"" + xmlGregorianCalendar.toString() + "\"");
System.err.println("XMLGregorianCalendar created: \"" + xmlGregorianCalendar + "\"");
}
// 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() + "\"");
fail("the values: (" + TEST_VALUES[onTestValue] + ", " + TEST_VALUES[onTestValue + 1] + ", " + TEST_VALUES[onTestValue + 2]
+ ") are invalid, " + "yet it created the XMLGregorianCalendar \"" + xmlGregorianCalendar + "\"");
}
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating XMLGregorianCalendar: \"" + exception.toString() + "\"");
System.err.println("Exception in creating XMLGregorianCalendar: \"" + exception + "\"");
}
// 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() + "\"");
fail("the values: (" + TEST_VALUES[onTestValue] + ", " + TEST_VALUES[onTestValue + 1] + ", " + TEST_VALUES[onTestValue + 2]
+ ") are valid yet it failed with \"" + exception + "\"");
}
// expected failure
}
@ -122,7 +111,7 @@ public class XMLGregorianCalendarTest {
@Test
public final void testSetHour() {
/**
/*
* Hour values to test and expected result.
*/
final int[] TEST_VALUES = {
@ -133,20 +122,8 @@ public class XMLGregorianCalendarTest {
// 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();
XMLGregorianCalendar xmlGregorianCalendar = factory.newXMLGregorianCalendar();
// test each value
for (int onTestValue = 0; onTestValue < TEST_VALUES.length; onTestValue = onTestValue + 5) {
@ -163,25 +140,25 @@ public class XMLGregorianCalendarTest {
xmlGregorianCalendar.setHour(TEST_VALUES[onTestValue + 3]);
if (DEBUG) {
System.err.println("XMLGregorianCalendar created: \"" + xmlGregorianCalendar.toString() + "\"");
System.err.println("XMLGregorianCalendar created: \"" + xmlGregorianCalendar + "\"");
}
// 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()
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
+ "\"");
}
} catch (Exception exception) {
if (DEBUG) {
System.err.println("Exception in creating XMLGregorianCalendar: \"" + exception.toString() + "\"");
System.err.println("Exception in creating XMLGregorianCalendar: \"" + exception + "\"");
}
// 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() + "\"");
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 + "\"");
}
// expected failure
}
@ -190,38 +167,24 @@ public class XMLGregorianCalendarTest {
@Test
public void testEqualsWithDifferentObjectParam() {
Assert.assertFalse(calendar.equals(new Integer(0)), "equals method should return false for any object other" + " than XMLGregorianCalendar");
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");
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());
}
assertTrue(calendar.equals(factory.newXMLGregorianCalendar()), "equals method is expected to return true");
}
@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());
}
String inputDateTime = "2006-10-23T22:15:01.000000135+08:00";
XMLGregorianCalendar calendar = factory.newXMLGregorianCalendar(inputDateTime);
String toStr = calendar.toString();
assertEquals(-1, toStr.indexOf("E"), "String value cannot contain exponent");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,14 +23,18 @@
package sax;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.ext.Attributes2Impl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.Attributes2ImplTest
* @run junit/othervm sax.Attributes2ImplTest
* @summary Test Attributes2Impl.
*/
public class Attributes2ImplTest {
@ -43,42 +47,25 @@ public class Attributes2ImplTest {
impl.addAttribute("http://www.cars.com/xml", "attr2", "Qname2", "type", "value");
impl.addAttribute("http://www.cars.com/xml", "attr3", "Qname3", "type", "value");
Assert.assertTrue(impl.isDeclared(0));
assertTrue(impl.isDeclared(0));
impl.setDeclared(0, false);
Assert.assertFalse(impl.isDeclared(0));
assertFalse(impl.isDeclared(0));
Assert.assertTrue(impl.isDeclared("Qname2"));
assertTrue(impl.isDeclared("Qname2"));
impl.setDeclared(1, false);
Assert.assertFalse(impl.isDeclared("Qname2"));
assertFalse(impl.isDeclared("Qname2"));
Assert.assertTrue(impl.isDeclared("http://www.cars.com/xml", "attr3"));
assertTrue(impl.isDeclared("http://www.cars.com/xml", "attr3"));
impl.setDeclared(2, false);
Assert.assertFalse(impl.isDeclared(2));
assertFalse(impl.isDeclared(2));
try {
impl.isDeclared(3);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Expected ArrayIndexOutOfBoundsException");
}
assertThrows(ArrayIndexOutOfBoundsException.class, () -> impl.isDeclared(3));
try {
impl.isDeclared("wrongQname");
} catch (IllegalArgumentException e) {
System.out.println("Expected IllegalArgumentException");
}
try {
impl.isDeclared("http://www.cars.com/xml", "attr4");
} catch (IllegalArgumentException e) {
System.out.println("Expected IllegalArgumentException");
}
assertThrows(IllegalArgumentException.class, () -> impl.isDeclared("wrongQname"));
assertThrows(IllegalArgumentException.class, () -> impl.isDeclared("http://www.cars.com/xml", "attr4"));
impl.removeAttribute(2);
try {
impl.isDeclared(2);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Expected ArrayIndexOutOfBoundsException on index=2 after removing");
}
assertThrows(ArrayIndexOutOfBoundsException.class, () -> impl.isDeclared(2));
}
@Test
@ -89,42 +76,25 @@ public class Attributes2ImplTest {
impl.addAttribute("http://www.cars.com/xml", "attr2", "Qname2", "type", "value");
impl.addAttribute("http://www.cars.com/xml", "attr3", "Qname3", "type", "value");
Assert.assertTrue(impl.isSpecified(0));
assertTrue(impl.isSpecified(0));
impl.setSpecified(0, false);
Assert.assertFalse(impl.isSpecified(0));
assertFalse(impl.isSpecified(0));
Assert.assertTrue(impl.isSpecified("Qname2"));
assertTrue(impl.isSpecified("Qname2"));
impl.setSpecified(1, false);
Assert.assertFalse(impl.isSpecified("Qname2"));
assertFalse(impl.isSpecified("Qname2"));
Assert.assertTrue(impl.isSpecified("http://www.cars.com/xml", "attr3"));
assertTrue(impl.isSpecified("http://www.cars.com/xml", "attr3"));
impl.setSpecified(2, false);
Assert.assertFalse(impl.isSpecified(2));
assertFalse(impl.isSpecified(2));
try {
impl.isSpecified(3);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Expected ArrayIndexOutOfBoundsException");
}
assertThrows(ArrayIndexOutOfBoundsException.class, () -> impl.isSpecified(3));
try {
impl.isSpecified("wrongQname");
} catch (IllegalArgumentException e) {
System.out.println("Expected IllegalArgumentException");
}
try {
impl.isSpecified("http://www.cars.com/xml", "attr4");
} catch (IllegalArgumentException e) {
System.out.println("Expected IllegalArgumentException");
}
assertThrows(IllegalArgumentException.class, () -> impl.isSpecified("wrongQname"));
assertThrows(IllegalArgumentException.class, () -> impl.isSpecified("http://www.cars.com/xml", "attr4"));
impl.removeAttribute(2);
try {
impl.isSpecified(2);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Expected ArrayIndexOutOfBoundsException on index=2 after removing");
}
assertThrows(ArrayIndexOutOfBoundsException.class, () -> impl.isSpecified(2));
}
@Test
@ -140,13 +110,13 @@ public class Attributes2ImplTest {
Attributes2Impl impl3 = new Attributes2Impl();
impl3.setAttributes(impl1);
Assert.assertTrue(impl1.getQName(0).equals(impl2.getQName(0)));
Assert.assertTrue(impl1.getQName(0).equals(impl3.getQName(0)));
assertEquals(impl1.getQName(0), impl2.getQName(0));
assertEquals(impl1.getQName(0), impl3.getQName(0));
Assert.assertTrue(impl1.getQName(1).equals(impl2.getQName(1)));
Assert.assertTrue(impl1.getQName(1).equals(impl3.getQName(1)));
assertEquals(impl1.getQName(1), impl2.getQName(1));
assertEquals(impl1.getQName(1), impl3.getQName(1));
Assert.assertTrue(impl1.getQName(2).equals(impl2.getQName(2)));
Assert.assertTrue(impl1.getQName(2).equals(impl3.getQName(2)));
assertEquals(impl1.getQName(2), impl2.getQName(2));
assertEquals(impl1.getQName(2), impl3.getQName(2));
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,64 +23,26 @@
package sax;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @bug 6889654
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.Bug6889654Test
* @run junit/othervm sax.Bug6889654Test
* @summary Test SAXException includes whole information.
*/
public class Bug6889654Test {
final String MSG = "Failed to parse XML";
@Test
public void testException() {
try {
parse();
} catch (SAXException e) {
// e.printStackTrace();
String msg = e.toString();
if (msg.indexOf("systemId") == -1) {
Assert.fail("CR6889654 -- details should be returned.");
}
if (msg.indexOf(MSG) == -1) {
Assert.fail("CR6889649 -- additional error message not returned.");
}
System.out.println("error message:\n" + msg);
}
RuntimeException cause = new RuntimeException("<cause message>");
// The toString() of a SAXException includes the message of its cause.
SAXException wrapped = new SAXException("<wrapped message>", cause);
assertTrue(wrapped.toString().contains("<wrapped message>"));
assertTrue(wrapped.toString().contains("<cause message>"));
}
void parse() throws SAXException {
String xml = "<data>\n<broken/>\u0000</data>";
try {
InputSource is = new InputSource(new StringReader(xml));
is.setSystemId("file:///path/to/some.xml");
// notice that exception thrown here doesn't include the line number
// information when reported by JVM -- CR6889654
SAXParserFactory.newInstance().newSAXParser().parse(is, new DefaultHandler());
} catch (SAXException e) {
// notice that this message isn't getting displayed -- CR6889649
throw new SAXException(MSG, e);
} catch (ParserConfigurationException pce) {
} catch (IOException ioe) {
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,37 +23,30 @@
package sax;
import javax.xml.datatype.DatatypeConfigurationException;
import org.testng.annotations.Test;
import org.testng.Assert;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.datatype.DatatypeConfigurationException;
/*
* @test
* @bug 6925410
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.Bug6925410Test
* @run junit/othervm sax.Bug6925410Test
* @summary Test XMLReaderFactory can createXMLReader repeatedly.
*/
public class Bug6925410Test {
@Test
public void test() throws DatatypeConfigurationException {
try {
int times = 100;
long start = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
XMLReaderFactory.createXMLReader();
}
long end = System.currentTimeMillis();
double speed = ((end - start));
System.out.println(speed + "ms");
} catch (Throwable e) {
e.printStackTrace();
Assert.fail(e.toString());
public void test() throws DatatypeConfigurationException, SAXException {
int times = 100;
long start = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
XMLReaderFactory.createXMLReader();
}
long end = System.currentTimeMillis();
double speed = ((end - start));
System.out.println(speed + "ms");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,57 +23,52 @@
package sax;
import java.io.ByteArrayInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.ByteArrayInputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @bug 6949607
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.Bug6949607Test
* @run junit/othervm sax.Bug6949607Test
* @summary Test Attributes.getValue returns null when parameter uri is empty.
*/
public class Bug6949607Test {
final String MSG = "Failed to parse XML";
String textXML = "<prefix:rootElem xmlns:prefix=\"something\" prefix:attr=\"attrValue\" />";
private static final String TEXT_XML =
"<prefix:rootElem xmlns:prefix=\"something\" prefix:attr=\"attrValue\" />";
@Test
public void testException() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
SAXParser saxParser = factory.newSAXParser();
public void testException() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new ByteArrayInputStream(textXML.getBytes()), new TestFilter());
} catch (Throwable t) {
t.printStackTrace();
}
TestFilter filter = new TestFilter();
saxParser.parse(new ByteArrayInputStream(TEXT_XML.getBytes()), filter);
assertTrue(filter.wasTested);
}
class TestFilter extends DefaultHandler {
static class TestFilter extends DefaultHandler {
boolean wasTested = false;
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
super.startElement(uri, localName, qName, atts);
String attr_WithNs = atts.getValue("something", "attr");
String attr_NoNs = atts.getValue("", "attr");
System.out.println("withNs: " + attr_WithNs);
System.out.println("NoNs: " + attr_NoNs);
Assert.assertTrue(attr_NoNs == null, "Should return null when uri is empty.");
assertEquals("attrValue", atts.getValue("something", "attr"));
assertNull(atts.getValue("", "attr"), "Should return null when uri is empty.");
wasTested = true;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,63 +23,49 @@
package sax;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.ByteArrayInputStream;
import static org.junit.jupiter.api.Assertions.assertFalse;
/*
* @test
* @bug 6992561
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.Bug6992561Test
* @run junit/othervm sax.Bug6992561Test
* @summary Test encoding of SystemId in Locator.
*/
public class Bug6992561Test {
@Test
public void test() {
public void test() throws Exception {
ContentHandler handler = new DefaultHandler() {
public void setDocumentLocator(Locator locator) {
String sysId = locator.getSystemId();
System.out.println(locator.getSystemId());
if (sysId.indexOf("%7") > 0) {
Assert.fail("the original system id should be left as is and not encoded.");
}
assertFalse(sysId.contains("%7"), "the original system id should be left as is and not encoded.");
}
};
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser;
try {
parser = spf.newSAXParser();
parser = spf.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(handler);
String xml = "<test>abc</test>";
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
InputSource is = new InputSource("file:/home2/ramapulavarthi/w/bugs/jaxws861/foo~bla/test/src/wsdl/HelloTypes.xsd");
is.setByteStream(bis);
reader.parse(is);
} catch (ParserConfigurationException ex) {
Assert.fail(ex.toString());
} catch (SAXException ex) {
Assert.fail(ex.toString());
} catch (IOException ex) {
Assert.fail(ex.toString());
}
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(handler);
String xml = "<test>abc</test>";
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
InputSource is = new InputSource("file:/home2/ramapulavarthi/w/bugs/jaxws861/foo~bla/test/src/wsdl/HelloTypes.xsd");
is.setByteStream(bis);
reader.parse(is);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,171 +23,43 @@
package sax;
import static jaxp.library.JAXPTestUtilities.USER_DIR;
import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import javax.xml.parsers.ParserConfigurationException;
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.ErrorHandler;
import org.xml.sax.SAXException;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DefaultHandler2;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @bug 7057778
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.Bug7057778Test
* @run junit/othervm sax.Bug7057778Test
* @summary Test the file can be deleted after SAXParser.parse(File, DefaultHandler).
*/
public class Bug7057778Test {
static final String xml = "Bug7057778.xml";
static final String xml1 = "Bug7057778_1.xml";
@Test
public void testParse() {
File src = new File(getClass().getResource(xml).getFile());
File dst = new File(USER_DIR + xml1);
try {
copyFile(src, dst);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", new MyHandler1());
parser.parse(dst, new MyHandler1());
} catch (SAXException ex) {
ex.printStackTrace();
} catch (IOException ex) {
// shouldn't happen
} catch (ParserConfigurationException ex) {
// shouldn't happen
} catch (Exception ex) {
}
if (dst != null) {
if (dst.delete()) {
System.out.println("Delete: OK");
} else {
System.out.println("Delete: NG");
Assert.fail("Error: denied to delete the file");
}
}
public void testParse() throws Exception {
Path badXml = Path.of("bad.xml");
Files.writeString(badXml, "\n\n\n\n");
}
private void copyFile(File src, File dst) throws FileNotFoundException, IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public class MyHandler1 extends DefaultHandler2 implements ErrorHandler {
private Writer out;
StringBuffer textBuffer;
private String indentString = " "; // Amount to indent
private int indentLevel = 0;
public MyHandler1() {
try {
out = new OutputStreamWriter(System.out, "UTF8");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
}
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
try {
System.out.println("uri: " + uri);
System.out.println("localName: " + localName);
System.out.println("qName: " + qName);
} catch (Exception e) {
throw new SAXException(e);
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
}
public void characters(char ch[], int start, int length) throws SAXException {
}
public void comment(char[] ch, int start, int length) {
String text = new String(ch, start, length);
// System.out.println(text);
try {
nl();
emit("COMMENT: " + text);
} catch (Exception e) {
e.printStackTrace();
}
}
public void error(SAXParseException exception) {
exception.printStackTrace();
}
public void fatalError(SAXParseException exception) {
exception.printStackTrace();
}
public void warning(SAXParseException exception) {
exception.printStackTrace();
}
// Wrap I/O exceptions in SAX exceptions, to
// suit handler signature requirements
private void emit(String s) throws SAXException {
try {
out.write(s);
out.flush();
} catch (IOException e) {
throw new SAXException("I/O error", e);
}
}
// Start a new line
// and indent the next line appropriately
private void nl() throws SAXException {
String lineEnd = getSystemProperty("line.separator");
try {
out.write(lineEnd);
for (int i = 0; i < indentLevel; i++)
out.write(indentString);
} catch (IOException e) {
throw new SAXException("I/O error", e);
}
}
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
DefaultHandler2 noopHandler = new DefaultHandler2();
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", noopHandler);
// Test file is empty and fails parsing.
File dst = badXml.toFile();
assertThrows(SAXParseException.class, () -> parser.parse(dst, noopHandler));
// But parse failure should not keep the destination file open.
assertTrue(dst.delete(), "could not delete the file");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,25 +23,25 @@
package sax;
import java.io.File;
import java.io.StringReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.xml.sax.ContentHandler;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.StringReader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @bug 8230814
* @run testng sax.DeclarationTest
* @run junit sax.DeclarationTest
* @summary Test SAX Parser's handling of XML Declarations.
*/
public class DeclarationTest {
@ -56,12 +56,8 @@ public class DeclarationTest {
*
* Fields:
* XML string, expected version, encoding and standalone strings
*
* @return data array for the test
* @throws Exception
*/
@DataProvider(name = "default")
public Object[][] forDefaultHandler() throws Exception {
public static Object[][] defaultHandlerData() throws Exception {
return new Object[][] {
{ XML_NO_DECLARATION, null, null, null},
{ XML_NO_STANDALONE, null, null, null},
@ -75,12 +71,8 @@ public class DeclarationTest {
*
* Fields:
* XML string, expected version, encoding and standalone strings
*
* @return data array for the test
* @throws Exception
*/
@DataProvider(name = "sax-data")
public Object[][] xmlSAXData() throws Exception {
public static Object[][] xmlSAXData() throws Exception {
return new Object[][] {
{ XML_NO_DECLARATION, null, null, null},
{ XML_NO_STANDALONE, "1.0", "ISO-8859-1", null},
@ -95,12 +87,8 @@ public class DeclarationTest {
*
* Fields:
* Source files, expected version, encoding and standalone strings
*
* @return data array for the test
* @throws Exception
*/
@DataProvider(name = "sax-data-files")
public Object[][] xmlSAXDataFiles() throws Exception {
public static Object[][] xmlSAXDataFiles() throws Exception {
return new Object[][] {
//the source contains no declaration
{ new File(SRC_DIR + "/../transform/SourceTest.xml"), null, null, null},
@ -129,7 +117,8 @@ public class DeclarationTest {
* @param standalone expected standalone string
* @throws Exception if the test fails
*/
@Test(dataProvider = "default")
@ParameterizedTest
@MethodSource("defaultHandlerData")
public void testDefault(String xml, String version, String encoding, String standalone)
throws Exception {
DefaultImpl h = new DefaultImpl();
@ -145,7 +134,8 @@ public class DeclarationTest {
* @param standalone expected standalone string
* @throws Exception if the test fails
*/
@Test(dataProvider = "sax-data")
@ParameterizedTest
@MethodSource("xmlSAXData")
public void test(String xml, String version, String encoding, String standalone)
throws Exception {
NewMethodImpl h = new NewMethodImpl();
@ -161,15 +151,16 @@ public class DeclarationTest {
* @param standalone expected standalone string
* @throws Exception if the test fails
*/
@Test(dataProvider = "sax-data-files")
@ParameterizedTest
@MethodSource("xmlSAXDataFiles")
public void testFiles(File xml, String version, String encoding, String standalone)
throws Exception {
SAXParser parser = SAXParserFactory.newDefaultInstance().newSAXParser();
NewMethodImpl h = new NewMethodImpl();
parser.parse(xml, h);
Assert.assertEquals(h.version, version);
Assert.assertEquals(h.encoding, encoding);
Assert.assertEquals(h.standalone, standalone);
assertEquals(version, h.version);
assertEquals(encoding, h.encoding);
assertEquals(standalone, h.standalone);
}
/**
@ -187,12 +178,12 @@ public class DeclarationTest {
XMLReader r = SAXParserFactory.newDefaultInstance().newSAXParser().getXMLReader();
r.setContentHandler(h);
r.parse(new InputSource(new StringReader(xml)));
Assert.assertEquals(h.version, version);
Assert.assertEquals(h.encoding, encoding);
Assert.assertEquals(h.standalone, standalone);
assertEquals(version, h.version);
assertEquals(encoding, h.encoding);
assertEquals(standalone, h.standalone);
}
class DefaultImpl extends DefaultHandler{
static class DefaultImpl extends DefaultHandler {
boolean startDocumentInvoked = false;
String version, encoding, standalone;
@ -202,7 +193,7 @@ public class DeclarationTest {
}
}
class NewMethodImpl extends DefaultImpl {
static class NewMethodImpl extends DefaultImpl {
public void startDocument() throws SAXException {
super.startDocument();
@ -213,7 +204,7 @@ public class DeclarationTest {
throws SAXException
{
super.declaration(version, encoding, standalone);
Assert.assertTrue(startDocumentInvoked, "declaration follows startDocument");
assertTrue(startDocumentInvoked, "declaration follows startDocument");
this.version = version;
this.encoding = encoding;
this.standalone = standalone;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,16 +23,7 @@
package sax;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.DefaultHandler2;
@ -41,210 +32,135 @@ import org.xml.sax.helpers.ParserAdapter;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.DefaultHandler2Test
* @run junit/othervm sax.DefaultHandler2Test
* @summary Test DefaultHandler2.
*/
public class DefaultHandler2Test {
@Test
public void testParse01() {
System.out.println("===in testParse01===");
try {
DefaultHandler handler = new MyDefaultHandler2();
SAXParserFactory saxFac = SAXParserFactory.newInstance();
System.out.println(saxFac.getFeature("http://xml.org/sax/features/use-locator2"));
public void testParse01() throws Exception {
DefaultHandler handler = new MyDefaultHandler2();
SAXParserFactory saxFac = SAXParserFactory.newInstance();
System.out.println(saxFac.getFeature("http://xml.org/sax/features/use-locator2"));
// set use-entity-resolver2 as FALSE to use EntityResolver firstly.
saxFac.setFeature("http://xml.org/sax/features/use-entity-resolver2", false);
saxFac.setValidating(true);
// set use-entity-resolver2 as FALSE to use EntityResolver firstly.
saxFac.setFeature("http://xml.org/sax/features/use-entity-resolver2", false);
saxFac.setValidating(true);
SAXParser parser = saxFac.newSAXParser();
parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
SAXParser parser = saxFac.newSAXParser();
parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
parser.parse(this.getClass().getResource("toys.xml").getFile(), handler);
} catch (ParserConfigurationException e) {
e.printStackTrace();
Assert.fail("ParserConfigurationException in testParse01()");
} catch (SAXException e) {
e.printStackTrace();
Assert.fail("SAXException in testParse01()");
} catch (IOException e) {
e.printStackTrace();
Assert.fail("IOException in testParse01()");
}
parser.parse(this.getClass().getResource("toys.xml").getFile(), handler);
}
@Test
public void testParse02() {
System.out.println("===in testParse02===");
try {
DefaultHandler handler = new MyDefaultHandler2();
SAXParserFactory saxFac = SAXParserFactory.newInstance();
System.out.println(saxFac.getFeature("http://xml.org/sax/features/use-locator2"));
public void testParse02() throws Exception {
DefaultHandler handler = new MyDefaultHandler2();
SAXParserFactory saxFac = SAXParserFactory.newInstance();
System.out.println(saxFac.getFeature("http://xml.org/sax/features/use-locator2"));
// Enable namespace parsing
System.out.println(saxFac.getFeature("http://xml.org/sax/features/namespaces"));
saxFac.setNamespaceAware(true);
// Enable namespace parsing
System.out.println(saxFac.getFeature("http://xml.org/sax/features/namespaces"));
saxFac.setNamespaceAware(true);
saxFac.setValidating(true);
SAXParser parser = saxFac.newSAXParser();
parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
saxFac.setValidating(true);
SAXParser parser = saxFac.newSAXParser();
parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
parser.parse(this.getClass().getResource("toys.xml").getFile(), handler);
} catch (ParserConfigurationException e) {
e.printStackTrace();
Assert.fail("ParserConfigurationException in testParse02()");
} catch (SAXException e) {
e.printStackTrace();
Assert.fail("SAXException in testParse02()");
} catch (IOException e) {
e.printStackTrace();
Assert.fail("IOException in testParse02()");
}
parser.parse(this.getClass().getResource("toys.xml").getFile(), handler);
}
@Test
public void testParse03() {
System.out.println("===in testParse03===");
try {
DefaultHandler handler = new MyDefaultHandler2();
public void testParse03() throws Exception {
DefaultHandler handler = new MyDefaultHandler2();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
System.out.println("XMLReader : " + xmlReader.getProperty("http://xml.org/sax/properties/declaration-handler"));
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
System.out.println("XMLReader : " + xmlReader.getProperty("http://xml.org/sax/properties/declaration-handler"));
SAXParserFactory saxFac = SAXParserFactory.newInstance();
SAXParser parser = saxFac.newSAXParser();
parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
System.out.println("SAXParser : " + parser.getProperty("http://xml.org/sax/properties/declaration-handler"));
// From https://docs.oracle.com/javase/7/docs/api,
// ParserAdapter.setProperty() and ParserAdapter.getProperty() does
// not support any property currently.
try {
ParserAdapter adapter = new ParserAdapter(parser.getParser());
System.out.println("ParserAdapter : " + adapter.getProperty("http://xml.org/sax/properties/declaration-handler"));
} catch (SAXNotRecognizedException e) {
System.out.println("Expected SAXNotRecognizedException since ParserAdapter.getProperty() does not support any property currently");
}
try {
ParserAdapter adapter = new ParserAdapter(parser.getParser());
adapter.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
} catch (SAXNotRecognizedException e) {
System.out.println("Expected SAXNotRecognizedException since ParserAdapter.setProperty() does not support any property currently");
}
} catch (SAXException e) {
e.printStackTrace();
Assert.fail("SAXException in testParse03()");
} catch (ParserConfigurationException e) {
e.printStackTrace();
Assert.fail("ParserConfigurationException in testParse03()");
}
SAXParserFactory saxFac = SAXParserFactory.newInstance();
SAXParser parser = saxFac.newSAXParser();
parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
System.out.println("SAXParser : " + parser.getProperty("http://xml.org/sax/properties/declaration-handler"));
// From https://docs.oracle.com/javase/7/docs/api,
// ParserAdapter.setProperty() and ParserAdapter.getProperty() does
// not support any property currently.
ParserAdapter adapter = new ParserAdapter(parser.getParser());
assertThrows(SAXNotRecognizedException.class, () -> adapter.getProperty("http://xml.org/sax/properties/declaration-handler"));
assertThrows(SAXNotRecognizedException.class, () -> adapter.setProperty("http://xml.org/sax/properties/declaration-handler", handler));
}
@Test
public void testParse04() {
System.out.println("===in testParse04===");
try {
DefaultHandler handler = new MyDefaultHandler2();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
System.out.println(xmlReader.getFeature("http://xml.org/sax/features/namespaces"));
xmlReader.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
xmlReader.setContentHandler(handler);
public void testParse04() throws Exception {
DefaultHandler handler = new MyDefaultHandler2();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
System.out.println(xmlReader.getFeature("http://xml.org/sax/features/namespaces"));
xmlReader.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
xmlReader.setContentHandler(handler);
xmlReader.parse(this.getClass().getResource("toys.xml").getFile());
} catch (SAXException e) {
e.printStackTrace();
Assert.fail("SAXException in testParse04()");
} catch (IOException e) {
e.printStackTrace();
Assert.fail("IOException in testParse04()");
}
xmlReader.parse(this.getClass().getResource("toys.xml").getFile());
}
@Test
public void testParse05() {
System.out.println("===in testParse05===");
try {
DefaultHandler handler = new MyDefaultHandler2();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
XMLFilterImpl filterImpl = new XMLFilterImpl(xmlReader);
System.out.println(xmlReader.getFeature("http://xml.org/sax/features/namespaces"));
filterImpl.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
filterImpl.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
filterImpl.setContentHandler(handler);
public void testParse05() throws Exception {
DefaultHandler handler = new MyDefaultHandler2();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
XMLFilterImpl filterImpl = new XMLFilterImpl(xmlReader);
System.out.println(xmlReader.getFeature("http://xml.org/sax/features/namespaces"));
filterImpl.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
filterImpl.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
filterImpl.setContentHandler(handler);
filterImpl.parse(this.getClass().getResource("toys.xml").getFile());
} catch (SAXException e) {
e.printStackTrace();
Assert.fail("SAXException in testParse05()");
} catch (IOException e) {
e.printStackTrace();
Assert.fail("IOException in testParse05()");
}
filterImpl.parse(this.getClass().getResource("toys.xml").getFile());
}
@Test
public void testParse06() {
System.out.println("===in testParse06===");
try {
DefaultHandler handler = new MyDefaultHandler2();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
XMLFilterImpl filterImpl = new XMLFilterImpl(xmlReader);
System.out.println(xmlReader.getFeature("http://xml.org/sax/features/namespaces"));
filterImpl.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
filterImpl.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
filterImpl.setContentHandler(handler);
public void testParse06() throws Exception {
DefaultHandler handler = new MyDefaultHandler2();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
XMLFilterImpl filterImpl = new XMLFilterImpl(xmlReader);
System.out.println(xmlReader.getFeature("http://xml.org/sax/features/namespaces"));
filterImpl.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
filterImpl.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
filterImpl.setContentHandler(handler);
AssertJUnit.assertTrue(filterImpl.getProperty("http://xml.org/sax/properties/declaration-handler") instanceof DefaultHandler2);
assertInstanceOf(DefaultHandler2.class, filterImpl.getProperty("http://xml.org/sax/properties/declaration-handler"));
// filterImpl.setFeature("http://xml.org/sax/features/external-general-entities",
// false) ;
// filterImpl.setFeature("http://xml.org/sax/features/external-parameter-entities",
// false) ;
filterImpl.skippedEntity("name2");
// filterImpl.setFeature("http://xml.org/sax/features/external-general-entities",
// false) ;
// filterImpl.setFeature("http://xml.org/sax/features/external-parameter-entities",
// false) ;
filterImpl.skippedEntity("name2");
filterImpl.parse(this.getClass().getResource("toys.xml").getFile());
} catch (SAXException e) {
e.printStackTrace();
Assert.fail("SAXException in testParse06()");
} catch (IOException e) {
e.printStackTrace();
Assert.fail("IOException in testParse06()");
}
filterImpl.parse(this.getClass().getResource("toys.xml").getFile());
}
@Test
public void testParse07() {
System.out.println("===in testParse07===");
try {
DefaultHandler handler = new MyDefaultHandler2();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
XMLFilterImpl filterImpl = new XMLFilterImpl(xmlReader);
System.out.println(xmlReader.getFeature("http://xml.org/sax/features/namespaces"));
filterImpl.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
filterImpl.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
filterImpl.setContentHandler(handler);
filterImpl.setErrorHandler(handler);
AssertJUnit.assertTrue(filterImpl.getProperty("http://xml.org/sax/properties/declaration-handler") instanceof DefaultHandler2);
public void testParse07() throws Exception {
DefaultHandler handler = new MyDefaultHandler2();
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
XMLFilterImpl filterImpl = new XMLFilterImpl(xmlReader);
System.out.println(xmlReader.getFeature("http://xml.org/sax/features/namespaces"));
filterImpl.setProperty("http://xml.org/sax/properties/declaration-handler", handler);
filterImpl.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
filterImpl.setContentHandler(handler);
filterImpl.setErrorHandler(handler);
assertInstanceOf(DefaultHandler2.class, filterImpl.getProperty("http://xml.org/sax/properties/declaration-handler"));
filterImpl.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true);
filterImpl.parse(this.getClass().getResource("toys_error.xml").getFile());
} catch (SAXException e) {
e.printStackTrace();
Assert.fail("SAXException in testParse07()");
} catch (IOException e) {
e.printStackTrace();
Assert.fail("IOException in testParse07()");
}
filterImpl.setFeature("http://apache.org/xml/features/continue-after-fatal-error", true);
filterImpl.parse(this.getClass().getResource("toys_error.xml").getFile());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,78 +23,50 @@
package sax;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.Attributes;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.StringReader;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 6809409
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.IssueTracker56Test
* @run junit/othervm sax.IssueTracker56Test
* @summary Test SAXException has Cause.
*/
public class IssueTracker56Test {
@Test
public void testException() {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
String xmlToParse = "<root>Issue 56: SAXException does not do the exception chaining properly</root>";
InputSource source = new InputSource(new StringReader(xmlToParse));
parser.parse(source, new MyHandler());
} catch (SAXException ex) {
System.out.println(ex.getCause());
if (ex.getCause() == null)
Assert.fail("failed chaining exception properly.");
// ex.printStackTrace(); //will not print out root cause without the
// fix
} catch (IOException ex) {
// shouldn't happen
} catch (ParserConfigurationException ex) {
// shouldn't happen
}
public void testException() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
String xmlToParse = "<root>Issue 56: SAXException does not do the exception chaining properly</root>";
InputSource source = new InputSource(new StringReader(xmlToParse));
SAXException ex = assertThrows(SAXException.class, () -> parser.parse(source, new MyHandler()));
assertNotNull(ex.getCause(), "failed chaining exception properly.");
}
@Test
public void testWorkAround() throws Exception {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
String xmlToParse = "<root>Issue 56: SAXException does not do the exception chaining properly</root>";
InputSource source = new InputSource(new StringReader(xmlToParse));
parser.parse(source, new MyHandler1());
} catch (SAXException ex) {
System.out.println(ex.getCause());
// ex.printStackTrace(); //will print out root cause
} catch (IOException ex) {
// shouldn't happen
} catch (ParserConfigurationException ex) {
// shouldn't happen
}
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
String xmlToParse = "<root>Issue 56: SAXException does not do the exception chaining properly</root>";
InputSource source = new InputSource(new StringReader(xmlToParse));
assertThrows(SAXException.class, () -> parser.parse(source, new MyHandler1()));
}
public class MyHandler extends DefaultHandler implements ErrorHandler {
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public static class MyHandler extends DefaultHandler implements ErrorHandler {
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
try {
System.out.println(uri);
@ -104,23 +76,9 @@ public class IssueTracker56Test {
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
}
public void characters(char ch[], int start, int length) throws SAXException {
}
}
public class MyHandler1 extends DefaultHandler implements ErrorHandler {
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public static class MyHandler1 extends DefaultHandler implements ErrorHandler {
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXExceptionExt {
try {
System.out.println(uri);
@ -130,12 +88,5 @@ public class IssueTracker56Test {
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
}
public void characters(char ch[], int start, int length) throws SAXException {
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2014, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,17 +23,20 @@
package sax;
import org.junit.jupiter.api.Test;
import org.xml.sax.helpers.NamespaceSupport;
import java.util.Enumeration;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import org.xml.sax.helpers.NamespaceSupport;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.NSSupportTest
* @run junit/othervm sax.NSSupportTest
* @summary Test NamespaceSupport.
*/
public class NSSupportTest {
@ -48,14 +51,14 @@ public class NSSupportTest {
String[] parts = new String[3];
nssupport.processName("dc:name1", parts, false);
Assert.assertTrue(parts[0].equals("http://www.purl.org/dc"));
Assert.assertTrue(parts[1].equals("name1"));
Assert.assertTrue(parts[2].equals("dc:name1"));
assertEquals("http://www.purl.org/dc", parts[0]);
assertEquals("name1", parts[1]);
assertEquals("dc:name1", parts[2]);
nssupport.processName("name2", parts, false);
Assert.assertTrue(parts[0].equals("http://www.java.com"));
Assert.assertTrue(parts[1].equals("name2"));
Assert.assertTrue(parts[2].equals("name2"));
assertEquals("http://www.java.com", parts[0]);
assertEquals("name2", parts[1]);
assertEquals("name2", parts[2]);
}
@Test
@ -64,30 +67,30 @@ public class NSSupportTest {
NamespaceSupport nssupport = new NamespaceSupport();
nssupport.pushContext();
Assert.assertFalse(nssupport.isNamespaceDeclUris());
assertFalse(nssupport.isNamespaceDeclUris());
nssupport.declarePrefix("xmlns", "");
nssupport.processName("xmlns:name", parts, true);
Assert.assertNull(parts[0]);
Assert.assertNull(parts[1]);
Assert.assertNull(parts[2]);
assertNull(parts[0]);
assertNull(parts[1]);
assertNull(parts[2]);
nssupport.reset();
nssupport.setNamespaceDeclUris(true);
nssupport.declarePrefix("xmlns", "");
nssupport.processName("xmlns:name", parts, true);
Assert.assertTrue(parts[0].equals(NamespaceSupport.NSDECL));
Assert.assertTrue(parts[1].equals("name"));
Assert.assertTrue(parts[2].equals("xmlns:name"));
assertEquals(NamespaceSupport.NSDECL, parts[0]);
assertEquals("name", parts[1]);
assertEquals("xmlns:name", parts[2]);
nssupport.reset();
nssupport.setNamespaceDeclUris(true);
nssupport.declarePrefix("xml", "");
nssupport.processName("xml:name", parts, true);
Assert.assertTrue(parts[0].equals(NamespaceSupport.XMLNS));
Assert.assertTrue(parts[1].equals("name"));
Assert.assertTrue(parts[2].equals("xml:name"));
assertEquals(NamespaceSupport.XMLNS, parts[0]);
assertEquals("name", parts[1]);
assertEquals("xml:name", parts[2]);
}
@ -98,14 +101,14 @@ public class NSSupportTest {
nssupport.pushContext();
nssupport.declarePrefix("dc", "http://www.purl.org/dc");
Assert.assertEquals(nssupport.getPrefix("http://www.purl.org/dc"), "dc");
assertEquals("dc", nssupport.getPrefix("http://www.purl.org/dc"));
nssupport.popContext();
Assert.assertNull(nssupport.getPrefix("http://www.purl.org/dc"));
assertNull(nssupport.getPrefix("http://www.purl.org/dc"));
nssupport.processName("dc:name1", parts, false);
Assert.assertNull(parts[0]);
Assert.assertNull(parts[1]);
Assert.assertNull(parts[2]);
assertNull(parts[0]);
assertNull(parts[1]);
assertNull(parts[2]);
}
@Test
@ -124,9 +127,9 @@ public class NSSupportTest {
nssupport.declarePrefix("dc2", "http://www.purl.org/dc2");
nssupport.declarePrefix("dcnew", "http://www.purl.org/dcnew");
Enumeration enu1 = nssupport.getDeclaredPrefixes();
Enumeration<String> enu1 = nssupport.getDeclaredPrefixes();
while (enu1.hasMoreElements()) {
String str = (String) enu1.nextElement();
String str = enu1.nextElement();
if (str.equals("dc")) {
hasdc = true;
} else if (str.equals("dc1")) {
@ -137,8 +140,8 @@ public class NSSupportTest {
hasdcnew = true;
}
}
AssertJUnit.assertTrue(hasdcnew && hasdc1 && hasdc2);
AssertJUnit.assertFalse(hasdc);
assertTrue(hasdcnew && hasdc1 && hasdc2);
assertFalse(hasdc);
}
@Test
@ -157,9 +160,9 @@ public class NSSupportTest {
nssupport.declarePrefix("dc2", "http://www.purl.org/dc2");
nssupport.declarePrefix("dcnew", "http://www.purl.org/dcnew");
Enumeration enu1 = nssupport.getPrefixes();
Enumeration<String> enu1 = nssupport.getPrefixes();
while (enu1.hasMoreElements()) {
String str = (String) enu1.nextElement();
String str = enu1.nextElement();
if (str.equals("dc")) {
hasdc = true;
} else if (str.equals("dc1")) {
@ -170,7 +173,7 @@ public class NSSupportTest {
hasdcnew = true;
}
}
AssertJUnit.assertTrue(hasdcnew && hasdc1 && hasdc2 && hasdc);
assertTrue(hasdcnew && hasdc1 && hasdc2 && hasdc);
}
@Test
@ -189,9 +192,9 @@ public class NSSupportTest {
nssupport.declarePrefix("dc2", "http://www.purl.org/dc2");
nssupport.declarePrefix("dcnew", "http://www.purl.org/dcnew");
Enumeration enu1 = nssupport.getPrefixes("http://www.purl.org/dc");
Enumeration<String> enu1 = nssupport.getPrefixes("http://www.purl.org/dc");
while (enu1.hasMoreElements()) {
String str = (String) enu1.nextElement();
String str = enu1.nextElement();
if (str.equals("dc")) {
hasdc = true;
} else if (str.equals("dc1")) {
@ -202,9 +205,9 @@ public class NSSupportTest {
hasdcnew = true;
}
}
AssertJUnit.assertTrue(hasdc1 && hasdc);
AssertJUnit.assertFalse(hasdc2);
AssertJUnit.assertFalse(hasdcnew);
assertTrue(hasdc1 && hasdc);
assertFalse(hasdc2);
assertFalse(hasdcnew);
}
@Test
@ -219,13 +222,13 @@ public class NSSupportTest {
nssupport.declarePrefix("dc2", "http://www.purl.org/dc2");
nssupport.declarePrefix("dcnew", "http://www.purl.org/dcnew");
AssertJUnit.assertTrue(nssupport.getURI("dc").equals("http://www.purl.org/dc"));
AssertJUnit.assertTrue(nssupport.getURI("dc1").equals("http://www.purl.org/dc"));
AssertJUnit.assertTrue(nssupport.getURI("dc2").equals("http://www.purl.org/dc2"));
AssertJUnit.assertTrue(nssupport.getURI("dcnew").equals("http://www.purl.org/dcnew"));
assertEquals("http://www.purl.org/dc", nssupport.getURI("dc"));
assertEquals("http://www.purl.org/dc", nssupport.getURI("dc1"));
assertEquals("http://www.purl.org/dc2", nssupport.getURI("dc2"));
assertEquals("http://www.purl.org/dcnew", nssupport.getURI("dcnew"));
// Negative test
Assert.assertNull(nssupport.getURI("wrong_prefix"));
Assert.assertNull(nssupport.getURI(""));
assertNull(nssupport.getURI("wrong_prefix"));
assertNull(nssupport.getURI(""));
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -27,12 +27,15 @@
* @summary The initCause() incorrectly initialize the cause in
* SAXException class when used with SAXException(String)
* constructor.
* @run testng/othervm sax.SAXExceptionInitCause
* @run junit/othervm sax.SAXExceptionInitCause
* @author aleksej.efimov@oracle.com
*/
package sax;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -40,9 +43,11 @@ import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class SAXExceptionInitCause {
@ -55,8 +60,8 @@ public class SAXExceptionInitCause {
serialSAX = pickleException(noCauseException);
deserializedException = unpickleException(serialSAX);
Assert.assertNull(deserializedException.getCause());
Assert.assertEquals(deserializedException.getMessage(), SAX_MESSAGE);
assertNull(deserializedException.getCause());
assertEquals(SAX_MESSAGE, deserializedException.getMessage());
}
@Test
@ -69,18 +74,18 @@ public class SAXExceptionInitCause {
serialSAX = pickleException(withCauseException);
deserializedException = unpickleException(serialSAX);
Assert.assertNotNull(deserializedException.getCause());
Assert.assertEquals(deserializedException.getMessage(), SAX_MESSAGE);
Assert.assertEquals(deserializedException.getCause().getMessage(), SAX_CAUSE_MESSAGE);
assertNotNull(deserializedException.getCause());
assertEquals(SAX_MESSAGE, deserializedException.getMessage());
assertEquals(SAX_CAUSE_MESSAGE, deserializedException.getCause().getMessage());
}
@Test
public void testCauseInitByCtor() throws Exception {
public void testCauseInitByCtor() {
// Check that constructor properly initializes cause
Exception cause = new Exception(SAX_CAUSE_MESSAGE);
SAXException exception = new SAXException(cause);
Assert.assertSame(exception.getCause(), cause);
Assert.assertSame(exception.getException(), cause);
assertSame(cause, exception.getCause());
assertSame(cause, exception.getException());
}
@Test
@ -89,8 +94,8 @@ public class SAXExceptionInitCause {
SAXException exception = new SAXException();
Exception cause = new Exception(SAX_CAUSE_MESSAGE);
exception.initCause(cause);
Assert.assertSame(exception.getCause(), cause);
Assert.assertSame(exception.getException(), cause);
assertSame(cause, exception.getCause());
assertSame(cause, exception.getException());
}
@Test
@ -100,48 +105,51 @@ public class SAXExceptionInitCause {
SAXException exception = new SAXException();
Throwable cause = new Throwable(SAX_CAUSE_MESSAGE);
exception.initCause(cause);
Assert.assertSame(exception.getCause(),cause);
Assert.assertNull(exception.getException());
assertSame(cause, exception.getCause());
assertNull(exception.getException());
}
@Test(expectedExceptions = IllegalStateException.class)
@Test
public void testInitCauseTwice() {
SAXException exception = new SAXException(new Exception(SAX_CAUSE_MESSAGE));
// Expecting IllegalStateException at this point
exception.initCause(new Exception(SAX_CAUSE_MESSAGE));
assertThrows(
IllegalStateException.class,
() -> exception.initCause(new Exception(SAX_CAUSE_MESSAGE)));
}
@Test
public void testLegacySerialCtor() throws Exception {
SAXException saxException8 = unpickleException(JDK8_SET_WITH_CTOR_ONLY);
Assert.assertNotNull(saxException8.getCause());
Assert.assertNotNull(saxException8.getException());
assertNotNull(saxException8.getCause());
assertNotNull(saxException8.getException());
}
@Test
public void testLegacySerialCtorAndInit() throws Exception {
SAXException saxException8 = unpickleException(JDK8_SET_WITH_CTOR_AND_INIT);
Assert.assertNotNull(saxException8.getCause());
Assert.assertNotNull(saxException8.getException());
assertNotNull(saxException8.getCause());
assertNotNull(saxException8.getException());
}
@Test
public void testLegacySerialInitCause() throws Exception {
SAXException saxException8 = unpickleException(JDK8_WITH_INIT_ONLY);
Assert.assertNotNull(saxException8.getCause());
Assert.assertNotNull(saxException8.getException());
assertNotNull(saxException8.getCause());
assertNotNull(saxException8.getException());
}
@Test
public void testLegacySerialNothingSet() throws Exception {
SAXException saxException8 = unpickleException(JDK8_NOTHING_SET);
Assert.assertNull(saxException8.getCause());
Assert.assertNull(saxException8.getException());
assertNull(saxException8.getCause());
assertNull(saxException8.getException());
}
@Test(expectedExceptions = InvalidClassException.class)
public void testReadObjectIllegalStateException() throws Exception {
SAXException saxException8 = unpickleException(JDK8_CHECK_ILLEGAL_STATE_EXCEPTION);
@Test
public void testReadObjectIllegalStateException() {
assertThrows(
InvalidClassException.class,
() -> unpickleException(JDK8_CHECK_ILLEGAL_STATE_EXCEPTION));
}
// Serialize SAXException to byte array
@ -164,8 +172,8 @@ public class SAXExceptionInitCause {
return saxException;
}
private static String SAX_MESSAGE = "SAXException message";
private static String SAX_CAUSE_MESSAGE = "SAXException cause message";
private static final String SAX_MESSAGE = "SAXException message";
private static final String SAX_CAUSE_MESSAGE = "SAXException cause message";
/* This is a serial form of ordinary SAXException serialized
* by the following JDK8 code:

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,24 +23,25 @@
package sax;
import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.annotations.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 8213734
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng sax.SAXParserTest
* @summary Tests functionalities for SAXParser.
* @run junit sax.SAXParserTest
* @summary Tests that failed parsing closes the file correctly.
*/
public class SAXParserTest {
@ -51,35 +52,24 @@ public class SAXParserTest {
*/
@Test
public void testCloseReaders() throws Exception {
if (!getSystemProperty("os.name").contains("Windows")) {
System.out.println("This test only needs to be run on Windows.");
return;
}
Path testFile = createTestFile(null, "Test");
Path testFile = createTestFile("Test");
System.out.println("Test file: " + testFile.toString());
SAXParserFactory factory = SAXParserFactory.newDefaultInstance();
SAXParser parser = factory.newSAXParser();
try {
parser.parse(testFile.toFile(), new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
throw new SAXException("Stop the parser.");
}
});
} catch (SAXException e) {
// Do nothing
}
// deletion failes on Windows when the file is not closed
Files.deleteIfExists(testFile);
DefaultHandler explodingHandler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
throw new SAXException("Stop the parser.");
}
};
assertThrows(SAXException.class, () -> parser.parse(testFile.toFile(), explodingHandler));
// Deletion would fail on Windows if the file was not closed.
Files.delete(testFile);
}
private static Path createTestFile(Path dir, String name) throws IOException {
private static Path createTestFile(String name) throws IOException {
Path path = Files.createTempFile(name, ".xml");
byte[] bytes = "<?xml version=\"1.0\"?><test a1=\"x\" a2=\"y\"/>"
.getBytes(StandardCharsets.UTF_8);
Files.write(path, bytes);
Files.writeString(path, "<?xml version=\"1.0\"?><test a1=\"x\" a2=\"y\"/>");
return path;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,20 +23,23 @@
package sax;
import java.io.StringReader;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.StringReader;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
/*
* @test
* @bug 8173390 8176168
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm -Djdk.xml.resetSymbolTable=false sax.SymbolTableResetTest
* @run testng/othervm -Djdk.xml.resetSymbolTable=true sax.SymbolTableResetTest
* @run junit/othervm -Djdk.xml.resetSymbolTable=false sax.SymbolTableResetTest
* @run junit/othervm -Djdk.xml.resetSymbolTable=true sax.SymbolTableResetTest
* @summary Test that SAXParser reallocates symbol table during
* subsequent parse operations
*/
@ -115,9 +118,9 @@ public class SymbolTableResetTest {
// Check symbol table references after two subsequent parse operations
if (resetExpected) {
Assert.assertNotSame(symTable1, symTable2, "Symbol table references");
assertNotSame(symTable1, symTable2, "Symbol table references");
} else {
Assert.assertSame(symTable1, symTable2, "Symbol table references");
assertSame(symTable1, symTable2, "Symbol table references");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -23,36 +23,26 @@
package sax;
import static jaxp.library.JAXPTestUtilities.clearSystemProperty;
import static jaxp.library.JAXPTestUtilities.setSystemProperty;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderAdapter;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 8158246 8316383
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sax.XMLReaderTest
* @run junit/othervm sax.XMLReaderTest
* @summary This class contains tests that cover the creation of XMLReader.
*/
public class XMLReaderTest {
private final String SAX_PROPNAME = "org.xml.sax.driver";
/*
* Clean up after test
*/
@AfterClass
public void cleanUp() throws Exception {
clearSystemProperty(SAX_PROPNAME);
}
private static final String SAX_PROPNAME = "org.xml.sax.driver";
/*
* @bug 8158246
@ -61,12 +51,16 @@ public class XMLReaderTest {
*
* Except test format, this test is the same as JCK's test Ctor003.
*/
@Test(expectedExceptions = SAXException.class)
@Test
public void testcreateXMLReader() throws SAXException, ParserConfigurationException {
String className = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader().getClass().getName();
setSystemProperty(SAX_PROPNAME, className + "nosuch");
XMLReaderAdapter adapter = new XMLReaderAdapter();
.getXMLReader().getClass().getName();
System.setProperty(SAX_PROPNAME, className + "nosuch");
try {
assertThrows(SAXException.class, XMLReaderAdapter::new);
} finally {
System.clearProperty(SAX_PROPNAME);
}
}
/*

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2024, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -22,19 +22,21 @@
*/
package sbd.test;
import java.io.File;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import static org.junit.jupiter.api.Assertions.assertThrows;
/*
* @test
* @bug 8326915
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
* @run testng/othervm sbd.test.ExternalRefTest
* @run junit/othervm sbd.test.ExternalRefTest
* @summary Part of the Secure-By-Default (SBD) project. This test verifies issues
* and error message improvements related to external references.
*/
@ -43,11 +45,10 @@ public class ExternalRefTest {
* @bug 8326915
* Verifies that SAXParseException rather than NPE is thrown when a validating
* parser is restricted from processing external references.
* @throws Exception if the test fails
*/
@Test
public void testValidatingParser() throws Exception {
Assert.assertThrows(SAXParseException.class, () -> validateWithParser());
public void testValidatingParser() {
assertThrows(SAXParseException.class, this::validateWithParser);
}
private void validateWithParser() throws Exception {