(wip) Umsetzung OHNE Nutzung eines java.nio.Filesystem

This commit is contained in:
Andreas Penski (init) 2019-05-07 08:46:24 +02:00 committed by Andreas Penski
parent 7af9b1fdbd
commit 99930a2b0a
14 changed files with 312 additions and 188 deletions

View file

@ -42,38 +42,6 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
class ClassPathResourceResolver implements LSResourceResolver {
private final URI base;
/**
* Instantiiert einen neuen resolver mit angegebenen Basispfad
*
* @param basePath der Basispfad
*/
public ClassPathResourceResolver(String basePath) {
if (!StringUtils.startsWith(basePath, "/")) {
throw new IllegalArgumentException("Base path must start with a slash");
}
base = URI.create(basePath + (basePath.endsWith("/") == basePath.length() > 1 ? "" : "/"));
}
@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {
final URL resource = ClassPathResourceResolver.class.getResource(base.resolve(systemId).toASCIIString());
if (resource != null) {
try {
InputStream in = resource.openStream();
final LSInputImpl input = new LSInputImpl(publicId, systemId, baseURI);
input.setByteStream(in);
return input;
} catch (IOException e) {
log.error("Error loading schema resource from {}", resource, e);
}
}
// not found
return null;
}
/**
* Simple {@link LSInput}-Implementierung, die einen Stream liefern kann
*/
@ -100,11 +68,12 @@ class ClassPathResourceResolver implements LSResourceResolver {
/**
* Instantiierung einer neue Instanz.
*
* @param publicId die publicId
* @param systemId die systemId
* @param baseURI die baseURI
*/
public LSInputImpl(String publicId, String systemId, String baseURI) {
public LSInputImpl(final String publicId, final String systemId, final String baseURI) {
this.publicId = publicId;
this.systemId = systemId;
this.baseURI = baseURI;
@ -112,7 +81,48 @@ class ClassPathResourceResolver implements LSResourceResolver {
@Override
public boolean getCertifiedText() {
return certifiedText;
return this.certifiedText;
}
}
private final URI base;
/**
* Instantiiert einen neuen resolver mit angegebenen Basispfad
*
* @param basePath der Basispfad
*/
public ClassPathResourceResolver(final String basePath) {
if (!StringUtils.startsWith(basePath, "/")) {
throw new IllegalArgumentException("Base path must start with a slash");
}
this.base = URI.create(basePath + (basePath.endsWith("/") == basePath.length() > 1 ? "" : "/"));
}
public ClassPathResourceResolver(final URI jarUri) {
this.base = jarUri;
}
@Override
public LSInput resolveResource(final String type, final String namespaceURI, final String publicId, final String systemId,
final String baseURI) {
final URI resolved = RelativeUriResolver.resolve(URI.create(systemId), this.base);
if (resolved != null) {
try {
final URL resource = resolved.isAbsolute() ? resolved.toURL()
: ClassPathResourceResolver.class.getResource(resolved.toASCIIString());
final InputStream in = resource.openStream();
final LSInputImpl input = new LSInputImpl(publicId, systemId, resolved.toASCIIString());
input.setByteStream(in);
return input;
} catch (final IOException e) {
log.error("Error loading schema resource from {}", resolved, e);
}
}
// not found
return null;
}
}

View file

@ -39,7 +39,12 @@ import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.s9api.*;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XPathCompiler;
import net.sf.saxon.s9api.XPathExecutable;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;
/**
* Repository für verschiedene XML Artefakte zur Vearbeitung der Prüfszenarien.
@ -57,25 +62,25 @@ public class ContentRepository {
private Schema reportInputSchema;
private static Source resolve(URL resource) {
private static Source resolve(final URL resource) {
try {
return new StreamSource(resource.openStream(), resource.toURI().getRawPath());
} catch (IOException | URISyntaxException e) {
} catch (final IOException | URISyntaxException e) {
throw new IllegalStateException("Can not load schema for resource " + resource.getPath(), e);
}
}
private static Schema createSchema(Source[] schemaSources, LSResourceResolver resourceResolver) {
private static Schema createSchema(final Source[] schemaSources, final LSResourceResolver resourceResolver) {
try {
SchemaFactory sf = ObjectFactory.createSchemaFactory();
final SchemaFactory sf = ObjectFactory.createSchemaFactory();
sf.setResourceResolver(resourceResolver);
return sf.newSchema(schemaSources);
} catch (SAXException e) {
} catch (final SAXException e) {
throw new IllegalArgumentException("Can not load schema from sources " + schemaSources[0].getSystemId(), e);
}
}
private static Schema createSchema(Source[] schemaSources) {
private static Schema createSchema(final Source[] schemaSources) {
return createSchema(schemaSources, null);
}
@ -85,16 +90,16 @@ public class ContentRepository {
* @param uri die URI der XSL Definition
* @return ein XSLT Executable
*/
public XsltExecutable loadXsltScript(URI uri) {
public XsltExecutable loadXsltScript(final URI uri) {
log.info("Loading XSLT script from {}", uri);
final XsltCompiler xsltCompiler = getProcessor().newXsltCompiler();
final CollectingErrorEventHandler listener = new CollectingErrorEventHandler();
try {
xsltCompiler.setErrorListener(listener);
xsltCompiler.setURIResolver(new RelativeUriResolver(repository));
xsltCompiler.setURIResolver(new RelativeUriResolver(this.repository));
return xsltCompiler.compile(resolve(uri));
} catch (SaxonApiException e) {
} catch (final SaxonApiException e) {
listener.getErrors().forEach(event -> event.log(log));
throw new IllegalStateException("Can not compile xslt executable for uri " + uri, e);
} finally {
@ -111,9 +116,13 @@ public class ContentRepository {
* @param url die url
* @return das erzeugte Schema
*/
public Schema createSchema(URL url) {
public static Schema createSchema(final URL url) {
return createSchema(url, null);
}
public static Schema createSchema(final URL url, final LSResourceResolver resourceResolver) {
log.info("Load schema from source {}", url.getPath());
return createSchema(new Source[] { resolve(url) });
return createSchema(new Source[] { resolve(url) }, resourceResolver);
}
/**
@ -121,7 +130,7 @@ public class ContentRepository {
*
* @return Scenario-Schema
*/
public Schema getScenarioSchema() {
public static Schema getScenarioSchema() {
return createSchema(ContentRepository.class.getResource("/xsd/scenarios.xsd"));
}
@ -131,11 +140,11 @@ public class ContentRepository {
* @return ReportInput-Schema
*/
public Schema getReportInputSchema() {
if (reportInputSchema == null) {
if (this.reportInputSchema == null) {
final Source source = resolve(ContentRepository.class.getResource("/xsd/createReportInput.xsd"));
reportInputSchema = createSchema(new Source[] { source }, new ClassPathResourceResolver("/xsd"));
this.reportInputSchema = createSchema(new Source[] { source }, new ClassPathResourceResolver("/xsd"));
}
return reportInputSchema;
return this.reportInputSchema;
}
/**
@ -144,12 +153,13 @@ public class ContentRepository {
* @param uris die uris in String-Repräsentation
* @return das Schema
*/
public Schema createSchema(Collection<String> uris) {
public Schema createSchema(final Collection<String> uris) {
return createSchema(uris.stream().map(s -> resolve(URI.create(s))).toArray(Source[]::new));
}
private Source resolve(URI source) {
return new StreamSource(repository.resolve(source).toASCIIString());
private Source resolve(final URI source) {
final URI resolved = RelativeUriResolver.resolve(source, this.repository);
return new StreamSource(resolved.toASCIIString());
}
/**
@ -159,17 +169,37 @@ public class ContentRepository {
* @param namespaces optionale Namespace-Mappings
* @return ein kompiliertes Executable
*/
public XPathExecutable createXPath(String expression, Map<String, String> namespaces) {
public XPathExecutable createXPath(final String expression, final Map<String, String> namespaces) {
try {
final XPathCompiler compiler = getProcessor().newXPathCompiler();
if (namespaces != null) {
namespaces.entrySet().forEach(n -> compiler.declareNamespace(n.getKey(), n.getValue()));
namespaces.forEach(compiler::declareNamespace);
}
return compiler.compile(expression);
} catch (SaxonApiException e) {
} catch (final SaxonApiException e) {
throw new IllegalStateException(String.format("Can not compile xpath match expression '%s'",
StringUtils.isNotBlank(expression) ? expression : "EMPTY EXPRESSION"), e);
}
}
/**
* Zeigt an, ob diese URI in ein JAR zeigt.
*
* @param uri der URI
* @return true wenn innerhalb eines JARs
*/
public static boolean isJarResource(final URI uri) {
return isJarResource(uri.toString());
}
/**
* Zeigt an, ob dieser Pfad in ein JAR zeigt.
*
* @param path der Pfad (URI-Format)
* @return true wenn innerhalb eines JARs
*/
public static boolean isJarResource(final String path) {
return StringUtils.startsWithIgnoreCase(path, "jar:") && path.split("!").length == 2;
}
}

View file

@ -25,7 +25,6 @@ import java.io.Reader;
import java.net.URI;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;
@ -48,38 +47,49 @@ public class RelativeUriResolver implements URIResolver, UnparsedTextURIResolver
private final URI baseUri;
@Override
public Source resolve(final String href, final String base) throws TransformerException {
final URI resolved = URI.create(base).resolve(href);
public Source resolve(final String href, final String base) {
final URI resolved = resolve(URI.create(href), URI.create(base));
if (isUnderBaseUri(resolved)) {
try {
return new StreamSource(resolved.toURL().openStream());
return new StreamSource(resolved.toURL().openStream(), resolved.toASCIIString());
} catch (final IOException e) {
throw new IllegalStateException(String.format("Can not resolve required %s", href), e);
}
} else {
throw new IllegalStateException(
String.format("The resolved transformation artifact %s is not within the configured repository %s", resolved, baseUri));
throw new IllegalStateException(String
.format("The resolved transformation artifact %s is not within the configured repository %s", resolved, this.baseUri));
}
}
private boolean isUnderBaseUri(URI resolved) {
String base = baseUri.toASCIIString().replaceAll("file:/+", "");
String r = resolved.toASCIIString().replaceAll("file:/+", "");
static URI resolve(final URI href, final URI base) {
final boolean jarURI = isJarURI(base);
final URI tmpBase = jarURI ? URI.create(base.toASCIIString().substring(4)) : base;
final URI result = tmpBase.resolve(href);
return jarURI ? URI.create("jar:" + result.toString()) : result;
}
static boolean isJarURI(final URI uri) {
return uri.isOpaque() && uri.getScheme().equals("jar");
}
private boolean isUnderBaseUri(final URI resolved) {
final String base = this.baseUri.toASCIIString().replaceAll("file:/+", "");
final String r = resolved.toASCIIString().replaceAll("file:/+", "");
return r.startsWith(base);
}
@Override
public Reader resolve(URI absoluteURI, String encoding, Configuration config) throws XPathException {
public Reader resolve(final URI absoluteURI, final String encoding, final Configuration config) throws XPathException {
if (isUnderBaseUri(absoluteURI)) {
try {
return new InputStreamReader(absoluteURI.toURL().openStream(), encoding);
} catch (IOException e) {
} catch (final IOException e) {
throw new IllegalStateException(String.format("Can not resolve required %s", absoluteURI), e);
}
} else {
throw new IllegalStateException(
String.format("The resolved transformation artifact %s is not within the configured repository %s", absoluteURI, baseUri));
throw new IllegalStateException(String.format(
"The resolved transformation artifact %s is not within the configured repository %s", absoluteURI, this.baseUri));
}
}
}

View file

@ -73,7 +73,7 @@ public class ScenarioRepository {
@Getter
private Scenarios scenarios;
private static boolean isSupportedDocument(XdmNode doc) {
private static boolean isSupportedDocument(final XdmNode doc) {
final XdmNode root = findRoot(doc);
final String frameworkVersion = root.getAttributeValue(new QName("frameworkVersion"));
return startsWith(frameworkVersion, SUPPORTED_MAJOR_VERSION)
@ -91,8 +91,8 @@ public class ScenarioRepository {
throw new IllegalArgumentException("Kein root element gefunden");
}
private static void checkVersion(URI scenarioDefinition) {
DocumentParseAction p = new DocumentParseAction();
private static void checkVersion(final URI scenarioDefinition) {
final DocumentParseAction p = new DocumentParseAction();
try {
final Result<XdmNode, XMLSyntaxError> result = p.parseDocument(InputFactory.read(scenarioDefinition.toURL()));
if (result.isValid() && !isSupportedDocument(result.getObject())) {
@ -101,16 +101,17 @@ public class ScenarioRepository {
scenarioDefinition, SUPPORTED_MAJOR_VERSION_SCHEMA));
}
} catch (MalformedURLException e) {
} catch (final MalformedURLException e) {
throw new IllegalStateException("Error reading definition file");
}
}
public XsltExecutable getNoScenarioReport() {
if (noScenarioReport == null) {
noScenarioReport = repository.loadXsltScript(URI.create(scenarios.getNoScenarioReport().getResource().getLocation()));
if (this.noScenarioReport == null) {
this.noScenarioReport = this.repository
.loadXsltScript(URI.create(this.scenarios.getNoScenarioReport().getResource().getLocation()));
}
return noScenarioReport;
return this.noScenarioReport;
}
/**
@ -118,18 +119,18 @@ public class ScenarioRepository {
*
* @param config die Konfiguration
*/
public void initialize(CheckConfiguration config) {
ConversionService conversionService = new ConversionService();
public void initialize(final CheckConfiguration config) {
final ConversionService conversionService = new ConversionService();
checkVersion(config.getScenarioDefinition());
log.info("Loading scenarios from {}", config.getScenarioDefinition());
CollectingErrorEventHandler handler = new CollectingErrorEventHandler();
this.scenarios = conversionService.readXml(config.getScenarioDefinition(), Scenarios.class, repository.getScenarioSchema(),
final CollectingErrorEventHandler handler = new CollectingErrorEventHandler();
this.scenarios = conversionService.readXml(config.getScenarioDefinition(), Scenarios.class, ContentRepository.getScenarioSchema(),
handler);
if (!handler.hasErrors()) {
log.info("Loaded scenarios for {} by {} from {}. The following scenarios are available:\n\n{}", scenarios.getName(),
scenarios.getAuthor(), scenarios.getDate(), summarizeScenarios());
log.info("Loaded scenarios for {} by {} from {}. The following scenarios are available:\n\n{}", this.scenarios.getName(),
this.scenarios.getAuthor(), this.scenarios.getDate(), summarizeScenarios());
log.info("Loading scenario content from {}", config.getScenarioRepository());
getScenarios().getScenario().forEach(s -> s.initialize(repository, false));
getScenarios().getScenario().forEach(s -> s.initialize(this.repository, false));
} else {
throw new IllegalStateException(String.format("Can not load scenarios from %s due to %s", config.getScenarioDefinition(),
handler.getErrorDescription()));
@ -140,8 +141,8 @@ public class ScenarioRepository {
}
private String summarizeScenarios() {
StringBuilder b = new StringBuilder();
scenarios.getScenario().forEach(s -> {
final StringBuilder b = new StringBuilder();
this.scenarios.getScenario().forEach(s -> {
b.append(s.getName());
b.append("\n");
});
@ -154,9 +155,10 @@ public class ScenarioRepository {
* @param document das Eingabedokument
* @return ein Ergebnis-Objekt zur weiteren Verarbeitung
*/
public Result<ScenarioType, String> selectScenario(XdmNode document) {
public Result<ScenarioType, String> selectScenario(final XdmNode document) {
Result<ScenarioType, String> result = new Result<>();
final List<ScenarioType> collect = scenarios.getScenario().stream().filter(s -> match(document, s)).collect(Collectors.toList());
final List<ScenarioType> collect = this.scenarios.getScenario().stream().filter(s -> match(document, s))
.collect(Collectors.toList());
if (collect.size() == 1) {
result = new Result<>(collect.get(0));
} else if (collect.isEmpty()) {
@ -168,19 +170,19 @@ public class ScenarioRepository {
}
private boolean match(XdmNode document, ScenarioType scenario) {
private static boolean match(final XdmNode document, final ScenarioType scenario) {
try {
final XPathSelector selector = scenario.getSelector();
selector.setContextItem(document);
return selector.effectiveBooleanValue();
} catch (SaxonApiException e) {
} catch (final SaxonApiException e) {
log.error("Error evaluating xpath expression", e);
}
return false;
}
void initialize(Scenarios def) {
void initialize(final Scenarios def) {
this.scenarios = def;
}
}

View file

@ -22,6 +22,9 @@ package de.kosit.validationtool.impl;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@ -48,64 +51,85 @@ public class ContentRepositoryTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
repository = new ContentRepository(ObjectFactory.createProcessor(), Helper.REPOSITORY);
this.repository = new ContentRepository(ObjectFactory.createProcessor(), Helper.REPOSITORY);
}
@Test
public void testCreateSchema() throws MalformedURLException {
final Schema schema = repository.createSchema(Helper.ASSERTION_SCHEMA.toURL());
final Schema schema = ContentRepository.createSchema(Helper.ASSERTION_SCHEMA.toURL());
assertThat(schema).isNotNull();
}
@Test
public void testSchemaCaching() throws MalformedURLException {
final Schema schema = repository.getReportInputSchema();
assertThat(repository.getReportInputSchema()).isSameAs(schema);
public void testSchemaCaching() {
final Schema schema = this.repository.getReportInputSchema();
assertThat(this.repository.getReportInputSchema()).isSameAs(schema);
}
@Test
public void testCreateSchemaNotExisting()throws Exception {
exception.expect(IllegalStateException.class);
repository.createSchema(Helper.ASSERTION_SCHEMA.resolve("noexisting").toURL());
public void testCreateSchemaNotExisting() throws Exception {
this.exception.expect(IllegalStateException.class);
ContentRepository.createSchema(Helper.ASSERTION_SCHEMA.resolve("noexisting").toURL());
}
@Test
public void testLoadXSLT() throws MalformedURLException {
final XsltExecutable executable = repository.loadXsltScript(Helper.SAMPLE_XSLT);
public void testLoadXSLT() {
final XsltExecutable executable = this.repository.loadXsltScript(Helper.SAMPLE_XSLT);
assertThat(executable).isNotNull();
}
@Test
public void testLoadXSLTNotExisting() throws MalformedURLException {
exception.expect(IllegalStateException.class);
repository.loadXsltScript(Helper.SAMPLE_XSLT.resolve("notexisting"));
public void testLoadXSLTNotExisting() {
this.exception.expect(IllegalStateException.class);
this.repository.loadXsltScript(Helper.SAMPLE_XSLT.resolve("notexisting"));
}
@Test
public void testXpathCreation() throws MalformedURLException {
XPathExecutable xPath = repository.createXPath("//html", null);
public void testXpathCreation() {
XPathExecutable xPath = this.repository.createXPath("//html", null);
assertThat(xPath).isNotNull();
xPath = repository.createXPath("//html", Collections.emptyMap());
xPath = this.repository.createXPath("//html", Collections.emptyMap());
assertThat(xPath).isNotNull();
Map<String,String> namespace = new HashMap<>();
final Map<String, String> namespace = new HashMap<>();
namespace.put("html", "http://www.w3.org/1999/xhtml");
xPath = repository.createXPath("//html:html", namespace );
xPath = this.repository.createXPath("//html:html", namespace);
assertThat(xPath).isNotNull();
}
@Test
public void testXpathCreationWithoutNamespace(){
exception.expect(IllegalStateException.class);
repository.createXPath("//html:html", null );
public void testXpathCreationWithoutNamespace() {
this.exception.expect(IllegalStateException.class);
this.repository.createXPath("//html:html", null);
}
@Test
public void testIllegalXpath(){
exception.expect(IllegalStateException.class);
repository.createXPath("kein Xpath Ausdruck", null );
public void testIllegalXpath() {
this.exception.expect(IllegalStateException.class);
this.repository.createXPath("kein Xpath Ausdruck", null);
}
@Test
public void loadFromJar() throws URISyntaxException {
this.repository = new ContentRepository(ObjectFactory.createProcessor(), Helper.JAR_REPOSITORY.toURI());
final XsltExecutable xsltExecutable = this.repository.loadXsltScript(URI.create("resources/eRechnung/report.xsl"));
assertThat(xsltExecutable).isNotNull();
}
@Test
public void testLoadSchema() {
final URL main = RelativeUriResolverTest.class.getClassLoader().getResource("simple/main.xsd");
final Schema schema = ContentRepository.createSchema(main, new ClassPathResourceResolver("/simple"));
assertThat(schema).isNotNull();
}
@Test
public void testLoadSchemaPackaged() throws URISyntaxException {
final URL main = RelativeUriResolverTest.class.getClassLoader().getResource("packaged/main.xsd");
final Schema schema = ContentRepository.createSchema(main,
new ClassPathResourceResolver(RelativeUriResolverTest.class.getClassLoader().getResource("packaged/").toURI()));
assertThat(schema).isNotNull();
}
}

View file

@ -57,65 +57,66 @@ public class ConversionServiceTest {
@Before
public void setup() {
service = new ConversionService();
repository = new ContentRepository(ObjectFactory.createProcessor(), new File("src/test/resources/examples/repository").toURI());
this.service = new ConversionService();
this.repository = new ContentRepository(ObjectFactory.createProcessor(),
new File("src/test/resources/examples/repository").toURI());
}
@Test
public void testMarshalNull() {
exception.expect(ConversionService.ConversionExeption.class);
service.writeXml(null);
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.writeXml(null);
}
@Test
public void testMarshalUnknown() {
exception.expect(ConversionService.ConversionExeption.class);
service.writeXml(new Serializable() {
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.writeXml(new Serializable() {
});
}
@Test
public void testUnmarshal() throws URISyntaxException {
final Scenarios s = service.readXml(VALID_XML.toURI(), Scenarios.class);
final Scenarios s = this.service.readXml(VALID_XML.toURI(), Scenarios.class);
assertThat(s).isNotNull();
assertThat(s.getName()).isEqualToIgnoringCase("XInneres");
}
@Test
public void testUnmarshalWithSchema() throws URISyntaxException {
final Scenarios s = service.readXml(VALID_XML.toURI(), Scenarios.class, repository.createSchema(SCHEMA));
final Scenarios s = this.service.readXml(VALID_XML.toURI(), Scenarios.class, ContentRepository.createSchema(SCHEMA));
assertThat(s).isNotNull();
assertThat(s.getName()).isEqualToIgnoringCase("XInneres");
}
@Test
public void testUnmarshalInvalidXml() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(INVALID_XML.toURI(), Scenarios.class, repository.createSchema(SCHEMA));
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(INVALID_XML.toURI(), Scenarios.class, ContentRepository.createSchema(SCHEMA));
}
@Test
public void testUnmarshalIllFormed() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(ILLFORMED_XML.toURI(), Scenarios.class, repository.createSchema(SCHEMA));
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(ILLFORMED_XML.toURI(), Scenarios.class, ContentRepository.createSchema(SCHEMA));
}
@Test
public void testUnmarshalEmpty() {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(null, Scenarios.class);
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(null, Scenarios.class);
}
@Test
public void testUnmarshalUnknownType() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(VALID_XML.toURI(), ConversionService.class);
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(VALID_XML.toURI(), ConversionService.class);
}
@Test
public void testUnmarshalWithoutType() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(VALID_XML.toURI(), null);
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(VALID_XML.toURI(), null);
}
}

View file

@ -56,27 +56,27 @@ public class DefaultCheckTest {
@Before
public void setup() throws URISyntaxException {
CheckConfiguration d = new CheckConfiguration(SCENARIO_DEFINITION.toURI());
final CheckConfiguration d = new CheckConfiguration(SCENARIO_DEFINITION.toURI());
d.setScenarioRepository(new File("src/test/resources/examples/repository").toURI());
implementation = new DefaultCheck(d);
this.implementation = new DefaultCheck(d);
}
@Test
public void testHappyCase() throws Exception {
final XdmNode doc = implementation.checkInput(read(VALID_EXAMPLE));
final XdmNode doc = this.implementation.checkInput(read(VALID_EXAMPLE));
assertThat(doc).isNotNull();
}
@Test
public void testHappyCaseDocument() throws Exception {
final Document doc = implementation.check(read(VALID_EXAMPLE));
final Document doc = this.implementation.check(read(VALID_EXAMPLE));
assertThat(doc).isNotNull();
}
@Test
public void testMultipleCase() throws Exception {
final List<Input> input = IntStream.range(0, MULTI_COUNT).mapToObj(i -> read(VALID_EXAMPLE)).collect(Collectors.toList());
final List<XdmNode> docs = implementation.checkInput(input);
final List<XdmNode> docs = this.implementation.checkInput(input);
assertThat(docs).isNotNull();
assertThat(docs).hasSize(MULTI_COUNT);
}
@ -84,7 +84,7 @@ public class DefaultCheckTest {
@Test
public void testMultipleCaseDocument() throws Exception {
final List<Input> input = IntStream.range(0, MULTI_COUNT).mapToObj(i -> read(VALID_EXAMPLE)).collect(Collectors.toList());
final List<Document> docs = implementation.check(input);
final List<Document> docs = this.implementation.check(input);
assertThat(docs).isNotNull();
assertThat(docs).hasSize(MULTI_COUNT);
}

View file

@ -22,7 +22,6 @@ package de.kosit.validationtool.impl;
import static de.kosit.validationtool.api.InputFactory.read;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URL;
import org.junit.Before;
@ -37,6 +36,8 @@ import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
import net.sf.saxon.s9api.XdmNode;
/**
* Testet die Document Parsing-Funktionalitäten.
*
* @author Andreas Penski
*/
public class DocumentParserTest {
@ -47,8 +48,6 @@ public class DocumentParserTest {
private static final URL NOT_EXISTING = ConversionServiceTest.class.getResource("/does not exist.xml");
@Rule
public ExpectedException exception = ExpectedException.none();
@ -56,22 +55,21 @@ public class DocumentParserTest {
@Before
public void setup() {
parser = new DocumentParseAction();
this.parser = new DocumentParseAction();
}
@Test
public void testSimple() throws IOException {
final Result<XdmNode, XMLSyntaxError> result = parser.parseDocument(read(CONTENT));
public void testSimple() {
final Result<XdmNode, XMLSyntaxError> result = this.parser.parseDocument(read(CONTENT));
assertThat(result).isNotNull();
assertThat(result.getObject()).isNotNull();
assertThat(result.getErrors()).isEmpty();
assertThat(result.isValid()).isTrue();
}
@Test
public void testIllformed() throws IOException {
final Result<XdmNode, XMLSyntaxError> result = parser.parseDocument(read(ILLFORMED));
public void testIllformed() {
final Result<XdmNode, XMLSyntaxError> result = this.parser.parseDocument(read(ILLFORMED));
assertThat(result).isNotNull();
assertThat(result.getErrors()).isNotEmpty();
assertThat(result.getObject()).isNull();
@ -80,10 +78,9 @@ public class DocumentParserTest {
@Test
public void testNullInput() {
exception.expect(IllegalArgumentException.class);
parser.parseDocument(null);
this.exception.expect(IllegalArgumentException.class);
this.parser.parseDocument(null);
}
}

View file

@ -57,6 +57,8 @@ public class Helper {
public static final URI REPOSITORY = EXAMPLES_DIR.resolve("repository/");
public static final URL JAR_REPOSITORY = Helper.class.getClassLoader().getResource("xrechnung/repository/");
public static final URI NOT_EXISTING = EXAMPLES_DIR.resolve("doesnotexist");
public static final URI SAMPLE_DIR = EXAMPLES_DIR.resolve("UBLReady/");
@ -73,18 +75,18 @@ public class Helper {
* @param url die url die geladen werden soll
* @return ein result objekt mit Dokument
*/
public static XdmNode load(URL url) {
try ( InputStream input = url.openStream() ) {
public static XdmNode load(final URL url) {
try ( final InputStream input = url.openStream() ) {
return ObjectFactory.createProcessor().newDocumentBuilder().build(new StreamSource(input));
} catch (SaxonApiException | IOException e) {
} catch (final SaxonApiException | IOException e) {
throw new IllegalStateException("Fehler beim Laden der XML-Datei", e);
}
}
public static <T> T load(URL url, Class<T> type) throws URISyntaxException {
ConversionService c = new ConversionService();
public static <T> T load(final URL url, final Class<T> type) throws URISyntaxException {
final ConversionService c = new ConversionService();
c.initialize(de.kosit.validationtool.model.reportInput.ObjectFactory.class.getPackage(),
de.kosit.validationtool.cmd.assertions.ObjectFactory.class.getPackage(),
de.kosit.validationtool.model.scenarios.ObjectFactory.class.getPackage());

View file

@ -23,6 +23,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
@ -44,7 +45,7 @@ public class RelativeUriResolverTest {
static {
try {
BASE = RelativeUriResolver.class.getResource("/examples/assertions/").toURI();
} catch (URISyntaxException e) {
} catch (final URISyntaxException e) {
throw new IllegalStateException(e);
}
}
@ -56,19 +57,35 @@ public class RelativeUriResolverTest {
@Test
public void testSucces() throws TransformerException {
final Source resource = resolver.resolve("ubl-0001.xml", BASE.toASCIIString());
final Source resource = this.resolver.resolve("ubl-0001.xml", BASE.toASCIIString());
assertThat(resource).isNotNull();
}
@Test
public void testNotExisting() throws TransformerException {
exception.expect(IllegalStateException.class);
resolver.resolve("ubl-0001", BASE.toASCIIString());
this.exception.expect(IllegalStateException.class);
this.resolver.resolve("ubl-0001", BASE.toASCIIString());
}
@Test
public void testOutOfPath() throws TransformerException {
exception.expect(IllegalStateException.class);
resolver.resolve("../results/report.xml", BASE.toASCIIString());
this.exception.expect(IllegalStateException.class);
this.resolver.resolve("../results/report.xml", BASE.toASCIIString());
}
@Test
public void testClasspathLocal() throws URISyntaxException, TransformerException {
this.resolver = new RelativeUriResolver(RelativeUriResolver.class.getClassLoader().getResource("simple").toURI());
final URL moz = RelativeUriResolverTest.class.getClassLoader().getResource("simple/main.xsd");
final Source resolved = this.resolver.resolve("./resources/reference.xsd", moz.toURI().toASCIIString());
assertThat(resolved).isNotNull();
}
@Test
public void testClasspathJAR() throws URISyntaxException, TransformerException {
this.resolver = new RelativeUriResolver(RelativeUriResolver.class.getClassLoader().getResource("packaged").toURI());
final URL moz = RelativeUriResolverTest.class.getClassLoader().getResource("packaged/main.xsd");
final Source resolved = this.resolver.resolve("./resources/reference.xsd", moz.toURI().toASCIIString());
assertThat(resolved).isNotNull();
}
}

View file

@ -24,6 +24,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import org.junit.Before;
@ -31,6 +32,7 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.api.CheckConfiguration;
import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.impl.tasks.DocumentParseAction;
import de.kosit.validationtool.model.scenarios.ScenarioType;
@ -57,46 +59,57 @@ public class ScenarioRepositoryTest {
@Before
public void setup() {
content = new ContentRepository(ObjectFactory.createProcessor(), new File("src/test/resources/examples/repository").toURI());
Scenarios def = new Scenarios();
ScenarioType t = new ScenarioType();
this.content = new ContentRepository(ObjectFactory.createProcessor(), new File("src/test/resources/examples/repository").toURI());
final Scenarios def = new Scenarios();
final ScenarioType t = new ScenarioType();
t.setMatch("//*:name");
t.setName("Test");
t.initialize(content, true);
t.initialize(this.content, true);
def.getScenario().add(t);
repository = new ScenarioRepository(ObjectFactory.createProcessor(), content);
repository.initialize(def);
this.repository = new ScenarioRepository(ObjectFactory.createProcessor(), this.content);
this.repository.initialize(def);
}
@Test
public void testHappyCase() throws Exception {
final Result<ScenarioType, String> scenario = repository.selectScenario(load(SAMPLE));
final Result<ScenarioType, String> scenario = this.repository.selectScenario(load(SAMPLE));
assertThat(scenario).isNotNull();
assertThat(scenario.isValid()).isTrue();
}
@Test
public void testNonMatch() throws Exception {
repository.getScenarios().getScenario().clear();
final Result<ScenarioType, String> scenario = repository.selectScenario(load(SAMPLE));
this.repository.getScenarios().getScenario().clear();
final Result<ScenarioType, String> scenario = this.repository.selectScenario(load(SAMPLE));
assertThat(scenario).isNotNull();
assertThat(scenario.isValid()).isFalse();
}
@Test
public void testMultiMatch() throws Exception {
ScenarioType t = new ScenarioType();
final ScenarioType t = new ScenarioType();
t.setMatch("//*:name");
t.setName("Test");
t.initialize(content, true);
repository.getScenarios().getScenario().add(t);
final Result<ScenarioType, String> scenario = repository.selectScenario(load(SAMPLE));
t.initialize(this.content, true);
this.repository.getScenarios().getScenario().add(t);
final Result<ScenarioType, String> scenario = this.repository.selectScenario(load(SAMPLE));
assertThat(scenario).isNotNull();
assertThat(scenario.isValid()).isFalse();
}
private XdmNode load(URL url) throws IOException {
DocumentParseAction p = new DocumentParseAction();
private static XdmNode load(final URL url) throws IOException {
final DocumentParseAction p = new DocumentParseAction();
return p.parseDocument(read(url)).getObject();
}
@Test
public void loadFromJar() throws URISyntaxException {
this.content = new ContentRepository(ObjectFactory.createProcessor(), Helper.JAR_REPOSITORY.toURI());
this.repository = new ScenarioRepository(ObjectFactory.createProcessor(), this.content);
final CheckConfiguration conf = new CheckConfiguration(
ScenarioRepository.class.getClassLoader().getResource("xrechnung/scenarios.xml").toURI());
this.repository.initialize(conf);
assertThat(this.repository.getScenarios()).isNotNull();
}
}

View file

@ -21,7 +21,6 @@ package de.kosit.validationtool.impl;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
@ -52,35 +51,33 @@ public class VersioningTest {
private ConversionService service;
private ContentRepository repository;
@Before
public void setup() {
service = new ConversionService();
repository = new ContentRepository(ObjectFactory.createProcessor(), new File("src/test/resources/examples/repository").toURI());
this.service = new ConversionService();
}
@Test
public void testBase() throws URISyntaxException {
final Scenarios result = service.readXml(BASE.toURI(), Scenarios.class, repository.getScenarioSchema());
final Scenarios result = this.service.readXml(BASE.toURI(), Scenarios.class, ContentRepository.getScenarioSchema());
assertThat(result).isNotNull();
}
@Test
public void testFrameworkIncrement() throws URISyntaxException {
final Scenarios result = service.readXml(INCREMENT.toURI(), Scenarios.class, repository.getScenarioSchema());
final Scenarios result = this.service.readXml(INCREMENT.toURI(), Scenarios.class, ContentRepository.getScenarioSchema());
assertThat(result).isNotNull();
}
@Test
public void testNewFeature() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(NEW_FEATURE.toURI(), Scenarios.class, repository.getScenarioSchema());
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(NEW_FEATURE.toURI(), Scenarios.class, ContentRepository.getScenarioSchema());
}
@Test
public void testNewVersion() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(NEW_VERSION.toURI(), Scenarios.class, repository.getScenarioSchema());
this.exception.expect(ConversionService.ConversionExeption.class);
this.service.readXml(NEW_VERSION.toURI(), Scenarios.class, ContentRepository.getScenarioSchema());
}
}

View file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns:ref="http://www.example.org/reference" xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/main"
elementFormDefault="qualified">
<import namespace="http://www.example.org/reference" schemaLocation="./resources/reference.xsd" />
<complexType name="MainType">
<sequence>
<element name="ref" type="ref:ReferenzTyp"></element>
</sequence>
</complexType>
</schema>

View file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/reference" xmlns:tns="http://www.example.org/reference" elementFormDefault="qualified">
<complexType name="ReferenzTyp">
<sequence>
<element name="some" type="string"></element>
</sequence>
</complexType>
</schema>