Search in sources :

Example 46 with SchematronOutputType

use of com.helger.schematron.svrl.jaxb.SchematronOutputType in project ph-schematron by phax.

the class AbstractSchematronXSLTBasedResource method getSchematronValidity.

@Nonnull
public final EValidity getSchematronValidity(@Nonnull final Node aXMLNode, @Nullable final String sBaseURI) throws Exception {
    ValueEnforcer.notNull(aXMLNode, "XMLNode");
    // We don't have a short circuit here - apply the full validation
    final SchematronOutputType aSO = applySchematronValidationToSVRL(aXMLNode, sBaseURI);
    if (aSO == null)
        return EValidity.INVALID;
    // And now filter all elements that make the passed source invalid
    return m_aXSLTValidator.getSchematronValidity(aSO);
}
Also used : SchematronOutputType(com.helger.schematron.svrl.jaxb.SchematronOutputType) Nonnull(javax.annotation.Nonnull)

Example 47 with SchematronOutputType

use of com.helger.schematron.svrl.jaxb.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())
            _errorOrFail("Only FileSystem resources are supported.");
        else
            for (final Resource aRes : aResCollection) {
                if (!aRes.isExists()) {
                    _errorOrFail("Could not find resource " + aRes.toLongString() + " to copy.");
                    continue;
                }
                File aBaseDir = NULL_FILE_PLACEHOLDER;
                String sName = aRes.getName();
                final FileProvider aFP = aRes.as(FileProvider.class);
                if (aFP != null) {
                    final FileResource aFR = ResourceUtils.asFileResource(aFP);
                    aBaseDir = _getKeyFile(aFR.getBaseDir());
                    if (aBaseDir == NULL_FILE_PLACEHOLDER)
                        sName = aFR.getFile().getAbsolutePath();
                }
                if ((aRes.isDirectory() || aFP != null) && sName != null) {
                    final DirectoryData aBaseDirData = aFiles.computeIfAbsent(_getKeyFile(aBaseDir), DirectoryData::new);
                    if (aRes.isDirectory())
                        aBaseDirData.addDir(sName);
                    else
                        aBaseDirData.addFile(sName);
                } else
                    _errorOrFail("Could not resolve resource " + aRes.toLongString() + " to a file.");
            }
    }
    for (final DirectoryData aBaseDirData : aFiles.values()) {
        _debug("Scanning directory " + aBaseDirData.getBaseDir() + " for XMLs to be Schematron validated");
        final ICommonsList<String> aIncludes = new CommonsArrayList<>();
        aIncludes.addAll(aBaseDirData.getFiles());
        for (final String sFile : aBaseDirData.getDirs()) aIncludes.add(sFile + "/**");
        final DirectoryScanner aScanner = new DirectoryScanner();
        aScanner.setBasedir(aBaseDirData.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(aBaseDirData.getBaseDir(), sXMLFilename);
                // Validate XML file
                _info("Validating XML file '" + aXMLFile.getPath() + "' against Schematron rules from '" + m_aSchematronFile.getName() + "' expecting " + (bExpectSuccess ? "success" : "failure"));
                try {
                    // This is performing the validation
                    final SchematronOutputType aSOT = aSch.applySchematronValidationToSVRL(TransformSourceFactory.create(aXMLFile));
                    if (aSOT != null) {
                        // Beautified SVRL :)
                        final SVRLMarshaller aMarshaller = new SVRLMarshaller(false);
                        aMarshaller.setFormattedOutput(true);
                        aMarshaller.setNamespaceContext(SVRLNamespaceContext.getInstance());
                        // If aSOT == null a different error should be present
                        if (aSVRLDirectory != null) {
                            // Save SVRL
                            final File aSVRLFile = new File(aSVRLDirectory, sXMLFilename + ".svrl");
                            if (FileOperations.createDirIfNotExisting(aSVRLFile.getParentFile()).isFailure())
                                _error("Failed to create parent directory of '" + aSVRLFile.getAbsolutePath() + "'!");
                            if (aMarshaller.write(aSOT, aSVRLFile).isSuccess())
                                _info("Successfully saved SVRL file '" + aSVRLFile.getPath() + "'");
                            else
                                _error("Error saving SVRL file '" + aSVRLFile.getPath() + "'");
                        }
                        _debug("Created SVRL:\n" + aMarshaller.getAsString(aSOT));
                    }
                    final ICommonsList<AbstractSVRLMessage> aMessages = SVRLHelper.getAllFailedAssertionsAndSuccessfulReports(aSOT);
                    final int nErrorMessages = aMessages.getCount(x -> x.getFlag().isGT(EErrorLevel.WARN));
                    final int nWarningMessages = aMessages.getCount(x -> x.getFlag().isEQ(EErrorLevel.WARN));
                    final int nInfoMessages = aMessages.getCount(x -> x.getFlag().isLT(EErrorLevel.WARN));
                    final String sErrors = nErrorMessages + " Schematron error" + (nErrorMessages == 1 ? "" : "s");
                    final String sWarnings = nWarningMessages + " Schematron warning" + (nWarningMessages == 1 ? "" : "s");
                    // No plural - haha
                    final String sInfos = nInfoMessages + " Schematron information";
                    final boolean bExpectationFulfilled;
                    if (bExpectSuccess) {
                        // No failed assertions expected
                        bExpectationFulfilled = nErrorMessages == 0;
                        if (bExpectationFulfilled) {
                            // Success as expected
                            _info("XML file '" + aXMLFile.getPath() + "' was validated against Schematron '" + aSch.getResource().getPath() + "' and matches the rules" + (nWarningMessages > 0 ? " (" + sWarnings + (nWarningMessages == 1 ? " is" : " are") + " contained)" : "") + (nInfoMessages > 0 ? " (" + sInfos + (nInfoMessages == 1 ? " is" : " are") + " contained)" : ""));
                        } else {
                            _error(sErrors + (nWarningMessages > 0 ? " and " + sWarnings : "") + (nInfoMessages > 0 ? " and " + sInfos : "") + " for XML file '" + aXMLFile.getPath() + "'");
                        }
                    } else {
                        // At least one failed assertions expected
                        bExpectationFulfilled = nErrorMessages > 0;
                        if (bExpectationFulfilled) {
                            // Errors as expected
                            _info("XML file '" + aXMLFile.getPath() + "' was validated against Schematron '" + aSch.getResource().getPath() + "' - " + sErrors + (nWarningMessages > 0 ? " and " + sWarnings : "") + (nInfoMessages > 0 ? " and " + sInfos : "") + (nErrorMessages == 1 && (nWarningMessages + nInfoMessages) == 0 ? " was" : " were") + " found (as expected)");
                        } else {
                            _error("No Schematron errors for erroneous XML file '" + aXMLFile.getPath() + "'" + (nWarningMessages > 0 ? " (" + sWarnings + (nWarningMessages == 1 ? " is" : " are") + " contained)" : "") + (nInfoMessages > 0 ? " (" + sInfos + (nInfoMessages == 1 ? " is" : " are") + " contained)" : ""));
                        }
                    }
                    // List details
                    for (final AbstractSVRLMessage aMessage : aMessages) {
                        final SVRLResourceError aResError = aMessage.getAsResourceError(aXMLFile.getPath());
                        final String sText = ErrorTextProvider.DEFAULT.getErrorText(aResError, Locale.US);
                        if (aMessage.getFlag().isGE(EErrorLevel.ERROR))
                            _error(sText);
                        else if (aMessage.getFlag().isGE(EErrorLevel.WARN))
                            _warn(sText);
                        else
                            _info(sText);
                    }
                    if (!bExpectationFulfilled)
                        _errorOrFail("The expectations were not fullfilled, therefore the overall result is negative");
                    if (nErrorMessages > 0 && m_bFailOnValidationError)
                        throw new BuildException("Validation errors are present.");
                    if (nWarningMessages > 0 && m_bFailOnValidationWarn)
                        throw new BuildException("Validation warnings are present.");
                    if (nInfoMessages > 0 && m_bFailOnValidationInfo)
                        throw new BuildException("Validation information are present.");
                } 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();
                    _errorOrFail(sMessage, ex);
                }
            }
        }
    }
}
Also used : FileResource(org.apache.tools.ant.types.resources.FileResource) Resource(org.apache.tools.ant.types.Resource) ISchematronResource(com.helger.schematron.ISchematronResource) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) 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(com.helger.schematron.svrl.jaxb.SchematronOutputType) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) FileProvider(org.apache.tools.ant.types.resources.FileProvider) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) SVRLResourceError(com.helger.schematron.svrl.SVRLResourceError) 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 48 with SchematronOutputType

