Search in sources :

Example 36 with SchematronOutputType

use of org.oclc.purl.dsdl.svrl.SchematronOutputType in project ph-schematron by phax.

the class SchematronHelperTest method testReadValidSchematronInvalidXML.

@Test
public void testReadValidSchematronInvalidXML() {
    final SchematronOutputType aSO = SchematronHelper.applySchematron(SchematronResourceSCH.fromClassPath(VALID_SCHEMATRON), new ClassPathResource(VALID_XMLINSTANCE + ".does.not.exist"));
    assertNull("Invalid XML", aSO);
}
Also used : SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) Test(org.junit.Test)

Example 37 with SchematronOutputType

use of org.oclc.purl.dsdl.svrl.SchematronOutputType in project ph-schematron by phax.

the class SchematronHelperTest method testReadInvalidSchematronInvalidXML.

@Test
public void testReadInvalidSchematronInvalidXML() {
    final SchematronOutputType aSO = SchematronHelper.applySchematron(SchematronResourceSCH.fromClassPath(VALID_SCHEMATRON + ".does.not.exist"), new ClassPathResource(VALID_XMLINSTANCE + ".does.not.exist"));
    assertNull("Invalid Schematron and XML", aSO);
}
Also used : SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) Test(org.junit.Test)

Example 38 with SchematronOutputType

use of org.oclc.purl.dsdl.svrl.SchematronOutputType in project ph-schematron by phax.

the class Schematron method _performValidation.

