Search in sources :

Example 1 with SVRLResourceError

use of com.helger.schematron.svrl.SVRLResourceError in project phive by phax.

the class PhiveJsonHelperTest method testSVRLError.

@Test
public void testSVRLError() {
    final IError aError = new SVRLResourceError(EErrorLevel.ERROR, "id2", "field1", new SimpleLocation("res12", 3, 4), new ConstantHasErrorText("bla failed"), null, " my test <>");
    // To Json
    final IJsonObject aJson = PhiveJsonHelper.getJsonError(aError, Locale.US);
    assertNotNull(aJson);
    // And back
    final IError aError2 = PhiveJsonHelper.getAsIError(aJson);
    assertNotNull(aError2);
    // And forth
    final IJsonObject aJson2 = PhiveJsonHelper.getJsonError(aError2, Locale.US);
    assertNotNull(aJson2);
    CommonsTestHelper.testDefaultImplementationWithEqualContentObject(aJson, aJson2);
    CommonsTestHelper.testDefaultImplementationWithEqualContentObject(aError, aError2);
}
Also used : IJsonObject(com.helger.json.IJsonObject) SVRLResourceError(com.helger.schematron.svrl.SVRLResourceError) SimpleLocation(com.helger.commons.location.SimpleLocation) IError(com.helger.commons.error.IError) ConstantHasErrorText(com.helger.commons.error.text.ConstantHasErrorText) Test(org.junit.Test)

Example 2 with SVRLResourceError

use of com.helger.schematron.svrl.SVRLResourceError 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 3 with SVRLResourceError

use of com.helger.schematron.svrl.SVRLResourceError in project phive by phax.

the class PhiveJsonHelper method getAsIError.

@Nonnull
public static IError getAsIError(@Nonnull final IJsonObject aObj) {
    final IErrorLevel aErrorLevel = getAsErrorLevel(aObj.getAsString(JSON_ERROR_LEVEL));
    final String sErrorID = aObj.getAsString(JSON_ERROR_ID);
    final String sErrorFieldName = aObj.getAsString(JSON_ERROR_FIELD_NAME);
    // Try new structured version
    ILocation aErrorLocation = getAsErrorLocation(aObj.getAsObject(JSON_ERROR_LOCATION_OBJ));
    if (aErrorLocation == null) {
        final IJsonValue aErrorLocationValue = aObj.getAsValue(JSON_ERROR_LOCATION_STR);
        if (aErrorLocationValue != null) {
            // It's a string - old version
            aErrorLocation = new SimpleLocation(aErrorLocationValue.getAsString());
        }
    }
    final String sErrorText = aObj.getAsString(JSON_ERROR_TEXT);
    final String sTest = aObj.getAsString(JSON_TEST);
    final PhiveRestoredException aLinkedException = PhiveRestoredException.createFromJson(aObj.getAsObject(JSON_EXCEPTION));
    if (sTest != null)
        return new SVRLResourceError(aErrorLevel, sErrorID, sErrorFieldName, aErrorLocation, new ConstantHasErrorText(sErrorText), aLinkedException, sTest);
    return new SingleError(aErrorLevel, sErrorID, sErrorFieldName, aErrorLocation, new ConstantHasErrorText(sErrorText), aLinkedException);
}
Also used : IJsonValue(com.helger.json.IJsonValue) SingleError(com.helger.commons.error.SingleError) ILocation(com.helger.commons.location.ILocation) IErrorLevel(com.helger.commons.error.level.IErrorLevel) SimpleLocation(com.helger.commons.location.SimpleLocation) SVRLResourceError(com.helger.schematron.svrl.SVRLResourceError) ConstantHasErrorText(com.helger.commons.error.text.ConstantHasErrorText) Nonnull(javax.annotation.Nonnull)

Example 4 with SVRLResourceError

use of com.helger.schematron.svrl.SVRLResourceError in project phive by phax.

the class PhiveJsonHelperTest method testSVRLErrorWithException.

@Test
public void testSVRLErrorWithException() {
    final IError aError = new SVRLResourceError(EErrorLevel.ERROR, "id2", "field1", new SimpleLocation("res12", 3, 4), new ConstantHasErrorText("bla failed"), new IllegalStateException("Sthg went wrong"), " my test <>");
    // To Json
    final IJsonObject aJson = PhiveJsonHelper.getJsonError(aError, Locale.US);
    assertNotNull(aJson);
    // And back
    final IError aError2 = PhiveJsonHelper.getAsIError(aJson);
    assertNotNull(aError2);
    // And forth
    final IJsonObject aJson2 = PhiveJsonHelper.getJsonError(aError2, Locale.US);
    assertNotNull(aJson2);
    CommonsTestHelper.testDefaultImplementationWithEqualContentObject(aJson, aJson2);
    // The objects differ, because of the different exception types
    assertTrue(aError2.getLinkedException() instanceof PhiveRestoredException);
    if (false)
        CommonsTestHelper.testDefaultImplementationWithEqualContentObject(aError, aError2);
}
Also used : IJsonObject(com.helger.json.IJsonObject) SVRLResourceError(com.helger.schematron.svrl.SVRLResourceError) SimpleLocation(com.helger.commons.location.SimpleLocation) IError(com.helger.commons.error.IError) ConstantHasErrorText(com.helger.commons.error.text.ConstantHasErrorText) Test(org.junit.Test)

Aggregations

SVRLResourceError (com.helger.schematron.svrl.SVRLResourceError)4 ConstantHasErrorText (com.helger.commons.error.text.ConstantHasErrorText)3 SimpleLocation (com.helger.commons.location.SimpleLocation)3 IError (com.helger.commons.error.IError)2 IJsonObject (com.helger.json.IJsonObject)2 Test (org.junit.Test)2 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)1 CommonsHashMap (com.helger.commons.collection.impl.CommonsHashMap)1 SingleError (com.helger.commons.error.SingleError)1 IErrorLevel (com.helger.commons.error.level.IErrorLevel)1 FileSystemResource (com.helger.commons.io.resource.FileSystemResource)1 ILocation (com.helger.commons.location.ILocation)1 IJsonValue (com.helger.json.IJsonValue)1 ISchematronResource (com.helger.schematron.ISchematronResource)1 AbstractSVRLMessage (com.helger.schematron.svrl.AbstractSVRLMessage)1 SVRLMarshaller (com.helger.schematron.svrl.SVRLMarshaller)1 SchematronOutputType (com.helger.schematron.svrl.jaxb.SchematronOutputType)1 File (java.io.File)1 Nonnull (javax.annotation.Nonnull)1 BuildException (org.apache.tools.ant.BuildException)1