Skip to content

Commit 135a07d

Browse files
committed
Use enum singleton pattern to cache Schema
1 parent 4b40b64 commit 135a07d

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

platform-tests/src/test/java/org/junit/platform/console/tasks/XmlReportAssertions.java

+22-12
Original file line numberDiff line numberDiff line change
@@ -10,45 +10,55 @@
1010

1111
package org.junit.platform.console.tasks;
1212

13+
import static org.junit.jupiter.api.Assertions.fail;
14+
1315
import java.io.StringReader;
1416
import java.net.URL;
15-
import java.util.concurrent.atomic.AtomicReference;
1617

1718
import javax.xml.XMLConstants;
1819
import javax.xml.transform.stream.StreamSource;
1920
import javax.xml.validation.Schema;
2021
import javax.xml.validation.SchemaFactory;
2122
import javax.xml.validation.Validator;
2223

23-
import org.opentest4j.AssertionFailedError;
2424
import org.xml.sax.SAXException;
2525

2626
/**
2727
* @since 1.0
2828
*/
2929
class XmlReportAssertions {
3030

31-
private static AtomicReference<Schema> schema = new AtomicReference<>();
32-
3331
static void assertValidAccordingToJenkinsSchema(String content) throws Exception {
3432
try {
3533
// Schema is thread-safe, Validator is not
36-
Validator validator = getSchema().newValidator();
34+
Validator validator = CachedSchema.JENKINS.newValidator();
3735
validator.validate(new StreamSource(new StringReader(content)));
3836
}
3937
catch (SAXException e) {
40-
throw new AssertionFailedError("Invalid XML document: " + content, e);
38+
fail("Invalid XML document: " + content, e);
4139
}
4240
}
4341

44-
private static Schema getSchema() throws SAXException {
45-
if (schema.get() == null) {
46-
URL schemaFile = XmlReportsWritingListener.class.getResource("/jenkins-junit.xsd");
42+
private enum CachedSchema {
43+
44+
JENKINS("/jenkins-junit.xsd");
45+
46+
private final Schema schema;
47+
48+
CachedSchema(String resourcePath) {
49+
URL schemaFile = XmlReportsWritingListener.class.getResource(resourcePath);
4750
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
48-
Schema newSchema = schemaFactory.newSchema(schemaFile);
49-
schema.compareAndSet(null, newSchema);
51+
try {
52+
this.schema = schemaFactory.newSchema(schemaFile);
53+
}
54+
catch (SAXException e) {
55+
throw new RuntimeException("Failed to create schema using " + schemaFile, e);
56+
}
57+
}
58+
59+
Validator newValidator() {
60+
return schema.newValidator();
5061
}
51-
return schema.get();
5262
}
5363

5464
}

0 commit comments

Comments
 (0)