private void _performValidation(@Nonnull final ISchematronResource aSch, @Nonnull final ICommonsList<ResourceCollection> aResCollections, @Nullable final File aSVRLDirectory, final boolean bExpectSuccess) throws BuildException {
    // Resolve resourceCollections - pain in the ass
    final ICommonsMap<File, DirectoryData> aFiles = new CommonsHashMap<>();
    for (final ResourceCollection aResCollection : aResCollections) {
        if (!aResCollection.isFilesystemOnly())
            _error("Only FileSystem resources are supported.");
        else
            for (final Resource aRes : aResCollection) {
                if (!aRes.isExists()) {
                    _error("Could not find resource " + aRes.toLongString() + " to copy.");
                    continue;
                }
                File baseDir = NULL_FILE_PLACEHOLDER;
                String name = aRes.getName();
                final FileProvider fp = aRes.as(FileProvider.class);
                if (fp != null) {
                    final FileResource fr = ResourceUtils.asFileResource(fp);
                    baseDir = _getKeyFile(fr.getBaseDir());
                    if (baseDir == NULL_FILE_PLACEHOLDER)
                        name = fr.getFile().getAbsolutePath();
                }
                if ((aRes.isDirectory() || fp != null) && name != null) {
                    final DirectoryData aBaseDir = aFiles.computeIfAbsent(_getKeyFile(baseDir), k -> new DirectoryData(k));
                    if (aRes.isDirectory())
                        aBaseDir.addDir(name);
                    else
                        aBaseDir.addFile(name);
                } else
                    _error("Could not resolve resource " + aRes.toLongString() + " to a file.");
            }
    }
    for (final DirectoryData aBaseDir : aFiles.values()) {
        log("Scanning directory " + aBaseDir.getBaseDir() + " for XMLs to be Schematron validated", Project.MSG_DEBUG);
        final ICommonsList<String> aIncludes = new CommonsArrayList<>();
        aIncludes.addAll(aBaseDir.getFiles());
        for (final String sFile : aBaseDir.getDirs()) aIncludes.add(sFile + "/**");
        final DirectoryScanner aScanner = new DirectoryScanner();
        aScanner.setBasedir(aBaseDir.getBaseDir());
        if (aIncludes.isNotEmpty())
            aScanner.setIncludes(aIncludes.toArray(new String[0]));
        aScanner.setCaseSensitive(true);
        aScanner.scan();
        final String[] aXMLFilenames = aScanner.getIncludedFiles();
        if (aXMLFilenames != null) {
            for (final String sXMLFilename : aXMLFilenames) {
                final File aXMLFile = new File(aBaseDir.getBaseDir(), sXMLFilename);
                // Validate XML file
                log("Validating XML file '" + aXMLFile.getPath() + "' against Schematron rules from '" + m_aSchematronFile.getName() + "' expecting " + (bExpectSuccess ? "success" : "failure"), Project.MSG_INFO);
                try {
                    final SchematronOutputType aSOT = aSch.applySchematronValidationToSVRL(TransformSourceFactory.create(aXMLFile));
                    if (aSVRLDirectory != null) {
                        // Save SVRL
                        final File aSVRLFile = new File(aSVRLDirectory, sXMLFilename + ".svrl");
                        if (!aSVRLFile.getParentFile().mkdirs())
                            log("Failed to create parent directory of '" + aSVRLFile.getAbsolutePath() + "'!", Project.MSG_ERR);
                        if (new SVRLMarshaller().write(aSOT, aSVRLFile).isSuccess())
                            log("Successfully saved SVRL file '" + aSVRLFile.getPath() + "'", Project.MSG_INFO);
                        else
                            log("Error saving SVRL file '" + aSVRLFile.getPath() + "'", Project.MSG_ERR);
                    }
                    if (false)
                        System.out.println(new SVRLMarshaller().getAsString(aSOT));
                    final ICommonsList<AbstractSVRLMessage> aMessages = SVRLHelper.getAllFailedAssertionsAndSuccessfulReports(aSOT);
                    final int nErrorMessages = aMessages.getCount(x -> x.getFlag().isError());
                    final int nWarningMessages = aMessages.size() - nErrorMessages;
                    final String sErrors = nErrorMessages + " Schematron error" + (nErrorMessages == 1 ? "" : "s");
                    final String sWarnings = nWarningMessages + " Schematron warning" + (nWarningMessages == 1 ? "" : "s");
                    if (bExpectSuccess) {
                        // No failed assertions expected
                        if (nErrorMessages > 0) {
                            final StringBuilder aMessage = new StringBuilder();
                            aMessage.append(sErrors + (nWarningMessages > 0 ? " and " + sWarnings : "") + " for XML file '" + aXMLFile.getPath() + "'");
                            for (final AbstractSVRLMessage aMsg : aMessages) {
                                aMessage.append("\n  ").append(ErrorTextProvider.DEFAULT.getErrorText(aMsg.getAsResourceError(aXMLFile.getPath()), Locale.US));
                            }
                            // As at least one error is contained, it's okay to throw an
                            // exception in case
                            _error(aMessage.toString());
                            continue;
                        }
                        // Success as expected
                        log("XML file '" + aXMLFile.getPath() + "' was validated against Schematron '" + aSch.getResource().getPath() + "' and matches the rules" + (nWarningMessages > 0 ? " - only " + sWarnings + " are contained" : ""), Project.MSG_INFO);
                    } else {
                        // At least one failed assertions expected
                        if (nErrorMessages == 0) {
                            String sMessage = "No Schematron errors for erroneous XML file '" + aXMLFile.getPath() + "'";
                            if (nWarningMessages > 0)
                                sMessage += " - only " + sWarnings + " are contained";
                            _error(sMessage);
                            continue;
                        }
                        // Success as expected
                        log("XML file '" + aXMLFile.getPath() + "' was validated against Schematron '" + aSch.getResource().getPath() + "' " + sErrors + (nWarningMessages > 0 ? " and " + sWarnings : "") + " were found (as expected)", Project.MSG_INFO);
                    }
                } catch (final BuildException up) {
                    throw up;
                } catch (final Exception ex) {
                    final String sMessage = "Exception validating XML '" + aXMLFile.getPath() + "' against Schematron rules from '" + m_aSchematronFile.getName() + "'. Technical details: " + ex.getClass().getSimpleName() + " - " + ex.getMessage();
                    _error(sMessage, ex);
                    continue;
                }
            }
        }
    }
}
Also used : OverrideOnDemand(com.helger.commons.annotation.OverrideOnDemand) Task(org.apache.tools.ant.Task) IError(com.helger.commons.error.IError) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) URIResolver(javax.xml.transform.URIResolver) ResourceCollection(org.apache.tools.ant.types.ResourceCollection) FileResource(org.apache.tools.ant.types.resources.FileResource) SchematronResourceXSLT(com.helger.schematron.xslt.SchematronResourceXSLT) AbstractSVRLMessage(com.helger.schematron.svrl.AbstractSVRLMessage) SVRLHelper(com.helger.schematron.svrl.SVRLHelper) ESchematronMode(com.helger.schematron.ESchematronMode) Locale(java.util.Locale) Project(org.apache.tools.ant.Project) CollectingTransformErrorListener(com.helger.xml.transform.CollectingTransformErrorListener) Nonnull(javax.annotation.Nonnull) TransformSourceFactory(com.helger.xml.transform.TransformSourceFactory) Nullable(javax.annotation.Nullable) EntityResolver(org.xml.sax.EntityResolver) ErrorTextProvider(com.helger.commons.error.ErrorTextProvider) Resource(org.apache.tools.ant.types.Resource) EErrorLevel(com.helger.commons.error.level.EErrorLevel) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) StringHelper(com.helger.commons.string.StringHelper) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) CollectingPSErrorHandler(com.helger.schematron.pure.errorhandler.CollectingPSErrorHandler) BuildException(org.apache.tools.ant.BuildException) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) File(java.io.File) SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) XMLCatalog(org.apache.tools.ant.types.XMLCatalog) ISchematronResource(com.helger.schematron.ISchematronResource) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsList(com.helger.commons.collection.impl.ICommonsList) SchematronResourceSCH(com.helger.schematron.xslt.SchematronResourceSCH) FileProvider(org.apache.tools.ant.types.resources.FileProvider) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) SchematronResourcePure(com.helger.schematron.pure.SchematronResourcePure) IErrorList(com.helger.commons.error.list.IErrorList) ResourceUtils(org.apache.tools.ant.util.ResourceUtils) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) FileResource(org.apache.tools.ant.types.resources.FileResource) Resource(org.apache.tools.ant.types.Resource) ISchematronResource(com.helger.schematron.ISchematronResource) FileResource(org.apache.tools.ant.types.resources.FileResource) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) AbstractSVRLMessage(com.helger.schematron.svrl.AbstractSVRLMessage) BuildException(org.apache.tools.ant.BuildException) SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) FileProvider(org.apache.tools.ant.types.resources.FileProvider) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) ResourceCollection(org.apache.tools.ant.types.ResourceCollection)