use of com.helger.schematron.svrl.jaxb.SchematronOutputType in project ph-schematron by phax.

the class IssueXsltKeyTest method validateAndProduceSVRL.

public static void validateAndProduceSVRL(final File schematron, final File xml) throws Exception {
    final IReadableResource aSchematron = new FileSystemResource(schematron.getAbsoluteFile());
    final IReadableResource anXMLSource = new FileSystemResource(xml.getAbsoluteFile());
    final AbstractSchematronResource pure = new SchematronResourceSCH(aSchematron);
    final SchematronOutputType aSVRL = pure.applySchematronValidationToSVRL(anXMLSource);
    assertNotNull(aSVRL);
    if (false)
        System.out.println(new SVRLMarshaller().getAsString(aSVRL));
}
Also used : SchematronOutputType(com.helger.schematron.svrl.jaxb.SchematronOutputType) SchematronResourceSCH(com.helger.schematron.sch.SchematronResourceSCH) IReadableResource(com.helger.commons.io.resource.IReadableResource) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) AbstractSchematronResource(com.helger.schematron.AbstractSchematronResource)

Example 49 with SchematronOutputType

use of com.helger.schematron.svrl.jaxb.SchematronOutputType in project ph-schematron by phax.

the class SVRLMarshallerFuncTest method testCreate.

