Compare commits

...

38 commits

Author SHA1 Message Date
Renzo Kottmann
46d061bdef Merge branch 'release/1.6.x' of https://projekte.kosit.org/kosit/validator into release/1.6.x 2025-11-07 15:16:10 +01:00
Philip Helger
e5acc2535b Updated API code snippet in readme for GitHub #117 2025-11-07 15:15:51 +01:00
Renzo Kottmann
7f180881bb Upgrade mvn owasp dep check to 12.1.8 2025-11-07 15:15:51 +01:00
Renzo Kottmann
829cbe7cc2 Merge branch 'release/1.6.x' of https://projekte.kosit.org/kosit/validator into release/1.6.x 2025-11-07 15:05:09 +01:00
Renzo Kottmann
28e85d3942 Upgrade mvn owasp dep check to 12.1.8 2025-11-07 15:04:48 +01:00
Philip Helger
af3ba73daf Updated API code snippet in readme for GitHub #117 2025-11-07 13:10:45 +01:00
Philip Helger
0e944616a5 Merge branch 'release/1.6.x' into 'main'
Update links to source code to current locations

See merge request kosit/validator!88
2025-11-07 13:00:53 +01:00
Renzo Kottmann
29766cf34b chore: Minor correction 2025-11-07 11:17:32 +01:00
Renzo Kottmann
091c2c643c Add Unreleased section to Changelog 2025-11-07 11:17:06 +01:00
Renzo Kottmann
535d88c829 [maven-release-plugin] prepare for next development iteration 2025-11-06 13:32:55 +01:00
Renzo Kottmann
f338f5f5f5 [maven-release-plugin] prepare release v1.6.0 2025-11-06 13:32:47 +01:00
Renzo Kottmann
32bec7c749 chore: add release date for 1.6.0 to Changelog 2025-11-06 13:23:14 +01:00
Renzo Kottmann
bbe93c965c Merge branch 'release/1.6.x' of https://projekte.kosit.org/kosit/validator into release/1.6.x 2025-11-05 18:34:11 +01:00
Renzo Kottmann
9601f921e5 chore: bump exec plugin to 3.6.2, use successCode for broken daemon shutdown 2025-11-05 18:32:34 +01:00
Renzo Kottmann
f412f72110 chore: bump exec plugin to 3.6.2, use successCode for broken daemon shutdown 2025-11-05 18:31:08 +01:00
Philip Helger
53a967f4a8 Official images 2025-11-05 14:01:29 +01:00
Philip Helger
140b6d009d Re-added Java 25 2025-11-05 13:55:49 +01:00
Philip Helger
f2d77b01e9 Version bump 2025-11-05 13:51:41 +01:00
Renzo Kottmann
6524c07631 Merge branch 'cleansing-ph-1.6' into 'release/1.6.x'
Replaced deprecated methods etc.

See merge request kosit/validator!77
2025-10-24 12:27:20 +02:00
Philip Helger
0b22c3ea91 Replaced deprecated methods etc. 2025-10-24 12:27:20 +02:00
Philip Helger
c030aaff02 Back to 24 2025-10-22 16:02:20 +02:00
Philip Helger
70f6026196 Add Java 25 instead of 24 2025-10-22 15:57:36 +02:00
Philip Helger
1da41a718f Enforcing specific Java versions for compilation 2025-10-22 15:54:07 +02:00
Philip Helger
be9dcaac03 Using release instead of source/target 2025-10-22 15:37:21 +02:00
Philip Helger
e6d537f78a Merge branch 'release/1.6.x' of https://projekte.kosit.org/kosit/validator.git into release/1.6.x 2025-10-22 15:33:37 +02:00
Philip Helger
9774dddb17 Lombok update for Java 25 2025-10-22 15:33:29 +02:00
Renzo Kottmann
1c5c3ab66f Add github #127 to changelog.md 2025-10-22 15:19:06 +02:00
Renzo Kottmann
8b869a7804 Merge branch '127-custom-error-level-java-result' into 'release/1.6.x'
Added custom error level to Result object.

See merge request kosit/validator!81
2025-10-22 14:59:35 +02:00
Marija Stojanovic
9ed443ffdb Added custom error level to Result object. 2025-10-22 14:59:35 +02:00
andreb
3c6b4d2e2e Merge branch 'main' into release/1.6.x
# Conflicts:
#	README.md
2025-10-06 09:08:21 +02:00
Philip Helger
705b0b2501 Updated examples + links 2025-09-10 14:52:29 +02:00
yunussozeri
1ed9377b83
Update links to source code to current locations
The links were old and not redirecting to the correct location
2025-09-08 14:43:51 +02:00
Renzo Kottmann
93a64223b8 minor grammar in README.md
(cherry picked from commit a96751e08f)

Co-authored-by: Renzo Kottmann <renzo.kottmann@finanzen.bremen.de>
2025-09-04 12:07:23 +02:00
Renzo Kottmann
16c6784c5b Merge branch 'version-badge' into 'main'
Added Maven Central badge

See merge request kosit/validator!78
2025-09-03 16:28:51 +02:00
Philip Helger
52e42fe6dc Removed ToC 2025-09-03 16:23:12 +02:00
Philip Helger
78e5d3d4ee Added badge, roadmap, contributors and license 2025-09-03 16:22:22 +02:00
Philip Helger
162339d485 Added Maven Central badge 2025-09-03 15:30:37 +02:00
Renzo Kottmann
fda9de5b3e Merge branch 'release/1.5.x' into 'main'
v1.5.2 release back to main

See merge request kosit/validator!75
2025-08-29 17:08:31 +02:00
54 changed files with 484 additions and 365 deletions

View file

@ -39,7 +39,7 @@ cache:
java-11: java-11:
extends: .java extends: .java
image: $CI_REGISTRY_IMAGE/maven:3-eclipse-temurin-11-alpine image: maven:3-eclipse-temurin-11-alpine
needs: [ ] needs: [ ]
script: script:
- mvn $MAVEN_CLI_OPTS $BUILD_PROPS $CI_JOB_TIMESTAMP install - mvn $MAVEN_CLI_OPTS $BUILD_PROPS $CI_JOB_TIMESTAMP install
@ -56,23 +56,27 @@ java-11:
java-11-openj9: java-11-openj9:
extends: .java_extended extends: .java_extended
image: $CI_REGISTRY_IMAGE/maven:3-jdk-11-openj9 image: maven:3-jdk-11-openj9
java-17: java-17:
extends: .java extends: .java
image: $CI_REGISTRY_IMAGE/maven:3-eclipse-temurin-17-alpine image: maven:3-eclipse-temurin-17-alpine
java-21: java-21:
extends: .java extends: .java
image: $CI_REGISTRY_IMAGE/maven:3-eclipse-temurin-21-alpine image: maven:3-eclipse-temurin-21-alpine
java-24: java-24:
extends: .java_extended extends: .java_extended
image: $CI_REGISTRY_IMAGE/maven:3-eclipse-temurin-24-alpine image: maven:3-eclipse-temurin-24-alpine
java-25:
extends: .java
image: maven:3-eclipse-temurin-25-alpine
deploy: deploy:
stage: deploy stage: deploy
image: $CI_REGISTRY_IMAGE/maven:3-eclipse-temurin-11-alpine image: maven:3-eclipse-temurin-11-alpine
needs: needs:
- job: java-11 - job: java-11
script: script:
@ -106,7 +110,7 @@ create-build-image:
owasp-check: owasp-check:
extends: .java extends: .java
image: $CI_REGISTRY_IMAGE/maven:3-eclipse-temurin-11-alpine image: maven:3-eclipse-temurin-11-alpine
needs: [ ] needs: [ ]
script: script:
- mvn $MAVEN_CLI_OPTS $BUILD_PROPS $CI_JOB_TIMESTAMP validate -Powasp-check - mvn $MAVEN_CLI_OPTS $BUILD_PROPS $CI_JOB_TIMESTAMP validate -Powasp-check

View file