Example 39 with SchematronOutputType

use of org.oclc.purl.dsdl.svrl.SchematronOutputType in project ph-schematron by phax.

the class SchematronValidationMojo method _performValidation.

private void _performValidation(@Nonnull final ISchematronResource aSch, @Nonnull final File aXMLDirectory, @Nullable final String sXMLIncludes, @Nullable final String sXMLExcludes, @Nullable final File aSVRLDirectory, final boolean bExpectSuccess) throws MojoExecutionException, MojoFailureException {
    final DirectoryScanner aScanner = new DirectoryScanner();
    aScanner.setBasedir(aXMLDirectory);
    if (StringHelper.hasText(sXMLIncludes))
        aScanner.setIncludes(new String[] { sXMLIncludes });
    if (StringHelper.hasText(sXMLExcludes))
        aScanner.setExcludes(new String[] { sXMLExcludes });
    aScanner.setCaseSensitive(true);
    aScanner.scan();
    final String[] aXMLFilenames = aScanner.getIncludedFiles();
    if (aXMLFilenames != null) {
        for (final String sXMLFilename : aXMLFilenames) {
            final File aXMLFile = new File(aXMLDirectory, sXMLFilename);
            // Validate XML file
            getLog().info("Validating XML file '" + aXMLFile.getPath() + "' against Schematron rules from '" + m_aSchematronFile + "' expecting " + (bExpectSuccess ? "success" : "failure"));
            try {
                final SchematronOutputType aSOT = aSch.applySchematronValidationToSVRL(TransformSourceFactory.create(aXMLFile));
                if (aSVRLDirectory != null) {
                    // Save SVRL
                    final File aSVRLFile = new File(aSVRLDirectory, sXMLFilename + ".svrl");
                    if (!aSVRLFile.getParentFile().mkdirs())
                        getLog().error("Failed to create parent directory of '" + aSVRLFile.getAbsolutePath() + "'!");
                    if (new SVRLMarshaller().write(aSOT, aSVRLFile).isSuccess())
                        getLog().info("Successfully saved SVRL file '" + aSVRLFile.getPath() + "'");
                    else
                        getLog().error("Error saving SVRL file '" + aSVRLFile.getPath() + "'");
                }
                final ICommonsList<SVRLFailedAssert> aFailedAsserts = SVRLHelper.getAllFailedAssertions(aSOT);
                if (bExpectSuccess) {
                    // No failed assertions expected
                    if (aFailedAsserts.isNotEmpty()) {
                        final String sMessage = aFailedAsserts.size() + " failed Schematron assertions for XML file '" + aXMLFile.getPath() + "'";
                        getLog().error(sMessage);
                        aFailedAsserts.forEach(x -> getLog().error(x.getAsResourceError(aXMLFile.getPath()).getAsString(Locale.US)));
                        throw new MojoFailureException(sMessage);
                    }
                } else {
                    // At least one failed assertions expected
                    if (aFailedAsserts.isEmpty()) {
                        final String sMessage = "No failed Schematron assertions for erroneous XML file '" + aXMLFile.getPath() + "'";
                        getLog().error(sMessage);
                        throw new MojoFailureException(sMessage);
                    }
                }
            } catch (final MojoFailureException | MojoExecutionException up) {
                throw up;
            } catch (final Exception ex) {
                final String sMessage = "Exception validating XML '" + aXMLFile.getPath() + "' against Schematron rules from '" + m_aSchematronFile + "'";
                getLog().error(sMessage, ex);
                throw new MojoExecutionException(sMessage, ex);
            }
        }
    }
}
Also used : SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) SVRLFailedAssert(com.helger.schematron.svrl.SVRLFailedAssert) DirectoryScanner(org.codehaus.plexus.util.DirectoryScanner) MojoFailureException(org.apache.maven.plugin.MojoFailureException) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) File(java.io.File) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Example 40 with SchematronOutputType