@Test
public void testCreate() throws Exception {
    final ISchematronResource aSV = SchematronResourceSCH.fromClassPath(VALID_SCHEMATRON);
    assertNotNull("Failed to parse Schematron", aSV);
    final Document aDoc = aSV.applySchematronValidation(new ClassPathResource(VALID_XMLINSTANCE));
    assertNotNull("Failed to parse demo XML", aDoc);
    final SchematronOutputType aSO = new SVRLMarshaller().read(aDoc);
    assertNotNull("Failed to parse Schematron output", aSO);
}
Also used : SchematronOutputType(com.helger.schematron.svrl.jaxb.SchematronOutputType) ISchematronResource(com.helger.schematron.ISchematronResource) Document(org.w3c.dom.Document) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) Test(org.junit.Test)

Example 50 with SchematronOutputType

use of com.helger.schematron.svrl.jaxb.SchematronOutputType in project ph-schematron by phax.

the class Issue077Test method _validateAndProduceSVRL.

private static void _validateAndProduceSVRL(@Nonnull final File aSchematron, @Nonnull final File aXML, final boolean bValid) throws Exception {
    final SchematronResourceSCH aSCH = SchematronResourceSCH.fromFile(aSchematron);
    aSCH.setAllowForeignElements(true);
    // Perform validation
    final SchematronOutputType aSVRL = aSCH.applySchematronValidationToSVRL(new FileSystemResource(aXML));
    assertNotNull(aSVRL);
    if (bValid)
        assertTrue(SVRLHelper.getAllFailedAssertionsAndSuccessfulReports(aSVRL).isEmpty());
    else
        assertTrue(SVRLHelper.getAllFailedAssertionsAndSuccessfulReports(aSVRL).isNotEmpty());
}
Also used : SchematronOutputType(com.helger.schematron.svrl.jaxb.SchematronOutputType) SchematronResourceSCH(com.helger.schematron.sch.SchematronResourceSCH) FileSystemResource(com.helger.commons.io.resource.FileSystemResource)

Aggregations

SchematronOutputType (com.helger.schematron.svrl.jaxb.SchematronOutputType)59 SVRLMarshaller (com.helger.schematron.svrl.SVRLMarshaller)33 FileSystemResource (com.helger.commons.io.resource.FileSystemResource)32 Test (org.junit.Test)21 SchematronResourcePure (com.helger.schematron.pure.SchematronResourcePure)18 ClassPathResource (com.helger.commons.io.resource.ClassPathResource)15 IReadableResource (com.helger.commons.io.resource.IReadableResource)13 SchematronResourceSCH (com.helger.schematron.sch.SchematronResourceSCH)12 ISchematronResource (com.helger.schematron.ISchematronResource)11 AbstractSchematronResource (com.helger.schematron.AbstractSchematronResource)9 Document (org.w3c.dom.Document)9 LoggingPSErrorHandler (com.helger.schematron.pure.errorhandler.LoggingPSErrorHandler)7 IXPathConfig (com.helger.schematron.pure.xpath.IXPathConfig)6 XPathConfigBuilder (com.helger.schematron.pure.xpath.XPathConfigBuilder)6 Nonnull (javax.annotation.Nonnull)5 SVRLFailedAssert (com.helger.schematron.svrl.SVRLFailedAssert)4 MapBasedXPathFunctionResolver (com.helger.xml.xpath.MapBasedXPathFunctionResolver)4 File (java.io.File)4 LoggingPSValidationHandler (com.helger.schematron.pure.validation.LoggingPSValidationHandler)3 XQueryAsXPathFunctionConverter (com.helger.schematron.pure.xpath.XQueryAsXPathFunctionConverter)3