@ -5,7 +5,15 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 1.6.0
## Unreleased
## 1.6.0 - 2025-11-07
### Added
- (CORE) [GitHub #127](https://github.com/itplr-kosit/validator/issues/127) New API method `Result.getCustomFailedAsserts()` to access failed asserts with custom error levels
### Fixed ### Fixed
@ -15,6 +23,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- (CORE) Migration from javax to jakarta xml bind - (CORE) Migration from javax to jakarta xml bind
- (DOC) [GitHub PR#132](https://github.com/itplr-kosit/validator/pull/132) Updated the link to the example Validator scenario configuration - (DOC) [GitHub PR#132](https://github.com/itplr-kosit/validator/pull/132) Updated the link to the example Validator scenario configuration
- (BUILD) Support for *building and compilation* is restricted to the following Java versions:
- Java 11: any version &ge; 11.0.23
- Java 12 to 16 will not work
- Java 17: any version &ge; 17.0.11
- Java 18 to 20 will not work
- Any version from Java 21 onwards will work
- The reason for this is the usage of the `-proc:full` compiler parameter which in turn is needed for Lombok usage in JDK 23+.
### Removed ### Removed

View file

@ -74,12 +74,12 @@ The [CLI documentation](./docs/cli.md) shows further configuration options.
The Validator can also be used in own Java Applications via the API. An example use of the API as follows: The Validator can also be used in own Java Applications via the API. An example use of the API as follows:
```java ```java
Path scenarios = Paths.get("scenarios.xml"); URL scenarios = this.getClass().getClassLoader().getResource("scenarios.xml");
Configuration config = Configuration.load(scenarios.toUri()); Configuration config = Configuration.load(scenarios.toURI()).build(ProcessorProvider.getProcessor());
Input document = InputFactory.read(testDocument);
Check validator = new DefaultCheck(config); Check validator = new DefaultCheck(config);
Result validationResult = validator.checkInput(document);
Input document = InputFactory.read(testDocument);
Result report = validator.checkInput(document);
// examine the result here // examine the result here
``` ```
@ -139,8 +139,8 @@ To use the standalone version with Maven coordinates, add the respective classif
This section describes the next steps planned in the Validator development. This section describes the next steps planned in the Validator development.
* Release version 1.6.0 based on Java 11 and using Jakarta 4.x. - Autumn 2025 * Version 1.5.x is frozen - no maintainance, no support
* Drop support of version 1.5.x when version 1.6 is released * Version 1.6.x - no feature development, but maintainance and best-effort support
* Develop version 2.0.0 which will include major API incompatibilities - Winter 2025 * Develop version 2.0.0 which will include major API incompatibilities - Winter 2025
* Rework scenarios.xml * Rework scenarios.xml
* Rework report output engine * Rework report output engine

44
pom.xml
View file

@ -6,7 +6,7 @@
<groupId>org.kosit</groupId> <groupId>org.kosit</groupId>
<artifactId>validator</artifactId> <artifactId>validator</artifactId>
<version>1.6.0-SNAPSHOT</version> <version>1.6.1-SNAPSHOT</version>
<description>KoSIT XML Validator against XSD and Schematron based on defined scenarios.</description> <description>KoSIT XML Validator against XSD and Schematron based on defined scenarios.</description>
<developers> <developers>
@ -15,7 +15,7 @@
<id>fabian.buettner</id> <id>fabian.buettner</id>
<name>Fabian Büttner</name> <name>Fabian Büttner</name>
<organization>KoSIT</organization> <organization>KoSIT</organization>
<organizationUrl>https://xeinkauf.de/</organizationUrl> <organizationUrl>https://xoev.de/</organizationUrl>
</developer> </developer>
<developer> <developer>
<id>renzo.kottmann</id> <id>renzo.kottmann</id>
@ -44,13 +44,13 @@
<version.jacoco>0.8.13</version.jacoco> <version.jacoco>0.8.13</version.jacoco>
<version.jaxb-api>4.0.2</version.jaxb-api> <version.jaxb-api>4.0.2</version.jaxb-api>
<version.jaxb-impl>4.0.5</version.jaxb-impl> <version.jaxb-impl>4.0.5</version.jaxb-impl>
<version.lombok>1.18.38</version.lombok> <version.lombok>1.18.42</version.lombok>
<version.mockito>4.11.0</version.mockito> <version.mockito>4.11.0</version.mockito>
<version.owasp-dependency-check>10.0.4</version.owasp-dependency-check> <version.owasp-dependency-check>12.1.8</version.owasp-dependency-check>
<version.rest-assured>5.5.5</version.rest-assured> <version.rest-assured>5.5.5</version.rest-assured>
<version.saxon-he>12.8</version.saxon-he> <version.saxon-he>12.8</version.saxon-he>
<version.slf4j>2.0.17</version.slf4j> <version.slf4j>2.0.17</version.slf4j>
<version.jaxb-maven-plugin>4.0.9</version.jaxb-maven-plugin> <version.jaxb-maven-plugin>4.0.11</version.jaxb-maven-plugin>
</properties> </properties>
<repositories> <repositories>
@ -239,8 +239,19 @@
<configuration> <configuration>
<rules> <rules>
<requireMavenVersion> <requireMavenVersion>
<version>[3.3.9,)</version> <!-- minimum for OWASP check-->
<version>[3.6.3,)</version>
</requireMavenVersion> </requireMavenVersion>
<requireJavaVersion>
<!-- Required for "-proc:full" required for Lombok:
Any Java 11 (LTS) >= 11.0.23
No Java 12 to 16
Any Java 17 (LTS) >= 17.0.11
No Java 18 to 20
Any Java 21 or higher
-->
<version>[11.0.23,12),[17.0.11,18),[21,)</version>
</requireJavaVersion>
</rules> </rules>
</configuration> </configuration>
</execution> </execution>
@ -251,9 +262,13 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version> <version>3.14.0</version>
<configuration> <configuration>
<source>11</source> <release>11</release>
<target>11</target>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<!-- This is required for Lombok only since JDK 23
Was backported to 17.0.11 and 11.0.23.
See: https://inside.java/2024/06/18/quality-heads-up/
-->
<proc>full</proc>
</configuration> </configuration>
</plugin> </plugin>
@ -444,7 +459,7 @@
<plugin> <plugin>
<groupId>org.codehaus.mojo</groupId> <groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId> <artifactId>exec-maven-plugin</artifactId>
<version>3.5.0</version> <version>3.6.2</version>
<executions> <executions>
<execution> <execution>
<id>run</id> <id>run</id>
@ -455,10 +470,15 @@
</execution> </execution>
</executions> </executions>
<configuration> <configuration>
<inheritIo>true</inheritIo>
<!-- have to catch exit codes, cause daemon throws 1 if shutdown is not proper-->
<successCodes>0,1</successCodes>
<executable>java</executable> <executable>java</executable>
<longClasspath>false</longClasspath> <longClasspath>false</longClasspath>
<async>true</async> <async>true</async>
<asyncDestroyOnShutdown>true</asyncDestroyOnShutdown> <asyncDestroyOnShutdown>true</asyncDestroyOnShutdown>
<cleanupDaemonThreads>false</cleanupDaemonThreads>
<arguments> <arguments>
<!--suppress MavenModelInspection --> <!--suppress MavenModelInspection -->
<argument>${jacocoFailsafe}</argument> <argument>${jacocoFailsafe}</argument>
@ -486,7 +506,7 @@
<target> <target>
<!-- schlafen um den Start des Daemon abzuwarten --> <!-- schlafen um den Start des Daemon abzuwarten -->
<sleep seconds="10" /> <sleep seconds="10" />
<echo>${jacoco.tcp.port}</echo> <echo>jacoco.tcp.port=${jacoco.tcp.port}</echo>
</target> </target>
</configuration> </configuration>
<executions> <executions>
@ -598,6 +618,10 @@
<artifactId>dependency-check-maven</artifactId> <artifactId>dependency-check-maven</artifactId>
<version>${version.owasp-dependency-check}</version> <version>${version.owasp-dependency-check}</version>
<configuration> <configuration>
<!-- Specifies if the build should be failed if a CVSS score
above a specified level is identified.
The default is 11 which means since the CVSS scores are 0-10,
by default the build will never fail.-->
<failBuildOnCVSS>0</failBuildOnCVSS> <failBuildOnCVSS>0</failBuildOnCVSS>
<suppressionFiles> <suppressionFiles>
<suppressionFile>${project.basedir}/owasp-suppressions.xml</suppressionFile> <suppressionFile>${project.basedir}/owasp-suppressions.xml</suppressionFile>

View file

@ -45,7 +45,7 @@ public interface Input {
/** /**
* The digest algorithm used for computing the {@link #getHashCode()} * The digest algorithm used for computing the {@link #getHashCode()}
* *
* @return the name of the digest algorith * @return the name of the digest algorithm
*/ */
String getDigestAlgorithm(); String getDigestAlgorithm();

View file

@ -22,6 +22,7 @@ import org.oclc.purl.dsdl.svrl.FailedAssert;
import org.oclc.purl.dsdl.svrl.SchematronOutput; import org.oclc.purl.dsdl.svrl.SchematronOutput;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import de.kosit.validationtool.impl.model.CustomFailedAssert;
import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmNode;
/** /**
@ -69,23 +70,31 @@ public interface Result {
/** /**
* Schnellzugriff auf die Empfehlung zur Weiterverarbeitung des Dokuments. * Schnellzugriff auf die Empfehlung zur Weiterverarbeitung des Dokuments.
* *
* @return true wenn {@link AcceptRecommendation#ACCEPTABLE} * @return <code>true</code> wenn {@link AcceptRecommendation#ACCEPTABLE}
*/ */
boolean isAcceptable(); boolean isAcceptable();
/** /**
* Gibt eine Liste mit gefundenen Schema-Validation-Fehler zurück. Diese Liste ist leer, wenn keine Fehler gefunden * Gibt eine Liste mit gefundenen Schema-Validation-Fehler zurück. Diese Liste ist leer, wenn keine Fehler gefunden
* wurden. * wurden.
*
* @return List of schema validation errors.
*/ */
List<XmlError> getSchemaViolations(); List<XmlError> getSchemaViolations();
/** /**
* Liefert die Ergebnisse der Schematron-Prüfungen, in der Reihenfolge der Szenario-Konfiguration. * Liefert die Ergebnisse der Schematron-Prüfungen, in der Reihenfolge der Szenario-Konfiguration.
* *
* @return Liste mit Schematron-Ergebnissen * @return List with Schematron results
*/ */
List<SchematronOutput> getSchematronResult(); List<SchematronOutput> getSchematronResult();
/**
* @return List of custom failed asserts per Schematron level. Only failed assertions with a custom level are
* contained. Never <code>null</code> but maybe empty.
*/
List<CustomFailedAssert> getCustomFailedAsserts();
/** /**
* Returns {@link org.oclc.purl.dsdl.svrl.FailedAssert FailedAsserts} of a schematron evaluation. * Returns {@link org.oclc.purl.dsdl.svrl.FailedAssert FailedAsserts} of a schematron evaluation.
* *
@ -96,14 +105,14 @@ public interface Result {
/** /**
* Liefert ein true, wenn keine Schema-Violations vorhanden sind. * Liefert ein true, wenn keine Schema-Violations vorhanden sind.
* *
* @return true wenn Schema-valide * @return <code>true</code> if XML Schema compliant
*/ */
boolean isSchemaValid(); boolean isSchemaValid();
/** /**
* Liefert ein true, wenn der Prüfling eine well-formed XML-Datei ist. * Liefert ein true, wenn der Prüfling eine well-formed XML-Datei ist.
* *
* @return true wenn well-formed * @return <code>true</code> if wellformed
*/ */
boolean isWellformed(); boolean isWellformed();
@ -111,7 +120,7 @@ public interface Result {
* Returns true, if schematron has been checked and the result does not contain any {@link FailedAssert * Returns true, if schematron has been checked and the result does not contain any {@link FailedAssert
* FailedAsserts}. * FailedAsserts}.
* *
* @return true, if valid * @return <code>true</code>, if valid
*/ */
boolean isSchematronValid(); boolean isSchematronValid();
} }

View file

@ -23,16 +23,14 @@ import java.util.Map;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import de.kosit.validationtool.cmd.assertions.AssertionType; import de.kosit.validationtool.cmd.assertions.AssertionType;
import de.kosit.validationtool.cmd.assertions.Assertions; import de.kosit.validationtool.cmd.assertions.Assertions;
import de.kosit.validationtool.impl.model.Result; import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.impl.tasks.CheckAction; import de.kosit.validationtool.impl.tasks.CheckAction;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XPathCompiler; import net.sf.saxon.s9api.XPathCompiler;
@ -56,12 +54,12 @@ class CheckAssertionAction implements CheckAction {
private Map<String, List<AssertionType>> mappedAssertions; private Map<String, List<AssertionType>> mappedAssertions;
private static boolean matches(String key, String name) { private static boolean matches(final String key, final String name) {
return key.startsWith(name) || (name + ".xml").endsWith(key); return key.startsWith(name) || (name + ".xml").endsWith(key);
} }
@Override @Override
public void check(Bag results) { public void check(final Bag results) {
log.info("Checking assertions for {}", results.getInput().getName()); log.info("Checking assertions for {}", results.getInput().getName());
final List<AssertionType> toCheck = findAssertions(results.getName()); final List<AssertionType> toCheck = findAssertions(results.getName());
final List<String> errors = new ArrayList<>(); final List<String> errors = new ArrayList<>();
@ -84,28 +82,28 @@ class CheckAssertionAction implements CheckAction {
} }
} }
private List<AssertionType> findAssertions(String name) { private List<AssertionType> findAssertions(final String name) {
return getMapped().entrySet().stream().filter(e -> matches(e.getKey(), name)).map(Map.Entry::getValue).findFirst().orElse(null); return getMapped().entrySet().stream().filter(e -> matches(e.getKey(), name)).map(Map.Entry::getValue).findFirst().orElse(null);
} }
private boolean check(XdmNode document, AssertionType assertion) { private boolean check(final XdmNode document, final AssertionType assertion) {
try { try {
final XPathSelector selector = createSelector(assertion); final XPathSelector selector = createSelector(assertion);
selector.setContextItem(document); selector.setContextItem(document);
return selector.effectiveBooleanValue(); return selector.effectiveBooleanValue();
} catch (SaxonApiException e) { } catch (final SaxonApiException e) {
log.error("Error evaluating assertion {} for {}", assertion.getTest(), assertion.getReportDoc(), e); log.error("Error evaluating assertion {} for {}", assertion.getTest(), assertion.getReportDoc(), e);
} }
return false; return false;
} }
private XPathSelector createSelector(AssertionType assertion) throws SaxonApiException { private XPathSelector createSelector(final AssertionType assertion) {
try { try {
final XPathCompiler compiler = getProcessor().newXPathCompiler(); final XPathCompiler compiler = getProcessor().newXPathCompiler();
assertions.getNamespace().forEach(ns -> compiler.declareNamespace(ns.getPrefix(), ns.getValue())); assertions.getNamespace().forEach(ns -> compiler.declareNamespace(ns.getPrefix(), ns.getValue()));
return compiler.compile(assertion.getTest()).load(); return compiler.compile(assertion.getTest()).load();
} catch (SaxonApiException e) { } catch (final SaxonApiException e) {
throw new IllegalStateException(String.format("Can not compile xpath match expression '%s'", throw new IllegalStateException(String.format("Can not compile xpath match expression '%s'",
StringUtils.isNotBlank(assertion.getTest()) ? assertion.getTest() : "EMPTY EXPRESSION"), e); StringUtils.isNotBlank(assertion.getTest()) ? assertion.getTest() : "EMPTY EXPRESSION"), e);
} }
@ -114,8 +112,8 @@ class CheckAssertionAction implements CheckAction {
private Map<String, List<AssertionType>> getMapped() { private Map<String, List<AssertionType>> getMapped() {
if (mappedAssertions == null) { if (mappedAssertions == null) {
mappedAssertions = new HashMap<>(); mappedAssertions = new HashMap<>();
for (AssertionType assertionType : assertions.getAssertion()) { for (final AssertionType assertionType : assertions.getAssertion()) {
List<AssertionType> list = mappedAssertions.computeIfAbsent(assertionType.getReportDoc(), k -> new ArrayList<>()); final List<AssertionType> list = mappedAssertions.computeIfAbsent(assertionType.getReportDoc(), k -> new ArrayList<>());
list.add(assertionType); list.add(assertionType);
} }
} }

View file

@ -95,6 +95,8 @@ public class CommandLineApplication {
return resultStatus; return resultStatus;
} }
// The signature is required, because the method is used a lambda
@SuppressWarnings("unused")
private static int logExecutionException(final Exception ex, final CommandLine cli, final ParseResult parseResult) { private static int logExecutionException(final Exception ex, final CommandLine cli, final ParseResult parseResult) {
final String message = isNotEmpty(ex.getMessage()) ? ex.getMessage() : "Es ist eine Fehler aufgetreten"; final String message = isNotEmpty(ex.getMessage()) ? ex.getMessage() : "Es ist eine Fehler aufgetreten";
Printer.writeErr(ex, message); Printer.writeErr(ex, message);

View file

@ -321,10 +321,8 @@ public class Validator {
private static URI determineRepository(final Path d) { private static URI determineRepository(final Path d) {
if (Files.isDirectory(d)) { if (Files.isDirectory(d)) {
return d.toUri(); return d.toUri();
} else {
throw new IllegalArgumentException(
String.format("Not a valid path for repository definition specified: '%s'", d.toAbsolutePath()));
} }
throw new IllegalArgumentException(String.format("Not a valid path for repository definition specified: '%s'", d.toAbsolutePath()));
} }

View file

@ -82,6 +82,7 @@ public class Grid {
* *
* @param name the name of the column * @param name the name of the column
* @param maxLength the max length of the column * @param maxLength the max length of the column
* @param minLength the minimum length of the column
*/ */
public ColumnDefinition(final String name, final int maxLength, final int minLength) { public ColumnDefinition(final String name, final int maxLength, final int minLength) {
this(name, maxLength, minLength, 1); this(name, maxLength, minLength, 1);
@ -91,7 +92,8 @@ public class Grid {
* Constructor. * Constructor.
* *
* @param name the name of the column * @param name the name of the column
* @param minLength the max length of the column * @param maxLength the max length of the column
* @param minLength the minimum length of the column
* @param maxLines the max lines per cell * @param maxLines the max lines per cell
*/ */
public ColumnDefinition(final String name, final int maxLength, final int minLength, final int maxLines) { public ColumnDefinition(final String name, final int maxLength, final int minLength, final int maxLines) {
@ -149,10 +151,6 @@ public class Grid {
this.text.add(txt); this.text.add(txt);
} }
public Cell(final Object object, final Code... codes) {
this(new Text(object, codes));
}
protected Line getFormattedLine(final int lineNumber, final ColumnDefinition def) { protected Line getFormattedLine(final int lineNumber, final ColumnDefinition def) {
final Line line = new Line(); final Line line = new Line();
int startSubstring = lineNumber * def.getLength(); int startSubstring = lineNumber * def.getLength();
@ -194,11 +192,6 @@ public class Grid {
} }
public Cell add(final Object object, final Code... codes) {
this.text.add(new Text(object, codes));
return this;
}
} }
private static final Format DEFAULT_FORMAT = new Format(); private static final Format DEFAULT_FORMAT = new Format();
@ -321,7 +314,7 @@ public class Grid {
} }
private static boolean isEmpty(final StringBuilder current) { private static boolean isEmpty(final StringBuilder current) {
return current.toString().replaceAll("\\|", "").trim().length() == 0; return current.toString().replace("|", "").trim().length() == 0;
} }
private int getMaxVirtualLine() { private int getMaxVirtualLine() {

View file

@ -16,8 +16,6 @@
package de.kosit.validationtool.config; package de.kosit.validationtool.config;
import static org.apache.commons.lang3.StringUtils.startsWith;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URI; import java.net.URI;
import java.util.HashMap; import java.util.HashMap;
@ -27,10 +25,7 @@ import java.util.stream.Collectors;
import javax.xml.validation.Schema; import javax.xml.validation.Schema;
import lombok.AccessLevel; import org.apache.commons.lang3.Strings;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import de.kosit.validationtool.api.Check; import de.kosit.validationtool.api.Check;
import de.kosit.validationtool.api.Configuration; import de.kosit.validationtool.api.Configuration;
@ -49,7 +44,10 @@ import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
import de.kosit.validationtool.model.scenarios.ResourceType; import de.kosit.validationtool.model.scenarios.ResourceType;
import de.kosit.validationtool.model.scenarios.ScenarioType; import de.kosit.validationtool.model.scenarios.ScenarioType;
import de.kosit.validationtool.model.scenarios.Scenarios; import de.kosit.validationtool.model.scenarios.Scenarios;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName; import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmNode;
@ -113,8 +111,8 @@ public class ConfigurationLoader {
private static boolean isSupportedDocument(final XdmNode doc) { private static boolean isSupportedDocument(final XdmNode doc) {
final XdmNode root = findRoot(doc); final XdmNode root = findRoot(doc);
final String frameworkVersion = root.getAttributeValue(new QName("frameworkVersion")); final String frameworkVersion = root.getAttributeValue(new QName("frameworkVersion"));
return startsWith(frameworkVersion, SUPPORTED_MAJOR_VERSION) return Strings.CS.startsWith(frameworkVersion, SUPPORTED_MAJOR_VERSION)
&& root.getNodeName().getNamespaceURI().equals(SUPPORTED_MAJOR_VERSION_SCHEMA); && root.getNodeName().getNamespace().equals(SUPPORTED_MAJOR_VERSION_SCHEMA);
} }
private static Scenario createFallback(final Scenarios scenarios, final ContentRepository repository) { private static Scenario createFallback(final Scenarios scenarios, final ContentRepository repository) {

View file

@ -44,18 +44,18 @@ abstract class BaseHandler implements HttpHandler {
throws IOException { throws IOException {
exchange.getResponseHeaders().add("Content-Type", contentType); exchange.getResponseHeaders().add("Content-Type", contentType);
exchange.sendResponseHeaders(statusCode, 0); exchange.sendResponseHeaders(statusCode, 0);
final OutputStream os = exchange.getResponseBody(); try ( final OutputStream os = exchange.getResponseBody() ) {
write.write(os); write.write(os);
os.close(); }
} }
protected static void error(final HttpExchange exchange, final int statusCode, final String message) throws IOException { protected static void error(final HttpExchange exchange, final int statusCode, final String message) throws IOException {
final byte[] bytes = message.getBytes(); final byte[] bytes = message.getBytes();
exchange.getResponseHeaders().add("Content-Type", "text/plain"); exchange.getResponseHeaders().add("Content-Type", "text/plain");
exchange.sendResponseHeaders(statusCode, bytes.length); exchange.sendResponseHeaders(statusCode, bytes.length);
final OutputStream os = exchange.getResponseBody(); try ( final OutputStream os = exchange.getResponseBody() ) {
os.write(bytes); os.write(bytes);
os.close(); }
} }
@FunctionalInterface @FunctionalInterface

View file

@ -17,11 +17,9 @@
package de.kosit.validationtool.impl; package de.kosit.validationtool.impl;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.List;
import java.util.StringJoiner; import java.util.StringJoiner;
import jakarta.xml.bind.ValidationEvent;
import jakarta.xml.bind.ValidationEventHandler;
import javax.xml.transform.ErrorListener; import javax.xml.transform.ErrorListener;
import javax.xml.transform.SourceLocator; import javax.xml.transform.SourceLocator;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
@ -30,11 +28,11 @@ import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; import org.xml.sax.SAXParseException;
import lombok.Getter;
import de.kosit.validationtool.model.reportInput.XMLSyntaxError; import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
import de.kosit.validationtool.model.reportInput.XMLSyntaxErrorSeverity; import de.kosit.validationtool.model.reportInput.XMLSyntaxErrorSeverity;
import jakarta.xml.bind.ValidationEvent;
import jakarta.xml.bind.ValidationEventHandler;
import lombok.Getter;
import net.sf.saxon.s9api.MessageListener2; import net.sf.saxon.s9api.MessageListener2;
import net.sf.saxon.s9api.QName; import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmNode;
@ -51,7 +49,7 @@ public class CollectingErrorEventHandler implements ValidationEventHandler, Erro
private static final int stopProcessCount = DEFAULT_ABORT_COUNT; private static final int stopProcessCount = DEFAULT_ABORT_COUNT;
private final Collection<XMLSyntaxError> errors = new ArrayList<>(); private final List<XMLSyntaxError> errors = new ArrayList<>();
private static XMLSyntaxError createError(final XMLSyntaxErrorSeverity severity, final String message) { private static XMLSyntaxError createError(final XMLSyntaxErrorSeverity severity, final String message) {
final XMLSyntaxError e = new XMLSyntaxError(); final XMLSyntaxError e = new XMLSyntaxError();

View file

@ -37,10 +37,6 @@ import javax.xml.validation.SchemaFactory;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import de.kosit.validationtool.api.ResolvingConfigurationStrategy; import de.kosit.validationtool.api.ResolvingConfigurationStrategy;
import de.kosit.validationtool.impl.Scenario.Transformation; import de.kosit.validationtool.impl.Scenario.Transformation;
import de.kosit.validationtool.impl.xml.RelativeUriResolver; import de.kosit.validationtool.impl.xml.RelativeUriResolver;
@ -49,7 +45,9 @@ import de.kosit.validationtool.model.scenarios.NamespaceType;
import de.kosit.validationtool.model.scenarios.ResourceType; import de.kosit.validationtool.model.scenarios.ResourceType;
import de.kosit.validationtool.model.scenarios.ScenarioType; import de.kosit.validationtool.model.scenarios.ScenarioType;
import de.kosit.validationtool.model.scenarios.ValidateWithSchematron; import de.kosit.validationtool.model.scenarios.ValidateWithSchematron;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.lib.UnparsedTextURIResolver; import net.sf.saxon.lib.UnparsedTextURIResolver;
import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.SaxonApiException;

View file

@ -24,14 +24,6 @@ import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.StringJoiner; import java.util.StringJoiner;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.JAXBIntrospector;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.ValidationEventHandler;
import jakarta.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName; import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLOutputFactory;
@ -44,6 +36,14 @@ import javax.xml.validation.Schema;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.JAXBIntrospector;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import jakarta.xml.bind.ValidationEventHandler;
import jakarta.xml.bind.annotation.XmlRegistry;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
/** /**
@ -219,6 +219,7 @@ public class ConversionService {
final XMLOutputFactory xof = XMLOutputFactory.newFactory(); final XMLOutputFactory xof = XMLOutputFactory.newFactory();
final XMLStreamWriter xmlStreamWriter = xof.createXMLStreamWriter(w); final XMLStreamWriter xmlStreamWriter = xof.createXMLStreamWriter(w);
if (null == introspector.getElementName(model)) { if (null == introspector.getElementName(model)) {
@SuppressWarnings({ "rawtypes", "unchecked" })
final JAXBElement jaxbElement = new JAXBElement(createQName(model), model.getClass(), model); final JAXBElement jaxbElement = new JAXBElement(createQName(model), model.getClass(), model);
marshaller.marshal(jaxbElement, xmlStreamWriter); marshaller.marshal(jaxbElement, xmlStreamWriter);
} else { } else {

View file

@ -20,19 +20,21 @@ import static de.kosit.validationtool.impl.DateFactory.createTimestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.Getter; import org.oclc.purl.dsdl.svrl.FailedAssert;
import lombok.extern.slf4j.Slf4j; import org.oclc.purl.dsdl.svrl.SchematronOutput;
import de.kosit.validationtool.api.Check; import de.kosit.validationtool.api.Check;
import de.kosit.validationtool.api.Configuration; import de.kosit.validationtool.api.Configuration;
import de.kosit.validationtool.api.Input; import de.kosit.validationtool.api.Input;
import de.kosit.validationtool.api.Result; import de.kosit.validationtool.api.Result;
import de.kosit.validationtool.api.XmlError; import de.kosit.validationtool.api.XmlError;
import de.kosit.validationtool.impl.model.CustomFailedAssert;
import de.kosit.validationtool.impl.tasks.CheckAction; import de.kosit.validationtool.impl.tasks.CheckAction;
import de.kosit.validationtool.impl.tasks.CheckAction.Bag; import de.kosit.validationtool.impl.tasks.CheckAction.Bag;
import de.kosit.validationtool.impl.tasks.ComputeAcceptanceAction; import de.kosit.validationtool.impl.tasks.ComputeAcceptanceAction;
@ -47,7 +49,10 @@ import de.kosit.validationtool.impl.xml.ProcessorProvider;
import de.kosit.validationtool.model.reportInput.CreateReportInput; import de.kosit.validationtool.model.reportInput.CreateReportInput;
import de.kosit.validationtool.model.reportInput.EngineType; import de.kosit.validationtool.model.reportInput.EngineType;
import de.kosit.validationtool.model.reportInput.XMLSyntaxError; import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
import de.kosit.validationtool.model.scenarios.ErrorLevelType;
import de.kosit.validationtool.model.scenarios.ScenarioType;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.Processor;
/** /**
@ -141,10 +146,31 @@ public class DefaultCheck implements Check {
result.setProcessingSuccessful(!t.isStopped() && t.isFinished()); result.setProcessingSuccessful(!t.isStopped() && t.isFinished());
result.setSchematronResult(t.getReportInput().getValidationResultsSchematron().stream().filter(e -> e.getResults() != null) result.setSchematronResult(t.getReportInput().getValidationResultsSchematron().stream().filter(e -> e.getResults() != null)
.map(e -> e.getResults().getSchematronOutput()).collect(Collectors.toList())); .map(e -> e.getResults().getSchematronOutput()).collect(Collectors.toList()));
result.setCustomFailedAsserts(buildCustomFailedAssertsList(t, result.getSchematronResult()));
return result; return result;
} }
private static List<XmlError> convertErrors(final Collection<XMLSyntaxError> errors) { private List<CustomFailedAssert> buildCustomFailedAssertsList(final Bag t, final List<SchematronOutput> schematronResult) {
// Get Map of Assertion ID to custom error levels for the current scenario
final Map<String, ErrorLevelType> customLevels = Optional.ofNullable(t.getScenarioSelectionResult())
.map(de.kosit.validationtool.impl.model.Result::getObject).map(Scenario::getConfiguration)
.map(ScenarioType::getCreateReport)
.map(r -> r.getCustomLevel().stream()
.flatMap(customLevel -> customLevel.getValue().stream().map(id -> Map.entry(id, customLevel.getLevel())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)))
.orElse(Collections.emptyMap());
// Now check all failed assertions of all schematron validations if they contain a failed assertion with one of
// the changed IDs
return schematronResult.stream().flatMap(x -> x.getActivePatternAndFiredRuleAndFailedAssert().stream())
.filter(FailedAssert.class::isInstance).map(FailedAssert.class::cast).filter(fa -> customLevels.containsKey(fa.getId()))
.map(fa -> new CustomFailedAssert(fa, customLevels.get(fa.getId()))).collect(Collectors.toList());
}
@SuppressWarnings("unchecked")
private static List<XmlError> convertErrors(final List<XMLSyntaxError> errors) {
// noinspection unchecked // noinspection unchecked
return (List<XmlError>) (List<?>) errors; return (List<XmlError>) (List<?>) errors;
} }

View file

@ -25,15 +25,14 @@ import org.oclc.purl.dsdl.svrl.SchematronOutput;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import de.kosit.validationtool.api.AcceptRecommendation; import de.kosit.validationtool.api.AcceptRecommendation;
import de.kosit.validationtool.api.Result; import de.kosit.validationtool.api.Result;
import de.kosit.validationtool.api.XmlError; import de.kosit.validationtool.api.XmlError;
import de.kosit.validationtool.impl.model.CustomFailedAssert;
import de.kosit.validationtool.model.reportInput.CreateReportInput; import de.kosit.validationtool.model.reportInput.CreateReportInput;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import net.sf.saxon.dom.NodeOverNodeInfo; import net.sf.saxon.dom.NodeOverNodeInfo;
import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmNode;
@ -67,6 +66,11 @@ public class DefaultResult implements Result {
@Setter(AccessLevel.PACKAGE) @Setter(AccessLevel.PACKAGE)
private List<SchematronOutput> schematronResult; private List<SchematronOutput> schematronResult;
/**
* List of custom failed asserts per Schematron level. Only failed assertions with a custom level are contained.
*/
private List<CustomFailedAssert> customFailedAsserts;
@Getter @Getter
@Setter @Setter
private boolean processingSuccessful; private boolean processingSuccessful;
@ -149,19 +153,28 @@ public class DefaultResult implements Result {
} }
private <T> List<T> filterSchematronResult(final Class<T> type) { private <T> List<T> filterSchematronResult(final Class<T> type) {
return getSchematronResult() != null return this.schematronResult != null
? getSchematronResult().stream().flatMap(e -> e.getActivePatternAndFiredRuleAndFailedAssert().stream()) ? this.schematronResult.stream().flatMap(e -> e.getActivePatternAndFiredRuleAndFailedAssert().stream())
.filter(type::isInstance).map(type::cast).collect(Collectors.toList()) .filter(type::isInstance).map(type::cast).collect(Collectors.toList())
: Collections.emptyList(); : Collections.emptyList();
} }
private boolean isSchematronEvaluated() { private boolean isSchematronEvaluated() {
return getSchematronResult() != null return this.schematronResult != null
&& getSchematronResult().stream().noneMatch(e -> e.getActivePatternAndFiredRuleAndFailedAssert().isEmpty()); && this.schematronResult.stream().noneMatch(e -> e.getActivePatternAndFiredRuleAndFailedAssert().isEmpty());
} }
@Override @Override
public boolean isSchematronValid() { public boolean isSchematronValid() {
return isSchematronEvaluated() && getFailedAsserts().isEmpty(); return isSchematronEvaluated() && getFailedAsserts().isEmpty();
} }
@Override
public List<CustomFailedAssert> getCustomFailedAsserts() {
return this.customFailedAsserts;
}
public void setCustomFailedAsserts(List<CustomFailedAssert> customFailedAsserts) {
this.customFailedAsserts = customFailedAsserts;
}
} }

View file

@ -17,7 +17,6 @@
package de.kosit.validationtool.impl; package de.kosit.validationtool.impl;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -81,10 +80,9 @@ public class ScenarioRepository {
if (collect.size() == 1) { if (collect.size() == 1) {
result = new Result<>(collect.get(0)); result = new Result<>(collect.get(0));
} else if (collect.isEmpty()) { } else if (collect.isEmpty()) {
result = new Result<>(getFallbackScenario(), result = new Result<>(getFallbackScenario(), Arrays.asList("None of the loaded scenarios matches the specified document"));
Collections.singleton("None of the loaded scenarios matches the specified document"));
} else { } else {
result = new Result<>(getFallbackScenario(), Collections.singleton("More than one scenario matches the specified document")); result = new Result<>(getFallbackScenario(), Arrays.asList("More than one scenario matches the specified document"));
} }
return result; return result;

View file

@ -19,18 +19,18 @@ package de.kosit.validationtool.impl.input;
import static org.apache.commons.lang3.StringUtils.defaultIfBlank; import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
import java.io.IOException; import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import jakarta.xml.bind.util.JAXBSource;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource; import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.input.ReaderInputStream; import org.apache.commons.io.input.ReaderInputStream;
import jakarta.xml.bind.util.JAXBSource;
import lombok.Getter; import lombok.Getter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.om.TreeInfo; import net.sf.saxon.om.TreeInfo;
/** /**
@ -102,7 +102,7 @@ public class SourceInput extends AbstractInput {
return isStreamSource(); return isStreamSource();
} }
private boolean isConsumed() throws IOException { private boolean isConsumed() {
if (isStreamSource()) { if (isStreamSource()) {
final StreamSource ss = (StreamSource) this.source; final StreamSource ss = (StreamSource) this.source;
@ -140,7 +140,13 @@ public class SourceInput extends AbstractInput {
if (ss.getInputStream() != null) { if (ss.getInputStream() != null) {
result = new StreamSource(wrap(ss.getInputStream()), this.source.getSystemId()); result = new StreamSource(wrap(ss.getInputStream()), this.source.getSystemId());
} else if (ss.getReader() != null) { } else if (ss.getReader() != null) {
result = new StreamSource(wrap(new ReaderInputStream(ss.getReader(), Charset.defaultCharset())), this.source.getSystemId()); try {
result = new StreamSource(
wrap(ReaderInputStream.builder().setReader(ss.getReader()).setCharset(Charset.defaultCharset()).get()),
this.source.getSystemId());
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
} }
} }
return result; return result;

View file

@ -20,13 +20,14 @@ import java.io.BufferedInputStream;
import java.io.FilterInputStream; import java.io.FilterInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UncheckedIOException;
import java.security.DigestInputStream; import java.security.DigestInputStream;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.input.CountingInputStream; import org.apache.commons.io.input.BoundedInputStream;
import de.kosit.validationtool.api.Input; import de.kosit.validationtool.api.Input;
@ -39,7 +40,7 @@ public class StreamHelper {
/** /**
* Helper class, which generates the hashcode while reading the stream e.g. for parsing the document. This allows * Helper class, which generates the hashcode while reading the stream e.g. for parsing the document. This allows
* generating the hashcode without an aditional reading step. * generating the hashcode without an additional reading step.
*/ */
@SuppressWarnings("squid:S4929") // efficient read is done by internally used stream @SuppressWarnings("squid:S4929") // efficient read is done by internally used stream
private static class DigestingInputStream extends FilterInputStream { private static class DigestingInputStream extends FilterInputStream {
@ -96,15 +97,15 @@ public class StreamHelper {
private final LazyReadInput reference; private final LazyReadInput reference;
public CountInputStream(final LazyReadInput input, final InputStream stream) { public CountInputStream(final LazyReadInput input, final InputStream stream) throws IOException {
super(new org.apache.commons.io.input.CountingInputStream(stream)); super(BoundedInputStream.builder().setInputStream(stream).get());
this.reference = input; this.reference = input;
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
super.close(); super.close();
this.reference.setLength(((CountingInputStream) this.in).getByteCount()); this.reference.setLength(((BoundedInputStream) this.in).getCount());
} }
} }
@ -130,19 +131,24 @@ public class StreamHelper {
/** /**
* Wraps the {@link InputStream} with a counting length implementation. * Wraps the {@link InputStream} with a counting length implementation.
* *
* @param input the {@link LazyReadInput input} * @param input the lazy read input
* @param stream the stream * @param stream the stream
* @return a wrapped stream * @return a wrapped stream
*/ */
public static InputStream wrapCount(final LazyReadInput input, final InputStream stream) { public static InputStream wrapCount(final LazyReadInput input, final InputStream stream) {
return new CountInputStream(input, stream); try {
return new CountInputStream(input, stream);
} catch (final IOException ex) {
throw new UncheckedIOException(ex);
}
} }
/** /**
* Wraps the {@link InputStream} with an implementation the generates a hash sum over the stream data. * Wraps the {@link InputStream} with an implementation the generates a hash sum over the stream data.
* *
* @param input the {@link LazyReadInput input} * @param input the lazy read input
* @param stream the stream * @param stream the stream
* @param digestAlgorithm the message digest algorithm to use
* @return a wrapped stream * @return a wrapped stream
*/ */
public static InputStream wrapDigesting(final LazyReadInput input, final InputStream stream, final String digestAlgorithm) { public static InputStream wrapDigesting(final LazyReadInput input, final InputStream stream, final String digestAlgorithm) {
@ -175,7 +181,7 @@ public class StreamHelper {
* @param input the input * @param input the input
* @throws IOException on I/O errors * @throws IOException on I/O errors
*/ */
@SuppressWarnings("squid:S1854") @SuppressWarnings({ "squid:S1854", "unused" })
public static void drain(final InputStream input) throws IOException { public static void drain(final InputStream input) throws IOException {
final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];

View file

@ -0,0 +1,41 @@
package de.kosit.validationtool.impl.model;
import java.util.Objects;
import org.oclc.purl.dsdl.svrl.FailedAssert;
import de.kosit.validationtool.model.scenarios.ErrorLevelType;
/**
* This class contains a single Schematron failed assertion that has a custom error level.
*
* @since 1.6.0
*/
public class CustomFailedAssert {
private final FailedAssert originalFailedAssert;
private final ErrorLevelType customLevelFlag;
/**
* Constructor
*
* @param failedAssert The failed assert from Schematron. May not be <code>null</code>.
* @param customLevelFlag The custom error level. May not be <code>null</code>.
*/
public CustomFailedAssert(final FailedAssert failedAssert, final ErrorLevelType customLevelFlag) {
Objects.requireNonNull(failedAssert);
Objects.requireNonNull(customLevelFlag);
this.originalFailedAssert = failedAssert;
this.customLevelFlag = customLevelFlag;
}
public FailedAssert getFailedAssert() {
return this.originalFailedAssert;
}
public ErrorLevelType getCustomLevelFlag() {
return this.customLevelFlag;
}
}

View file

@ -17,8 +17,8 @@
package de.kosit.validationtool.impl.model; package de.kosit.validationtool.impl.model;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Getter; import lombok.Getter;
@ -37,14 +37,14 @@ public class Result<T, E> {
private T object; private T object;
private Collection<E> errors = new ArrayList<>(); private List<E> errors = new ArrayList<>();
/** /**
* Erzeugt ein neues Ergebnis mit Fehler * Erzeugt ein neues Ergebnis mit Fehler
* *
* @param errors die Fehler * @param errors die Fehler
*/ */
public Result(Collection<E> errors) { public Result(final List<E> errors) {
this(null, errors); this(null, errors);
} }
@ -53,7 +53,7 @@ public class Result<T, E> {
* *
* @param o * @param o
*/ */
public Result(T o) { public Result(final T o) {
this(o, Collections.emptyList()); this(o, Collections.emptyList());
} }

View file

@ -21,10 +21,6 @@ import java.util.Collections;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import de.kosit.validationtool.api.AcceptRecommendation; import de.kosit.validationtool.api.AcceptRecommendation;
import de.kosit.validationtool.api.Input; import de.kosit.validationtool.api.Input;
import de.kosit.validationtool.impl.Scenario; import de.kosit.validationtool.impl.Scenario;
@ -32,7 +28,9 @@ import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.model.reportInput.CreateReportInput; import de.kosit.validationtool.model.reportInput.CreateReportInput;
import de.kosit.validationtool.model.reportInput.ProcessingError; import de.kosit.validationtool.model.reportInput.ProcessingError;
import de.kosit.validationtool.model.reportInput.XMLSyntaxError; import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmNode;
/** /**
@ -55,9 +53,9 @@ public interface CheckAction {
private Result<Scenario, String> scenarioSelectionResult; private Result<Scenario, String> scenarioSelectionResult;
@Setter(AccessLevel.NONE) @Setter(AccessLevel.NONE)
private CreateReportInput reportInput; private final CreateReportInput reportInput;
/** Das finale Ergebnis */ /** The final result */
private XdmNode report; private XdmNode report;
private boolean finished; private boolean finished;
@ -66,7 +64,7 @@ public interface CheckAction {
private AcceptRecommendation acceptStatus = AcceptRecommendation.UNDEFINED; private AcceptRecommendation acceptStatus = AcceptRecommendation.UNDEFINED;
/** Das zu prüfende Dokument */ /** The document to validate */
private Input input; private Input input;
private Result<XdmNode, XMLSyntaxError> parserResult; private Result<XdmNode, XMLSyntaxError> parserResult;
@ -85,7 +83,9 @@ public interface CheckAction {
} }
/** /**
* Signalisiert einen vorzeitigen Stop der Vearbeitung. * Indicates an early stop in processing.
*
* @param error Error text
*/ */
public void stopProcessing(final String error) { public void stopProcessing(final String error) {
stopProcessing(Collections.singleton(error)); stopProcessing(Collections.singleton(error));

View file

@ -17,19 +17,18 @@
package de.kosit.validationtool.impl.tasks; package de.kosit.validationtool.impl.tasks;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import de.kosit.validationtool.api.Input; import de.kosit.validationtool.api.Input;
import de.kosit.validationtool.impl.input.XdmNodeInput; import de.kosit.validationtool.impl.input.XdmNodeInput;
import de.kosit.validationtool.impl.model.Result; import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.model.reportInput.ValidationResultsWellformedness; import de.kosit.validationtool.model.reportInput.ValidationResultsWellformedness;
import de.kosit.validationtool.model.reportInput.XMLSyntaxError; import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
import de.kosit.validationtool.model.reportInput.XMLSyntaxErrorSeverity; import de.kosit.validationtool.model.reportInput.XMLSyntaxErrorSeverity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.s9api.DocumentBuilder; import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.SaxonApiException;
@ -75,7 +74,7 @@ public class DocumentParseAction implements CheckAction {
final XMLSyntaxError error = new XMLSyntaxError(); final XMLSyntaxError error = new XMLSyntaxError();
error.setSeverityCode(XMLSyntaxErrorSeverity.SEVERITY_FATAL_ERROR); error.setSeverityCode(XMLSyntaxErrorSeverity.SEVERITY_FATAL_ERROR);
error.setMessage(String.format("IOException while reading resource %s: %s", content.getName(), e.getMessage())); error.setMessage(String.format("IOException while reading resource %s: %s", content.getName(), e.getMessage()));
result = new Result<>(Collections.singleton(error)); result = new Result<>(Arrays.asList(error));
} }
return result; return result;

View file

@ -31,12 +31,6 @@ import javax.xml.validation.Validator;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import de.kosit.validationtool.api.Input; import de.kosit.validationtool.api.Input;
import de.kosit.validationtool.impl.CollectingErrorEventHandler; import de.kosit.validationtool.impl.CollectingErrorEventHandler;
import de.kosit.validationtool.impl.Scenario; import de.kosit.validationtool.impl.Scenario;
@ -45,7 +39,11 @@ import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.model.reportInput.CreateReportInput; import de.kosit.validationtool.model.reportInput.CreateReportInput;
import de.kosit.validationtool.model.reportInput.ValidationResultsXmlSchema; import de.kosit.validationtool.model.reportInput.ValidationResultsXmlSchema;
import de.kosit.validationtool.model.reportInput.XMLSyntaxError; import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer; import net.sf.saxon.s9api.Serializer;
@ -216,7 +214,7 @@ public class SchemaValidationAction implements CheckAction {
} }
} }
private interface SerializedDocument extends AutoCloseable, SourceProvider { private interface SerializedDocument extends SourceProvider {
void serialize(XdmNode node) throws SaxonApiException, IOException; void serialize(XdmNode node) throws SaxonApiException, IOException;

View file

@ -22,7 +22,7 @@ import java.io.Reader;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.net.URL;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Strings;
import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSResourceResolver; import org.w3c.dom.ls.LSResourceResolver;
@ -90,7 +90,7 @@ public class ClassPathResourceResolver implements LSResourceResolver {
* @param basePath der Basispfad * @param basePath der Basispfad
*/ */
public ClassPathResourceResolver(final String basePath) { public ClassPathResourceResolver(final String basePath) {
if (!StringUtils.startsWith(basePath, "/")) { if (!Strings.CS.startsWith(basePath, "/")) {
throw new IllegalArgumentException("Base path must start with a slash"); throw new IllegalArgumentException("Base path must start with a slash");
} }
this.base = URI.create(basePath + (basePath.endsWith("/") == basePath.length() > 1 ? "" : "/")); this.base = URI.create(basePath + (basePath.endsWith("/") == basePath.length() > 1 ? "" : "/"));

View file

@ -26,7 +26,6 @@ import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import net.sf.saxon.Configuration; import net.sf.saxon.Configuration;
import net.sf.saxon.lib.StandardUnparsedTextResolver; import net.sf.saxon.lib.StandardUnparsedTextResolver;
import net.sf.saxon.lib.UnparsedTextURIResolver; import net.sf.saxon.lib.UnparsedTextURIResolver;
@ -54,10 +53,9 @@ public class RelativeUriResolver implements URIResolver, UnparsedTextURIResolver
throw new TransformerException(String.format("Can not resolve required %s", href), e); throw new TransformerException(String.format("Can not resolve required %s", href), e);
} }
} else {
throw new TransformerException(String
.format("The resolved transformation artifact %s is not within the configured repository %s", resolved, this.baseUri));
} }
throw new TransformerException(String.format("The resolved transformation artifact %s is not within the configured repository %s",
resolved, this.baseUri));
} }
/** /**
@ -96,10 +94,9 @@ public class RelativeUriResolver implements URIResolver, UnparsedTextURIResolver
public Reader resolve(final URI absoluteURI, final String encoding, final Configuration config) throws XPathException { public Reader resolve(final URI absoluteURI, final String encoding, final Configuration config) throws XPathException {
if (isUnderBaseUri(absoluteURI, this.baseUri)) { if (isUnderBaseUri(absoluteURI, this.baseUri)) {
return new StandardUnparsedTextResolver().resolve(absoluteURI, encoding, config); return new StandardUnparsedTextResolver().resolve(absoluteURI, encoding, config);
} else {
throw new XPathException(String.format("The resolved transformation artifact %s is not within the configured repository %s",
absoluteURI, this.baseUri));
} }
throw new XPathException(String.format("The resolved transformation artifact %s is not within the configured repository %s",
absoluteURI, this.baseUri));
} }
} }

View file

@ -25,16 +25,13 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.nio.file.Paths; import java.nio.file.Paths;
import javax.xml.transform.dom.DOMSource; import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.AttributesImpl;
@ -45,7 +42,6 @@ import de.kosit.validationtool.impl.TestObjectFactory;
import de.kosit.validationtool.impl.input.SourceInput; import de.kosit.validationtool.impl.input.SourceInput;
import de.kosit.validationtool.impl.model.Result; import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.model.reportInput.XMLSyntaxError; import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
import net.sf.saxon.dom.NodeOverNodeInfo; import net.sf.saxon.dom.NodeOverNodeInfo;
import net.sf.saxon.s9api.BuildingContentHandler; import net.sf.saxon.s9api.BuildingContentHandler;
import net.sf.saxon.s9api.DocumentBuilder; import net.sf.saxon.s9api.DocumentBuilder;
@ -61,9 +57,6 @@ public class InputFactoryTest {
public static final String SOME_VALUE = "some value"; public static final String SOME_VALUE = "some value";
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test @Test
public void testDefaultDigestAlgorithm() { public void testDefaultDigestAlgorithm() {
assertThat(new InputFactory().getAlgorithm()).isEqualTo(InputFactory.DEFAULT_ALGORITH); assertThat(new InputFactory().getAlgorithm()).isEqualTo(InputFactory.DEFAULT_ALGORITH);
@ -81,15 +74,13 @@ public class InputFactoryTest {
assertThat(s1).isNotEqualTo(s3); assertThat(s1).isNotEqualTo(s3);
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testWrongAlgorithm() { public void testWrongAlgorithm() {
this.expectedException.expect(IllegalArgumentException.class);
new InputFactory("unknown"); new InputFactory("unknown");
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testNullInputURL() { public void testNullInputURL() {
this.expectedException.expect(IllegalArgumentException.class);
InputFactory.read((URL) null); InputFactory.read((URL) null);
} }
@ -105,44 +96,40 @@ public class InputFactoryTest {
assertThat(input).isNotNull(); assertThat(input).isNotNull();
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testNullStream() { public void testNullStream() {
this.expectedException.expect(IllegalArgumentException.class); InputFactory.read((InputStream) null, SOME_VALUE);
final Input input = InputFactory.read((InputStream) null, SOME_VALUE);
} }
@Test @Test
public void testInputFile() throws URISyntaxException { public void testInputFile() {
final Input input = InputFactory.read(new File(Simple.SIMPLE_VALID)); final Input input = InputFactory.read(new File(Simple.SIMPLE_VALID));
assertThat(input).isNotNull(); assertThat(input).isNotNull();
} }
@Test @Test
public void testInputPath() throws URISyntaxException { public void testInputPath() {
final Input input = InputFactory.read(Paths.get(Simple.SIMPLE_VALID)); final Input input = InputFactory.read(Paths.get(Simple.SIMPLE_VALID));
assertThat(input).isNotNull(); assertThat(input).isNotNull();
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testNullInput() { public void testNullInput() {
this.expectedException.expect(IllegalArgumentException.class);
InputFactory.read((byte[]) null, SOME_VALUE); InputFactory.read((byte[]) null, SOME_VALUE);
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testNullInputName() { public void testNullInputName() {
this.expectedException.expect(IllegalArgumentException.class);
InputFactory.read(SOME_VALUE.getBytes(), null); InputFactory.read(SOME_VALUE.getBytes(), null);
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testEmptyInputName() throws IOException { public void testEmptyInputName() throws IOException {
this.expectedException.expect(IllegalArgumentException.class);
final Input input = InputFactory.read(SOME_VALUE.getBytes(), ""); final Input input = InputFactory.read(SOME_VALUE.getBytes(), "");
drain(input); drain(input);
} }
@Test @Test(expected = IllegalStateException.class)
public void testSourceInput() throws IOException { public void testSourceInput() throws IOException {
try ( final InputStream s = Simple.SIMPLE_VALID.toURL().openStream() ) { try ( final InputStream s = Simple.SIMPLE_VALID.toURL().openStream() ) {
final SourceInput input = (SourceInput) InputFactory.read(new StreamSource(s)); final SourceInput input = (SourceInput) InputFactory.read(new StreamSource(s));
@ -150,12 +137,11 @@ public class InputFactoryTest {
drain(input); drain(input);
assertThat(input.getHashCode()).isNotNull(); assertThat(input.getHashCode()).isNotNull();
assertThat(input.getLength()).isGreaterThan(0L); assertThat(input.getLength()).isGreaterThan(0L);
this.expectedException.expect(IllegalStateException.class);
input.getSource(); input.getSource();
} }
} }
@Test @Test(expected = IllegalStateException.class)
public void testSourceInputReader() throws IOException { public void testSourceInputReader() throws IOException {
try ( final InputStream s = Simple.SIMPLE_VALID.toURL().openStream(); try ( final InputStream s = Simple.SIMPLE_VALID.toURL().openStream();
final InputStreamReader reader = new InputStreamReader(s) ) { final InputStreamReader reader = new InputStreamReader(s) ) {
@ -164,14 +150,12 @@ public class InputFactoryTest {
drain(input); drain(input);
assertThat(input.getHashCode()).isNotNull(); assertThat(input.getHashCode()).isNotNull();
assertThat(input.getLength()).isGreaterThan(0L); assertThat(input.getLength()).isGreaterThan(0L);
this.expectedException.expect(IllegalStateException.class);
input.getSource(); input.getSource();
} }
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testUnexistingInput() { public void testUnexistingInput() {
this.expectedException.expect(IllegalArgumentException.class);
InputFactory.read(Simple.NOT_EXISTING); InputFactory.read(Simple.NOT_EXISTING);
} }

View file

@ -18,7 +18,6 @@ package de.kosit.validationtool.cmd;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
@ -45,11 +44,8 @@ public class CheckAssertionActionTest {
private static final URL SAMPLE_ASSERTIONS = CheckAssertionActionTest.class.getResource("/examples/assertions/tests-xrechnung.xml"); private static final URL SAMPLE_ASSERTIONS = CheckAssertionActionTest.class.getResource("/examples/assertions/tests-xrechnung.xml");
private CommandLine commandLine;
@Before @Before
public void setup() throws IOException { public void setup() {
this.commandLine = new CommandLine();
CommandLine.activate(); CommandLine.activate();
} }

View file

@ -46,6 +46,7 @@ public class CommandLine {
*/ */
private static class ReplaceableOutputStream<O extends OutputStream> extends OutputStream { private static class ReplaceableOutputStream<O extends OutputStream> extends OutputStream {
@SuppressWarnings("hiding")
@Getter @Getter
@Setter @Setter
private O out; private O out;

View file

@ -26,7 +26,7 @@ import java.nio.file.Paths;
import java.util.List; import java.util.List;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Strings;
import org.assertj.core.api.Condition; import org.assertj.core.api.Condition;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
@ -45,13 +45,10 @@ public class CommandlineApplicationTest {
public static final String RESULT_OUTPUT = "Processing 1 object(s) completed"; public static final String RESULT_OUTPUT = "Processing 1 object(s) completed";
private CommandLine commandLine;
private final Path output = Paths.get("target/test-output"); private final Path output = Paths.get("target/test-output");
@Before @Before
public void setup() throws IOException { public void setup() throws IOException {
this.commandLine = new CommandLine();
CommandLine.activate(); CommandLine.activate();
if (Files.exists(this.output)) { if (Files.exists(this.output)) {
FileUtils.deleteDirectory(this.output.toFile()); FileUtils.deleteDirectory(this.output.toFile());
@ -164,7 +161,7 @@ public class CommandlineApplicationTest {
final String[] args = { "-s", Paths.get(Simple.SCENARIOS).toString(), "-o", this.output.toString(), "-r", final String[] args = { "-s", Paths.get(Simple.SCENARIOS).toString(), "-o", this.output.toString(), "-r",
Paths.get(Simple.REPOSITORY_URI).toString(), Paths.get(Simple.EXAMPLES).toString() }; Paths.get(Simple.REPOSITORY_URI).toString(), Paths.get(Simple.EXAMPLES).toString() };
CommandLineApplication.mainProgram(args); CommandLineApplication.mainProgram(args);
assertThat(CommandLine.getErrorOutput()).contains("Processing 8 object(s) completed"); assertThat(CommandLine.getErrorOutput()).contains("Processing 9 object(s) completed");
} }
@Test @Test
@ -194,7 +191,7 @@ public class CommandlineApplicationTest {
CommandLineApplication.mainProgram(args); CommandLineApplication.mainProgram(args);
assertThat(CommandLine.getErrorOutput()).contains(RESULT_OUTPUT); assertThat(CommandLine.getErrorOutput()).contains(RESULT_OUTPUT);
assertThat(CommandLine.getOutputLines()).haveAtLeastOne(new Condition<>( assertThat(CommandLine.getOutputLines()).haveAtLeastOne(new Condition<>(
s -> StringUtils.contains(s, "<?xml version=\"1.0\" " + "encoding=\"UTF-8\"?>"), "Must " + "contain xml preambel")); s -> Strings.CS.contains(s, "<?xml version=\"1.0\" " + "encoding=\"UTF-8\"?>"), "Must " + "contain xml preambel"));
} }
@Test @Test
@ -242,7 +239,7 @@ public class CommandlineApplicationTest {
} }
@Test @Test
public void testAndre() throws IOException { public void testAndre() {
final String[] args = { "-s", Paths.get(Simple.SCENARIOS).toString(), "-r", Paths.get(Simple.REPOSITORY_URI).toString(), final String[] args = { "-s", Paths.get(Simple.SCENARIOS).toString(), "-r", Paths.get(Simple.REPOSITORY_URI).toString(),
Paths.get(Simple.SIMPLE_VALID).toString(), "--report-prefix", "andre1" }; Paths.get(Simple.SIMPLE_VALID).toString(), "--report-prefix", "andre1" };
CommandLineApplication.mainProgram(args); CommandLineApplication.mainProgram(args);

View file

@ -35,13 +35,10 @@ import de.kosit.validationtool.impl.tasks.CheckAction;
*/ */
public class PrintReportActionTest { public class PrintReportActionTest {
private CommandLine commandLine;
private PrintReportAction action; private PrintReportAction action;
@Before @Before
public void setup() { public void setup() {
this.commandLine = new CommandLine();
CommandLine.activate(); CommandLine.activate();
this.action = new PrintReportAction(TestObjectFactory.createProcessor()); this.action = new PrintReportAction(TestObjectFactory.createProcessor());
} }

View file

@ -20,15 +20,14 @@ import static de.kosit.validationtool.config.ConfigurationBuilder.report;
import static de.kosit.validationtool.config.ConfigurationBuilder.schematron; import static de.kosit.validationtool.config.ConfigurationBuilder.schematron;
import static de.kosit.validationtool.config.TestConfigurationFactory.createSimpleConfiguration; import static de.kosit.validationtool.config.TestConfigurationFactory.createSimpleConfiguration;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.net.URI; import java.net.URI;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.Date; import java.util.Date;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.impl.Helper; import de.kosit.validationtool.impl.Helper;
@ -41,58 +40,69 @@ public class ConfigurationBuilderTest {
public static final LocalDate EPOCH = LocalDate.of(1970, 1, 1); public static final LocalDate EPOCH = LocalDate.of(1970, 1, 1);
@Rule @Test(expected = IllegalStateException.class)
public ExpectedException exceptions = ExpectedException.none();
@Test
public void testNoConfiguration() { public void testNoConfiguration() {
this.exceptions.expect(IllegalStateException.class);
new ConfigurationBuilder().build(Helper.getTestProcessor()); new ConfigurationBuilder().build(Helper.getTestProcessor());
} }
@Test @Test
public void testNoFallback() { public void testNoFallback() {
this.exceptions.expect(IllegalStateException.class); try {
this.exceptions.expectMessage(Matchers.containsString("fallback")); final ConfigurationBuilder builder = createSimpleConfiguration();
final ConfigurationBuilder builder = createSimpleConfiguration(); builder.with((FallbackBuilder) null);
builder.with((FallbackBuilder) null); builder.build(Helper.getTestProcessor());
builder.build(Helper.getTestProcessor()); fail();
} catch (final IllegalStateException ex) {
assertTrue(ex.getMessage().contains("fallback"));
}
} }
@Test @Test
public void testNoSchema() { public void testNoSchema() {
this.exceptions.expect(IllegalStateException.class); try {
this.exceptions.expectMessage(Matchers.containsString("schema")); final ConfigurationBuilder builder = createSimpleConfiguration();
final ConfigurationBuilder builder = createSimpleConfiguration(); builder.getScenarios().get(0).validate((SchemaBuilder) null);
builder.getScenarios().get(0).validate((SchemaBuilder) null); builder.build(Helper.getTestProcessor());
builder.build(Helper.getTestProcessor()); fail();
} catch (final IllegalStateException ex) {
assertTrue(ex.getMessage().contains("schema"));
}
} }
@Test @Test
public void testInvalidSchematron() { public void testInvalidSchematron() {
this.exceptions.expect(IllegalStateException.class); try {
this.exceptions.expectMessage(Matchers.containsString("schematron")); final ConfigurationBuilder builder = createSimpleConfiguration();
final ConfigurationBuilder builder = createSimpleConfiguration(); builder.getScenarios().get(0).validate(schematron("invalid").source(URI.create("DoesNotExist")));
builder.getScenarios().get(0).validate(schematron("invalid").source(URI.create("DoesNotExist"))); builder.build(Helper.getTestProcessor());
builder.build(Helper.getTestProcessor()); fail();
} catch (final IllegalStateException ex) {
assertTrue(ex.getMessage().contains("schematron"));
}
} }
@Test @Test
public void testInsufficientSchematron() { public void testInsufficientSchematron() {
this.exceptions.expect(IllegalStateException.class); try {
this.exceptions.expectMessage(Matchers.containsString("schematron")); final ConfigurationBuilder builder = createSimpleConfiguration();
final ConfigurationBuilder builder = createSimpleConfiguration(); builder.getScenarios().get(0).validate(schematron("invalid"));
builder.getScenarios().get(0).validate(schematron("invalid")); builder.build(Helper.getTestProcessor());
builder.build(Helper.getTestProcessor()); fail();
} catch (final IllegalStateException ex) {
assertTrue(ex.getMessage().contains("schematron"));
}
} }
@Test @Test
public void testNoReport() { public void testNoReport() {
this.exceptions.expect(IllegalStateException.class); try {
this.exceptions.expectMessage(Matchers.containsString("report")); final ConfigurationBuilder builder = createSimpleConfiguration();
final ConfigurationBuilder builder = createSimpleConfiguration(); builder.getScenarios().get(0).with(report("invalid"));
builder.getScenarios().get(0).with(report("invalid")); builder.build(Helper.getTestProcessor());
builder.build(Helper.getTestProcessor()); fail();
} catch (final IllegalStateException ex) {
assertTrue(ex.getMessage().contains("report"));
}
} }
@Test @Test

View file

@ -24,9 +24,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.impl.ContentRepository; import de.kosit.validationtool.impl.ContentRepository;
import de.kosit.validationtool.impl.Helper.Simple; import de.kosit.validationtool.impl.Helper.Simple;
@ -43,9 +41,6 @@ import net.sf.saxon.s9api.XPathExecutable;
*/ */
public class ScenarioBuilderTest { public class ScenarioBuilderTest {
@Rule
public ExpectedException exceptions = ExpectedException.none();
@Test @Test
public void simpleValid() { public void simpleValid() {
final Result<Scenario, String> result = createScenario().build(Simple.createContentRepository()); final Result<Scenario, String> result = createScenario().build(Simple.createContentRepository());
@ -161,7 +156,7 @@ public class ScenarioBuilderTest {
@Test @Test
public void testBasicAttributes() { public void testBasicAttributes() {
final ContentRepository repository = Simple.createContentRepository(); final ContentRepository repository = Simple.createContentRepository();
final String random = RandomStringUtils.random(5); final String random = RandomStringUtils.secure().next(5);
final ScenarioBuilder builder = createScenario(); final ScenarioBuilder builder = createScenario();
builder.name(random).description(random); builder.name(random).description(random);
final Result<Scenario, String> result = builder.build(repository); final Result<Scenario, String> result = builder.build(repository);

View file

@ -28,7 +28,6 @@ import org.junit.Test;
import de.kosit.validationtool.impl.ContentRepository; import de.kosit.validationtool.impl.ContentRepository;
import de.kosit.validationtool.impl.Helper.Simple; import de.kosit.validationtool.impl.Helper.Simple;
import de.kosit.validationtool.impl.model.Result; import de.kosit.validationtool.impl.model.Result;
import net.sf.saxon.s9api.XPathExecutable; import net.sf.saxon.s9api.XPathExecutable;
/** /**
@ -40,7 +39,7 @@ public class XPathBuilderTest {
@Test @Test
public void testSimpleString() { public void testSimpleString() {
final String name = RandomStringUtils.randomAlphanumeric(5); final String name = RandomStringUtils.secure().nextAlphanumeric(5);
final XPathBuilder b = new XPathBuilder(name); final XPathBuilder b = new XPathBuilder(name);
b.setXpath("//*"); b.setXpath("//*");
final Result<XPathExecutable, String> result = b.build(Simple.createContentRepository()); final Result<XPathExecutable, String> result = b.build(Simple.createContentRepository());
@ -54,7 +53,7 @@ public class XPathBuilderTest {
@Test @Test
public void testStringWithNamespace() { public void testStringWithNamespace() {
final String name = RandomStringUtils.randomAlphanumeric(5); final String name = RandomStringUtils.secure().nextAlphanumeric(5);
final XPathBuilder b = new XPathBuilder(name); final XPathBuilder b = new XPathBuilder(name);
final Map<String, String> ns = new HashMap<>(); final Map<String, String> ns = new HashMap<>();
ns.put("p", "http://somens"); ns.put("p", "http://somens");
@ -69,7 +68,7 @@ public class XPathBuilderTest {
@Test @Test
public void testStringWithUnknownNamespace() { public void testStringWithUnknownNamespace() {
final String name = RandomStringUtils.randomAlphanumeric(5); final String name = RandomStringUtils.secure().nextAlphanumeric(5);
final XPathBuilder b = new XPathBuilder(name); final XPathBuilder b = new XPathBuilder(name);
final Map<String, String> ns = new HashMap<>(); final Map<String, String> ns = new HashMap<>();
ns.put("p", "http://somens"); ns.put("p", "http://somens");
@ -82,7 +81,7 @@ public class XPathBuilderTest {
@Test @Test
public void testExecutable() { public void testExecutable() {
final String name = RandomStringUtils.randomAlphanumeric(5); final String name = RandomStringUtils.secure().nextAlphanumeric(5);
final ContentRepository repository = Simple.createContentRepository(); final ContentRepository repository = Simple.createContentRepository();
final XPathExecutable xpath = repository.createXPath("//*", Collections.emptyMap()); final XPathExecutable xpath = repository.createXPath("//*", Collections.emptyMap());
final XPathBuilder b = new XPathBuilder(name); final XPathBuilder b = new XPathBuilder(name);
@ -96,7 +95,7 @@ public class XPathBuilderTest {
@Test @Test
public void testExecutableWithNamespace() { public void testExecutableWithNamespace() {
final String name = RandomStringUtils.randomAlphanumeric(5); final String name = RandomStringUtils.secure().nextAlphanumeric(5);
final ContentRepository repository = Simple.createContentRepository(); final ContentRepository repository = Simple.createContentRepository();
final Map<String, String> ns = new HashMap<>(); final Map<String, String> ns = new HashMap<>();
ns.put("p", "http://somens"); ns.put("p", "http://somens");
@ -123,7 +122,7 @@ public class XPathBuilderTest {
@Test @Test
public void testNoConfig() { public void testNoConfig() {
final String name = RandomStringUtils.randomAlphanumeric(5); final String name = RandomStringUtils.secure().nextAlphanumeric(5);
final XPathBuilder b = new XPathBuilder(name); final XPathBuilder b = new XPathBuilder(name);
final Result<XPathExecutable, String> result = b.build(Simple.createContentRepository()); final Result<XPathExecutable, String> result = b.build(Simple.createContentRepository());
assertThat(result).isNotNull(); assertThat(result).isNotNull();

View file

@ -15,6 +15,7 @@ import net.sf.saxon.lib.UnparsedTextURIResolver;
public class MiscDocExampleCodes { public class MiscDocExampleCodes {
@SuppressWarnings("unused")
void m1() { void m1() {
final Configuration config = Configuration.load(URI.create("myscenarios.xml")).setResolvingMode(ResolvingMode.STRICT_LOCAL) final Configuration config = Configuration.load(URI.create("myscenarios.xml")).setResolvingMode(ResolvingMode.STRICT_LOCAL)
.build(ProcessorProvider.getProcessor()); .build(ProcessorProvider.getProcessor());
@ -43,6 +44,7 @@ public class MiscDocExampleCodes {
} }
} }
@SuppressWarnings("unused")
void m2() { void m2() {
final Configuration config = Configuration.load(URI.create("myscenarios.xml")) final Configuration config = Configuration.load(URI.create("myscenarios.xml"))
.setResolvingStrategy(new MyCustomResolvingConfigurationStrategy()).build(ProcessorProvider.getProcessor()); .setResolvingStrategy(new MyCustomResolvingConfigurationStrategy()).build(ProcessorProvider.getProcessor());

View file

@ -19,6 +19,7 @@ import de.kosit.validationtool.impl.xml.ProcessorProvider;
*/ */
public class MyValidator { public class MyValidator {
@SuppressWarnings("unused")
public static void main(final String[] args) { public static void main(final String[] args) {
final Configuration config = Configuration.create().name("myconfiguration") final Configuration config = Configuration.create().name("myconfiguration")
.with(scenario("firstScenario").match("//myNode").validate(schema("Sample Schema").schemaLocation(URI.create("simple.xsd"))) .with(scenario("firstScenario").match("//myNode").validate(schema("Sample Schema").schemaLocation(URI.create("simple.xsd")))

View file

@ -20,6 +20,7 @@ import de.kosit.validationtool.impl.xml.ProcessorProvider;
*/ */
public class StandardExample { public class StandardExample {
@SuppressWarnings("unused")
public void run(final Path testDocument) throws URISyntaxException { public void run(final Path testDocument) throws URISyntaxException {
// Load scenarios.xml from classpath // Load scenarios.xml from classpath
final URL scenarios = this.getClass().getClassLoader().getResource("examples/simple/scenarios-with-relative-paths.xml"); final URL scenarios = this.getClass().getClassLoader().getResource("examples/simple/scenarios-with-relative-paths.xml");

View file

@ -28,12 +28,9 @@ import java.util.Map;
import javax.xml.validation.Schema; import javax.xml.validation.Schema;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.impl.Helper.Simple; import de.kosit.validationtool.impl.Helper.Simple;
import net.sf.saxon.s9api.XPathExecutable; import net.sf.saxon.s9api.XPathExecutable;
import net.sf.saxon.s9api.XsltExecutable; import net.sf.saxon.s9api.XsltExecutable;
@ -46,9 +43,6 @@ public class ContentRepositoryTest {
private ContentRepository repository; private ContentRepository repository;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before @Before
public void setup() { public void setup() {
this.repository = Simple.createContentRepository(); this.repository = Simple.createContentRepository();
@ -60,9 +54,8 @@ public class ContentRepositoryTest {
assertThat(schema).isNotNull(); assertThat(schema).isNotNull();
} }
@Test @Test(expected = IllegalStateException.class)
public void testCreateSchemaNotExisting() throws Exception { public void testCreateSchemaNotExisting() throws Exception {
this.exception.expect(IllegalStateException.class);
this.repository.createSchema(Simple.NOT_EXISTING.toURL()); this.repository.createSchema(Simple.NOT_EXISTING.toURL());
} }
@ -72,9 +65,8 @@ public class ContentRepositoryTest {
assertThat(executable).isNotNull(); assertThat(executable).isNotNull();
} }
@Test @Test(expected = IllegalStateException.class)
public void testLoadXSLTNotExisting() { public void testLoadXSLTNotExisting() {
this.exception.expect(IllegalStateException.class);
this.repository.loadXsltScript(Simple.NOT_EXISTING); this.repository.loadXsltScript(Simple.NOT_EXISTING);
} }
@ -90,15 +82,13 @@ public class ContentRepositoryTest {
assertThat(xPath).isNotNull(); assertThat(xPath).isNotNull();
} }
@Test @Test(expected = IllegalStateException.class)
public void testXpathCreationWithoutNamespace() { public void testXpathCreationWithoutNamespace() {
this.exception.expect(IllegalStateException.class);
this.repository.createXPath("//html:html", null); this.repository.createXPath("//html:html", null);
} }
@Test @Test(expected = IllegalStateException.class)
public void testIllegalXpath() { public void testIllegalXpath() {
this.exception.expect(IllegalStateException.class);
this.repository.createXPath("kein Xpath Ausdruck", null); this.repository.createXPath("kein Xpath Ausdruck", null);
} }

View file

@ -16,16 +16,13 @@
package de.kosit.validationtool.impl; package de.kosit.validationtool.impl;
import static org.assertj.core.api.Java6Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import java.io.Serializable; import java.io.Serializable;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.impl.Helper.Invalid; import de.kosit.validationtool.impl.Helper.Invalid;
import de.kosit.validationtool.impl.Helper.Simple; import de.kosit.validationtool.impl.Helper.Simple;
@ -40,9 +37,6 @@ public class ConversionServiceTest {
private static final URL SCHEMA = ConversionServiceTest.class.getResource("/xsd/scenarios.xsd"); private static final URL SCHEMA = ConversionServiceTest.class.getResource("/xsd/scenarios.xsd");
@Rule
public ExpectedException exception = ExpectedException.none();
private ConversionService service; private ConversionService service;
private ContentRepository repository; private ContentRepository repository;
@ -53,15 +47,13 @@ public class ConversionServiceTest {
this.repository = Simple.createContentRepository(); this.repository = Simple.createContentRepository();
} }
@Test @Test(expected = ConversionService.ConversionExeption.class)
public void testMarshalNull() { public void testMarshalNull() {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.writeXml(null); this.service.writeXml(null);
} }
@Test @Test(expected = ConversionService.ConversionExeption.class)
public void testMarshalUnknown() { public void testMarshalUnknown() {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.writeXml(new Serializable() { this.service.writeXml(new Serializable() {
}); });
} }
@ -80,33 +72,28 @@ public class ConversionServiceTest {
assertThat(s.getName()).isEqualToIgnoringCase("HTML-TestSuite"); assertThat(s.getName()).isEqualToIgnoringCase("HTML-TestSuite");
} }
@Test @Test(expected = ConversionService.ConversionExeption.class)
public void testUnmarshalInvalidXml() { public void testUnmarshalInvalidXml() {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(Invalid.SCENARIOS, Scenarios.class, this.repository.createSchema(SCHEMA)); this.service.readXml(Invalid.SCENARIOS, Scenarios.class, this.repository.createSchema(SCHEMA));
} }
@Test @Test(expected = ConversionService.ConversionExeption.class)
public void testUnmarshalIllFormed() { public void testUnmarshalIllFormed() {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(Invalid.SCENARIOS_ILLFORMED, Scenarios.class, this.repository.createSchema(SCHEMA)); this.service.readXml(Invalid.SCENARIOS_ILLFORMED, Scenarios.class, this.repository.createSchema(SCHEMA));
} }
@Test @Test(expected = ConversionService.ConversionExeption.class)
public void testUnmarshalEmpty() { public void testUnmarshalEmpty() {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(null, Scenarios.class); this.service.readXml(null, Scenarios.class);
} }
@Test @Test(expected = ConversionService.ConversionExeption.class)
public void testUnmarshalUnknownType() throws URISyntaxException { public void testUnmarshalUnknownType() {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(Simple.SCENARIOS, ConversionService.class); this.service.readXml(Simple.SCENARIOS, ConversionService.class);
} }
@Test @Test(expected = ConversionService.ConversionExeption.class)
public void testUnmarshalWithoutType() throws URISyntaxException { public void testUnmarshalWithoutType() {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(Simple.SCENARIOS, null); this.service.readXml(Simple.SCENARIOS, null);
} }

View file

@ -17,6 +17,7 @@
package de.kosit.validationtool.impl; package de.kosit.validationtool.impl;
import static de.kosit.validationtool.api.InputFactory.read; import static de.kosit.validationtool.api.InputFactory.read;
import static de.kosit.validationtool.impl.Helper.Simple.FOO_CUSTOM_LEVEL_ERROR;
import static de.kosit.validationtool.impl.Helper.Simple.FOO_SCHEMATRON_INVALID; import static de.kosit.validationtool.impl.Helper.Simple.FOO_SCHEMATRON_INVALID;
import static de.kosit.validationtool.impl.Helper.Simple.GARBAGE; import static de.kosit.validationtool.impl.Helper.Simple.GARBAGE;
import static de.kosit.validationtool.impl.Helper.Simple.NOT_WELLFORMED; import static de.kosit.validationtool.impl.Helper.Simple.NOT_WELLFORMED;
@ -44,7 +45,8 @@ import de.kosit.validationtool.api.Input;
import de.kosit.validationtool.api.InputFactory; import de.kosit.validationtool.api.InputFactory;
import de.kosit.validationtool.api.Result; import de.kosit.validationtool.api.Result;
import de.kosit.validationtool.impl.Helper.Simple; import de.kosit.validationtool.impl.Helper.Simple;
import de.kosit.validationtool.impl.model.CustomFailedAssert;
import de.kosit.validationtool.model.scenarios.ErrorLevelType;
import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmNode;
/** /**
@ -239,6 +241,8 @@ public class DefaultCheckTest {
assertThat(result.isAcceptable()).isFalse(); assertThat(result.isAcceptable()).isFalse();
assertThat(result.getReport()).isNotNull(); assertThat(result.getReport()).isNotNull();
assertThat(result.getProcessingErrors()).hasSize(1); assertThat(result.getProcessingErrors()).hasSize(1);
assertThat(result.getCustomFailedAsserts()).isNotNull();
assertThat(result.getCustomFailedAsserts()).hasSize(0);
} }
@Test @Test
@ -254,4 +258,19 @@ public class DefaultCheckTest {
result = this.validCheck.checkInput(domInput); result = this.validCheck.checkInput(domInput);
assertThat(result.isProcessingSuccessful()).isEqualTo(true); assertThat(result.isProcessingSuccessful()).isEqualTo(true);
} }
@Test
public void testCustomFailedAssertsWarning() {
final Result result = this.errorCheck.checkInput(read(FOO_CUSTOM_LEVEL_ERROR));
assertThat(result.isSchematronValid()).isFalse();
assertThat(result.getFailedAsserts()).isNotEmpty();
assertThat(result.getAcceptRecommendation()).isEqualTo(AcceptRecommendation.ACCEPTABLE);
assertThat(result.getCustomFailedAsserts()).isNotNull();
assertThat(result.getCustomFailedAsserts()).hasSize(1);
CustomFailedAssert customFailedAssert = result.getCustomFailedAsserts().get(0);
assertThat(result.getFailedAsserts().get(0).getId()).isEqualTo(customFailedAssert.getFailedAssert().getId());
assertThat(customFailedAssert.getCustomLevelFlag()).isEqualTo(ErrorLevelType.WARNING);
}
} }

View file

@ -57,6 +57,8 @@ public class Helper {
public static final URI FOO_SCHEMATRON_INVALID = EXAMPLES.resolve("foo-schematron-invalid.xml"); public static final URI FOO_SCHEMATRON_INVALID = EXAMPLES.resolve("foo-schematron-invalid.xml");
public static final URI FOO_CUSTOM_LEVEL_ERROR = EXAMPLES.resolve("foo-custom-level-error.xml");
public static final URI REJECTED = ROOT.resolve("input/withManualReject.xml"); public static final URI REJECTED = ROOT.resolve("input/withManualReject.xml");
public static final URI SCENARIOS = ROOT.resolve("scenarios.xml"); public static final URI SCENARIOS = ROOT.resolve("scenarios.xml");

View file

@ -26,9 +26,7 @@ import javax.xml.transform.Source;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver; import javax.xml.transform.URIResolver;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.impl.xml.RelativeUriResolver; import de.kosit.validationtool.impl.xml.RelativeUriResolver;
@ -49,9 +47,6 @@ public class RelativeUriResolverTest {
} }
} }
@Rule
public ExpectedException exception = ExpectedException.none();
private URIResolver resolver = new RelativeUriResolver(BASE); private URIResolver resolver = new RelativeUriResolver(BASE);
@Test @Test
@ -60,15 +55,13 @@ public class RelativeUriResolverTest {
assertThat(resource).isNotNull(); assertThat(resource).isNotNull();
} }
@Test @Test(expected = TransformerException.class)
public void testNotExisting() throws TransformerException { public void testNotExisting() throws TransformerException {
this.exception.expect(TransformerException.class);
this.resolver.resolve("ubl-0001", BASE.toASCIIString()); this.resolver.resolve("ubl-0001", BASE.toASCIIString());
} }
@Test @Test(expected = TransformerException.class)
public void testOutOfPath() throws TransformerException { public void testOutOfPath() throws TransformerException {
this.exception.expect(TransformerException.class);
this.resolver.resolve("../results/report.xml", BASE.toASCIIString()); this.resolver.resolve("../results/report.xml", BASE.toASCIIString());
} }

View file

@ -25,15 +25,12 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.config.TestConfiguration; import de.kosit.validationtool.config.TestConfiguration;
import de.kosit.validationtool.impl.Helper.Simple; import de.kosit.validationtool.impl.Helper.Simple;
import de.kosit.validationtool.impl.model.Result; import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.model.scenarios.ScenarioType; import de.kosit.validationtool.model.scenarios.ScenarioType;
import net.sf.saxon.s9api.XPathExecutable; import net.sf.saxon.s9api.XPathExecutable;
import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmNode;
@ -45,9 +42,6 @@ import net.sf.saxon.s9api.XdmNode;
public class ScenarioRepositoryTest { public class ScenarioRepositoryTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
private ScenarioRepository repository; private ScenarioRepository repository;
private TestConfiguration configInstance; private TestConfiguration configInstance;
@ -107,9 +101,8 @@ public class ScenarioRepositoryTest {
assertThat(scenario.getObject().getName()).isEqualTo("fallback"); assertThat(scenario.getObject().getName()).isEqualTo("fallback");
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testNoConfiguration() { public void testNoConfiguration() {
this.expectedException.expect(IllegalArgumentException.class);
this.repository = new ScenarioRepository(); this.repository = new ScenarioRepository();
} }

View file

@ -22,11 +22,8 @@ import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.impl.Helper.Simple;
import de.kosit.validationtool.model.scenarios.Scenarios; import de.kosit.validationtool.model.scenarios.Scenarios;
/** /**
@ -44,16 +41,10 @@ public class VersioningTest {
private static final URL NEW_VERSION = VersioningTest.class.getResource("/examples/versioning/scenarios-newversion.xml"); private static final URL NEW_VERSION = VersioningTest.class.getResource("/examples/versioning/scenarios-newversion.xml");
@Rule
public ExpectedException exception = ExpectedException.none();
private ConversionService service; private ConversionService service;
private ContentRepository repository;
@Before @Before
public void setup() { public void setup() {
this.repository = Simple.createContentRepository();
this.service = new ConversionService(); this.service = new ConversionService();
} }
@ -69,15 +60,13 @@ public class VersioningTest {
assertThat(result).isNotNull(); assertThat(result).isNotNull();
} }
@Test @Test(expected = ConversionService.ConversionExeption.class)
public void testNewFeature() throws URISyntaxException { public void testNewFeature() throws URISyntaxException {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(NEW_FEATURE.toURI(), Scenarios.class, SchemaProvider.getScenarioSchema()); this.service.readXml(NEW_FEATURE.toURI(), Scenarios.class, SchemaProvider.getScenarioSchema());
} }
@Test @Test(expected = ConversionService.ConversionExeption.class)
public void testNewVersion() throws URISyntaxException { public void testNewVersion() throws URISyntaxException {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(NEW_VERSION.toURI(), Scenarios.class, SchemaProvider.getScenarioSchema()); this.service.readXml(NEW_VERSION.toURI(), Scenarios.class, SchemaProvider.getScenarioSchema());
} }
} }

View file

@ -20,15 +20,12 @@ import static de.kosit.validationtool.api.InputFactory.read;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.impl.Helper; import de.kosit.validationtool.impl.Helper;
import de.kosit.validationtool.impl.Helper.Simple; import de.kosit.validationtool.impl.Helper.Simple;
import de.kosit.validationtool.impl.model.Result; import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.model.reportInput.XMLSyntaxError; import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmNode;
/** /**
@ -38,9 +35,6 @@ import net.sf.saxon.s9api.XdmNode;
*/ */
public class DocumentParseActionTest { public class DocumentParseActionTest {
@Rule
public ExpectedException exception = ExpectedException.none();
private DocumentParseAction action; private DocumentParseAction action;
@Before @Before
@ -66,9 +60,8 @@ public class DocumentParseActionTest {
assertThat(result.isValid()).isFalse(); assertThat(result.isValid()).isFalse();
} }
@Test @Test(expected = IllegalArgumentException.class)
public void testNullInput() { public void testNullInput() {
this.exception.expect(IllegalArgumentException.class);
this.action.parseDocument(null); this.action.parseDocument(null);
} }

View file

@ -35,7 +35,6 @@ import javax.xml.validation.Validator;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import de.kosit.validationtool.api.Input; import de.kosit.validationtool.api.Input;
@ -56,8 +55,6 @@ import de.kosit.validationtool.impl.tasks.CheckAction.Bag;
*/ */
public class SchemaValidatorActionTest { public class SchemaValidatorActionTest {
public ExpectedException expectedException = ExpectedException.none();
private SchemaValidationAction service; private SchemaValidationAction service;
@Before @Before

View file

@ -25,9 +25,7 @@ import static org.mockito.Mockito.verify;
import javax.xml.XMLConstants; import javax.xml.XMLConstants;
import javax.xml.validation.SchemaFactory; import javax.xml.validation.SchemaFactory;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXNotSupportedException;
@ -51,9 +49,6 @@ public class BaseResolverConfigurationTest {
public static final String NOT_EXISTING_SCHEME = "not-existing-scheme"; public static final String NOT_EXISTING_SCHEME = "not-existing-scheme";
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test @Test
public void testIgnoreUnsupportedProperty() throws SAXNotRecognizedException, SAXNotSupportedException { public void testIgnoreUnsupportedProperty() throws SAXNotRecognizedException, SAXNotSupportedException {
final SchemaFactory sf = mock(SchemaFactory.class); final SchemaFactory sf = mock(SchemaFactory.class);
@ -62,9 +57,8 @@ public class BaseResolverConfigurationTest {
s.setInternalProperty(sf, true); s.setInternalProperty(sf, true);
} }
@Test @Test(expected = IllegalStateException.class)
public void testFailOnUnsupportedProperty() throws SAXNotRecognizedException, SAXNotSupportedException { public void testFailOnUnsupportedProperty() throws SAXNotRecognizedException, SAXNotSupportedException {
this.expectedException.expect(IllegalStateException.class);
final SchemaFactory sf = mock(SchemaFactory.class); final SchemaFactory sf = mock(SchemaFactory.class);
final TestResolvingStrategy s = new TestResolvingStrategy(); final TestResolvingStrategy s = new TestResolvingStrategy();
doThrow(new SAXNotRecognizedException("not supported")).when(sf).setProperty(any(), any()); doThrow(new SAXNotRecognizedException("not supported")).when(sf).setProperty(any(), any());

View file

@ -21,9 +21,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import javax.xml.validation.Schema; import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory; import javax.xml.validation.SchemaFactory;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.api.ResolvingConfigurationStrategy; import de.kosit.validationtool.api.ResolvingConfigurationStrategy;
import de.kosit.validationtool.impl.Helper.Resolving; import de.kosit.validationtool.impl.Helper.Resolving;
@ -35,9 +33,6 @@ import de.kosit.validationtool.impl.Helper.Resolving;
*/ */
public class RemoteResolvingStrategyTest { public class RemoteResolvingStrategyTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test @Test
public void testRemoteSchemaResolving() throws Exception { public void testRemoteSchemaResolving() throws Exception {
final ResolvingConfigurationStrategy s = new RemoteResolvingStrategy(); final ResolvingConfigurationStrategy s = new RemoteResolvingStrategy();

View file

@ -16,8 +16,12 @@
package de.kosit.validationtool.impl.xml; package de.kosit.validationtool.impl.xml;
import static org.junit.Assert.assertNotNull;
import javax.xml.validation.SchemaFactory; import javax.xml.validation.SchemaFactory;
import org.junit.Test;
import de.kosit.validationtool.impl.ResolvingMode; import de.kosit.validationtool.impl.ResolvingMode;
/** /**
@ -25,6 +29,10 @@ import de.kosit.validationtool.impl.ResolvingMode;
*/ */
public class SchemaProviderTest { public class SchemaProviderTest {
private final SchemaFactory schemaFactory = ResolvingMode.STRICT_RELATIVE.getStrategy().createSchemaFactory(); @Test
public void testBasic() {
final SchemaFactory schemaFactory = ResolvingMode.STRICT_RELATIVE.getStrategy().createSchemaFactory();
assertNotNull(schemaFactory);
}
} }

View file

@ -17,14 +17,13 @@
package de.kosit.validationtool.impl.xml; package de.kosit.validationtool.impl.xml;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.Assert.assertTrue;
import javax.xml.validation.Schema; import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory; import javax.xml.validation.SchemaFactory;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.xml.sax.SAXParseException; import org.xml.sax.SAXParseException;
import de.kosit.validationtool.api.ResolvingConfigurationStrategy; import de.kosit.validationtool.api.ResolvingConfigurationStrategy;
@ -37,16 +36,16 @@ import de.kosit.validationtool.impl.Helper.Resolving;
*/ */
public class StrictLocalResolvingTest { public class StrictLocalResolvingTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test @Test
public void testRemoteSchemaResolving() throws Exception { public void testRemoteSchemaResolving() throws Exception {
this.expectedException.expect(SAXParseException.class); try {
this.expectedException.expectMessage(Matchers.containsString("schema_reference")); final ResolvingConfigurationStrategy s = new StrictLocalResolvingStrategy();
final ResolvingConfigurationStrategy s = new StrictLocalResolvingStrategy(); final SchemaFactory schemaFactory = s.createSchemaFactory();
final SchemaFactory schemaFactory = s.createSchemaFactory(); schemaFactory.newSchema(Resolving.SCHEMA_WITH_REMOTE_REFERENCE.toURL());
schemaFactory.newSchema(Resolving.SCHEMA_WITH_REMOTE_REFERENCE.toURL()); fail();
} catch (SAXParseException ex) {
assertTrue(ex.getMessage().contains("schema_reference"));
}
} }
@Test @Test

View file

@ -17,14 +17,13 @@
package de.kosit.validationtool.impl.xml; package de.kosit.validationtool.impl.xml;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.Assert.assertTrue;
import javax.xml.validation.Schema; import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory; import javax.xml.validation.SchemaFactory;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.xml.sax.SAXParseException; import org.xml.sax.SAXParseException;
import de.kosit.validationtool.api.ResolvingConfigurationStrategy; import de.kosit.validationtool.api.ResolvingConfigurationStrategy;
@ -37,16 +36,16 @@ import de.kosit.validationtool.impl.Helper.Resolving;
*/ */
public class StrictRelativeResolvingTest { public class StrictRelativeResolvingTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test @Test
public void testRemoteSchemaResolving() throws Exception { public void testRemoteSchemaResolving() throws Exception {
this.expectedException.expect(SAXParseException.class); try {
this.expectedException.expectMessage(Matchers.containsString("schema_reference")); final ResolvingConfigurationStrategy s = new StrictLocalResolvingStrategy();
final ResolvingConfigurationStrategy s = new StrictLocalResolvingStrategy(); final SchemaFactory schemaFactory = s.createSchemaFactory();
final SchemaFactory schemaFactory = s.createSchemaFactory(); schemaFactory.newSchema(Resolving.SCHEMA_WITH_REMOTE_REFERENCE.toURL());
schemaFactory.newSchema(Resolving.SCHEMA_WITH_REMOTE_REFERENCE.toURL()); fail();
} catch (SAXParseException ex) {
assertTrue(ex.getMessage().contains("schema_reference"));
}
} }
@Test @Test

View file

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2017-2022 Koordinierungsstelle für IT-Standards (KoSIT)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<foo xmlns="http://validator.kosit.de/test-sample">
<inner>asldkfj</inner>
<inner>asldkfj</inner>
<content>
</content>
</foo>

View file

@ -52,6 +52,38 @@
</createReport> </createReport>
</scenario> </scenario>
<scenario>
<name>Simple</name>
<description>
<p>Foo schematron error</p>
</description>
<namespace prefix="cri">http://www.xoev.de/de/validator/framework/1/createreportinput</namespace>
<namespace prefix="test">http://validator.kosit.de/test-sample</namespace>
<namespace prefix="rpt">http://validator.kosit.de/test-report</namespace>
<match>/test:foo</match>
<validateWithXmlSchema>
<resource>
<name>Sample Schema</name>
<location>simple.xsd</location>
</resource>
</validateWithXmlSchema>
<validateWithSchematron>
<resource>
<name>Sample Schematron</name>
<location>simple-schematron-error.xsl</location>
</resource>
</validateWithSchematron>
<createReport>
<resource>
<name>Report für eRechnung</name>
<location>report.xsl</location>
</resource>
<customLevel level="warning">content-2</customLevel>
</createReport>
<acceptMatch>count(//test:rejected) = 0</acceptMatch>
</scenario>
<noScenarioReport> <noScenarioReport>
<resource> <resource>
<name>default</name> <name>default</name>