use of org.oclc.purl.dsdl.svrl.SchematronOutputType in project ph-schematron by phax.

the class SchematronResourcePure method applySchematronValidationToSVRL.

/**
 * The main method to convert a node to an SVRL document.
 *
 * @param aXMLNode
 *        The source node to be validated. May not be <code>null</code>.
 * @param sBaseURI
 *        Base URI of the XML document to be validated. May be
 *        <code>null</code>.
 * @return The SVRL document. Never <code>null</code>.
 * @throws SchematronException
 *         in case of a sever error validating the schema
 */
@Nonnull
public SchematronOutputType applySchematronValidationToSVRL(@Nonnull final Node aXMLNode, @Nullable final String sBaseURI) throws SchematronException {
    ValueEnforcer.notNull(aXMLNode, "XMLNode");
    final SchematronOutputType aSOT = getOrCreateBoundSchema().validateComplete(aXMLNode, sBaseURI);
    // Debug print the created SVRL document
    if (SchematronDebug.isShowCreatedSVRL())
        s_aLogger.info("Created SVRL:\n" + new SVRLMarshaller(false).getAsString(aSOT));
    return aSOT;
}
Also used : SchematronOutputType(org.oclc.purl.dsdl.svrl.SchematronOutputType) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) Nonnull(javax.annotation.Nonnull)

Aggregations

SchematronOutputType (org.oclc.purl.dsdl.svrl.SchematronOutputType)41 Test (org.junit.Test)20 SVRLMarshaller (com.helger.schematron.svrl.SVRLMarshaller)18 FileSystemResource (com.helger.commons.io.resource.FileSystemResource)17 SchematronResourcePure (com.helger.schematron.pure.SchematronResourcePure)15 ClassPathResource (com.helger.commons.io.resource.ClassPathResource)14 IReadableResource (com.helger.commons.io.resource.IReadableResource)11 Document (org.w3c.dom.Document)8 AbstractSchematronResource (com.helger.schematron.AbstractSchematronResource)6 LoggingPSErrorHandler (com.helger.schematron.pure.errorhandler.LoggingPSErrorHandler)6 ISchematronResource (com.helger.schematron.ISchematronResource)5 SchematronResourceSCH (com.helger.schematron.xslt.SchematronResourceSCH)5 MapBasedXPathFunctionResolver (com.helger.xml.xpath.MapBasedXPathFunctionResolver)5 SVRLFailedAssert (com.helger.schematron.svrl.SVRLFailedAssert)4 File (java.io.File)4 XQueryAsXPathFunctionConverter (com.helger.schematron.xpath.XQueryAsXPathFunctionConverter)3 Nonnull (javax.annotation.Nonnull)3 Nullable (javax.annotation.Nullable)3 CollectingPSErrorHandler (com.helger.schematron.pure.errorhandler.CollectingPSErrorHandler)2 PSReader (com.helger.schematron.pure.exchange.PSReader)2