Search in sources :

Example 6 with ValidationResult

use of com.helger.phive.api.result.ValidationResult in project en16931-cii2ubl by phax.

the class CIIToUBL23ConverterTest method testConvertAndValidateAll.

@Test
public void testConvertAndValidateAll() {
    final String sBasePath = MockSettings.getBaseDir().getAbsolutePath();
    for (final File aFile : MockSettings.getAllTestFiles()) {
        LOGGER.info("Converting " + aFile.toString() + " to UBL 2.3");
        // Main conversion
        final ErrorList aErrorList = new ErrorList();
        final Serializable aInvoice = new CIIToUBL23Converter().convertCIItoUBL(aFile, aErrorList);
        assertTrue("Errors: " + aErrorList.toString(), aErrorList.isEmpty());
        assertNotNull(aInvoice);
        final File aDestFile = new File("toubl23/" + aFile.getParentFile().getAbsolutePath().substring(sBasePath.length()), FilenameHelper.getBaseName(aFile.getName()) + "-ubl.xml");
        final ValidationResultList aResultList;
        if (aInvoice instanceof InvoiceType) {
            final InvoiceType aUBLInvoice = (InvoiceType) aInvoice;
            // Check UBL XSD scheme
            final UBL23WriterBuilder<InvoiceType> aWriter = UBL23Writer.invoice().setFormattedOutput(true);
            aWriter.write(aUBLInvoice, aDestFile);
            // Validate against EN16931 validation rules
            aResultList = ValidationExecutionManager.executeValidation(MockSettings.VES_REGISTRY.getOfID(EN16931Validation.VID_UBL_INVOICE_137), ValidationSourceXML.create(new FileSystemResource(aDestFile)));
        } else {
            final CreditNoteType aUBLInvoice = (CreditNoteType) aInvoice;
            // Check UBL XSD scheme
            final UBL23WriterBuilder<CreditNoteType> aWriter = UBL23Writer.creditNote().setFormattedOutput(true);
            aWriter.write(aUBLInvoice, aDestFile);
            // Validate against EN16931 validation rules
            aResultList = ValidationExecutionManager.executeValidation(MockSettings.VES_REGISTRY.getOfID(EN16931Validation.VID_UBL_CREDIT_NOTE_137), ValidationSourceXML.create(new FileSystemResource(aDestFile)));
        }
        assertNotNull(aResultList);
        // Check that no errors (but maybe warnings) are contained
        for (final ValidationResult aResult : aResultList) {
            assertTrue("Errors: " + aResult.getErrorList().toString(), aResult.getErrorList().isEmpty());
        }
    }
}
Also used : Serializable(java.io.Serializable) ErrorList(com.helger.commons.error.list.ErrorList) ValidationResultList(com.helger.phive.api.result.ValidationResultList) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) ValidationResult(com.helger.phive.api.result.ValidationResult) File(java.io.File) CreditNoteType(oasis.names.specification.ubl.schema.xsd.creditnote_23.CreditNoteType) CrossIndustryInvoiceType(un.unece.uncefact.data.standard.crossindustryinvoice._100.CrossIndustryInvoiceType) InvoiceType(oasis.names.specification.ubl.schema.xsd.invoice_23.InvoiceType) Test(org.junit.Test)

Example 7 with ValidationResult

use of com.helger.phive.api.result.ValidationResult in project phive by phax.

the class ValidationExecutorSchematron method applyValidation.

@Nonnull
public ValidationResult applyValidation(@Nonnull final IValidationSourceXML aSource, @Nullable final Locale aLocale) {
    ValueEnforcer.notNull(aSource, "Source");
    final IValidationArtefact aArtefact = getValidationArtefact();
    // Get source as XML DOM Node
    Node aNode = null;
    try {
        aNode = SchematronResourceHelper.getNodeOfSource(aSource.getAsTransformSource(), new DOMReaderSettings().setFeatureValues(EXMLParserFeature.AVOID_XML_ATTACKS));
    } catch (final Exception ex) {
        throw new IllegalStateException("For Schematron validation to work, the source must be valid XML which it is not.", ex);
    }
    if (StringHelper.hasText(m_sPrerequisiteXPath)) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Using Schematron prerequisite path '" + m_sPrerequisiteXPath + "'");
        // Check if the artefact can be applied on the given document by
        // checking the prerequisite XPath
        final XPath aXPathContext = XPathHelper.createNewXPath();
        if (m_aNamespaceContext != null)
            aXPathContext.setNamespaceContext(m_aNamespaceContext);
        try {
            final Boolean aResult = XPathExpressionHelper.evalXPathToBoolean(aXPathContext, m_sPrerequisiteXPath, XMLHelper.getOwnerDocument(aNode));
            if (aResult != null && !aResult.booleanValue()) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("Ignoring validation artefact " + aArtefact.getRuleResourcePath() + " because the prerequisite XPath expression '" + m_sPrerequisiteXPath + "' is not fulfilled.");
                return ValidationResult.createIgnoredResult(aArtefact);
            }
        } catch (final IllegalArgumentException ex) {
            // Catch errors in prerequisite XPaths - most likely because of
            // missing namespace prefixes...
            final String sErrorMsg = "Failed to verify if validation artefact " + aArtefact.getRuleResourcePath() + " matches the prerequisite XPath expression '" + m_sPrerequisiteXPath + "' - ignoring validation artefact.";
            LOGGER.error(sErrorMsg, ex);
            return new ValidationResult(aArtefact, new ErrorList(SingleError.builderError().errorText(sErrorMsg).linkedException(ex).build()));
        }
    }
    // No prerequisite or prerequisite matched
    final ErrorList aErrorList = new ErrorList();
    final Wrapper<ESchematronOutput> aOutput = new Wrapper<>(ESchematronOutput.SVRL);
    final AbstractSchematronResource aSCH = _createSchematronResource(aLocale, aErrorList, aOutput::set);
    // Don't cache to avoid that errors in the Schematron are hidden on
    // consecutive calls!
    aSCH.setUseCache(m_bCacheSchematron);
    try {
        // Main application of Schematron
        final Document aDoc = aSCH.applySchematronValidation(new DOMSource(aNode));
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("SVRL: " + XMLWriter.getNodeAsString(aDoc));
        switch(aOutput.get()) {
            case SVRL:
                {
                    final SchematronOutputType aSVRL = aDoc == null || aDoc.getDocumentElement() == null ? null : new SVRLMarshaller().read(aDoc);
                    if (aSVRL != null) {
                        // Convert failed asserts and successful reports to error objects
                        for (final SVRLFailedAssert aFailedAssert : SVRLHelper.getAllFailedAssertions(aSVRL)) aErrorList.add(aFailedAssert.getAsResourceError(aSource.getSystemID()));
                        for (final SVRLSuccessfulReport aSuccessfulReport : SVRLHelper.getAllSuccessfulReports(aSVRL)) aErrorList.add(aSuccessfulReport.getAsResourceError(aSource.getSystemID()));
                    } else {
                        // Schematron does not create SVRL!
                        LOGGER.warn("Failed to read the result as SVRL:" + (aDoc != null ? "\n" + XMLWriter.getNodeAsString(aDoc) : " no XML Document created"));
                        aErrorList.add(SingleError.builderError().errorLocation(aArtefact.getRuleResourcePath()).errorText("Internal error interpreting Schematron result").errorFieldName(aDoc != null ? XMLWriter.getNodeAsString(aDoc) : null).build());
                    }
                    break;
                }
            case OIOUBL:
                {
                    if (aDoc != null && aDoc.getDocumentElement() != null) {
                        for (final Element eError : XMLHelper.getChildElementIterator(aDoc.getDocumentElement(), "Error")) {
                            // final String sContext = eError.getAttribute ("context");
                            final String sPattern = XMLHelper.getFirstChildElementOfName(eError, "Pattern").getTextContent();
                            final String sDescription = XMLHelper.getFirstChildElementOfName(eError, "Description").getTextContent();
                            final String sXPath = XMLHelper.getFirstChildElementOfName(eError, "Xpath").getTextContent();
                            aErrorList.add(new SVRLErrorBuilder(sPattern).errorLocation(new SimpleLocation(aSource.getSystemID())).errorText(sDescription).errorFieldName(sXPath).build());
                        }
                    } else {
                        // Schematron does not create SVRL!
                        LOGGER.warn("Failed to read the result as OIOUBL result:" + (aDoc != null ? "\n" + XMLWriter.getNodeAsString(aDoc) : " no XML Document created"));
                        aErrorList.add(SingleError.builderError().errorLocation(aArtefact.getRuleResourcePath()).errorText("Internal error - no Schematron output created for OIOUBL").build());
                    }
                    break;
                }
            default:
                throw new IllegalStateException("Unsupported output type");
        }
    } catch (final Exception ex) {
        // Usually an error in the Schematron
        aErrorList.add(SingleError.builderError().errorLocation(aArtefact.getRuleResourcePath()).errorText(ex.getMessage()).linkedException(ex).build());
    }
    // Apply custom levels
    if (m_aCustomErrorLevels != null && aErrorList.isNotEmpty()) {
        final ErrorList aOldErrorList = aErrorList.getClone();
        aErrorList.clear();
        for (final IError aCurError : aOldErrorList) {
            final String sErrorID = aCurError.getErrorID();
            final IErrorLevel aCustomLevel = m_aCustomErrorLevels.get(sErrorID);
            if (aCustomLevel != null) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Changing error level of '" + sErrorID + "' from " + aCurError.getErrorLevel().getNumericLevel() + " to " + aCustomLevel + " (" + aCustomLevel.getNumericLevel() + ")");
                aErrorList.add(SingleError.builder(aCurError).errorLevel(aCustomLevel).build());
            } else {
                // No change
                aErrorList.add(aCurError);
            }
        }
    }
    return new ValidationResult(aArtefact, aErrorList);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) SVRLFailedAssert(com.helger.schematron.svrl.SVRLFailedAssert) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) ValidationResult(com.helger.phive.api.result.ValidationResult) Document(org.w3c.dom.Document) SVRLSuccessfulReport(com.helger.schematron.svrl.SVRLSuccessfulReport) SimpleLocation(com.helger.commons.location.SimpleLocation) DOMReaderSettings(com.helger.xml.serialize.read.DOMReaderSettings) XPath(javax.xml.xpath.XPath) Wrapper(com.helger.commons.wrapper.Wrapper) IValidationArtefact(com.helger.phive.api.artefact.IValidationArtefact) AbstractSchematronResource(com.helger.schematron.AbstractSchematronResource) IError(com.helger.commons.error.IError) SchematronOutputType(com.helger.schematron.svrl.jaxb.SchematronOutputType) ErrorList(com.helger.commons.error.list.ErrorList) IErrorLevel(com.helger.commons.error.level.IErrorLevel) SVRLErrorBuilder(com.helger.schematron.svrl.SVRLResourceError.SVRLErrorBuilder) Nonnull(javax.annotation.Nonnull)

Example 8 with ValidationResult

use of com.helger.phive.api.result.ValidationResult in project phive by phax.

the class ValidationExecutionManager method executeValidation.

public void executeValidation(@Nonnull final SOURCETYPE aSource, @Nonnull final ValidationResultList aValidationResults, @Nullable final Locale aLocale) {
    ValueEnforcer.notNull(aSource, "Source");
    ValueEnforcer.notNull(aValidationResults, "ValidationResults");
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Executing validation on source " + aSource + (aLocale == null ? "" : " and locale " + aLocale));
    boolean bIgnoreRest = false;
    for (final IValidationExecutor<SOURCETYPE> aExecutor : getAllExecutors()) {
        if (bIgnoreRest) {
            // Ignore executor because of previous failures
            aValidationResults.add(ValidationResult.createIgnoredResult(aExecutor.getValidationArtefact()));
        } else {
            // Execute validation
            final ValidationResult aResult = aExecutor.applyValidation(aSource, aLocale);
            assert aResult != null;
            aValidationResults.add(aResult);
            if (aResult.isFailure() && aExecutor.isStopValidationOnError()) {
                // Ignore all following executors
                bIgnoreRest = true;
            }
        }
    }
}
Also used : ValidationResult(com.helger.phive.api.result.ValidationResult)

Example 9 with ValidationResult

use of com.helger.phive.api.result.ValidationResult in project en16931-cii2ubl by phax.

the class CIIToUBL22ConverterTest method testConvertAndValidateAll.

@Test
public void testConvertAndValidateAll() {
    final String sBasePath = MockSettings.getBaseDir().getAbsolutePath();
    for (final File aFile : MockSettings.getAllTestFiles()) {
        LOGGER.info("Converting " + aFile.toString() + " to UBL 2.2");
        // Main conversion
        final ErrorList aErrorList = new ErrorList();
        final Serializable aInvoice = new CIIToUBL22Converter().convertCIItoUBL(aFile, aErrorList);
        assertTrue("Errors: " + aErrorList.toString(), aErrorList.isEmpty());
        assertNotNull(aInvoice);
        final File aDestFile = new File("toubl22/" + aFile.getParentFile().getAbsolutePath().substring(sBasePath.length()), FilenameHelper.getBaseName(aFile.getName()) + "-ubl.xml");
        final ValidationResultList aResultList;
        if (aInvoice instanceof InvoiceType) {
            final InvoiceType aUBLInvoice = (InvoiceType) aInvoice;
            // Check UBL XSD scheme
            final UBL22WriterBuilder<InvoiceType> aWriter = UBL22Writer.invoice().setFormattedOutput(true);
            aWriter.write(aUBLInvoice, aDestFile);
            // Validate against EN16931 validation rules
            aResultList = ValidationExecutionManager.executeValidation(MockSettings.VES_REGISTRY.getOfID(EN16931Validation.VID_UBL_INVOICE_137), ValidationSourceXML.create(new FileSystemResource(aDestFile)));
        } else {
            final CreditNoteType aUBLInvoice = (CreditNoteType) aInvoice;
            // Check UBL XSD scheme
            final UBL22WriterBuilder<CreditNoteType> aWriter = UBL22Writer.creditNote().setFormattedOutput(true);
            aWriter.write(aUBLInvoice, aDestFile);
            // Validate against EN16931 validation rules
            aResultList = ValidationExecutionManager.executeValidation(MockSettings.VES_REGISTRY.getOfID(EN16931Validation.VID_UBL_CREDIT_NOTE_137), ValidationSourceXML.create(new FileSystemResource(aDestFile)));
        }
        assertNotNull(aResultList);
        // Check that no errors (but maybe warnings) are contained
        for (final ValidationResult aResult : aResultList) {
            assertTrue("Errors: " + aResult.getErrorList().toString(), aResult.getErrorList().isEmpty());
        }
    }
}
Also used : Serializable(java.io.Serializable) ErrorList(com.helger.commons.error.list.ErrorList) ValidationResultList(com.helger.phive.api.result.ValidationResultList) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) ValidationResult(com.helger.phive.api.result.ValidationResult) File(java.io.File) CreditNoteType(oasis.names.specification.ubl.schema.xsd.creditnote_22.CreditNoteType) CrossIndustryInvoiceType(un.unece.uncefact.data.standard.crossindustryinvoice._100.CrossIndustryInvoiceType) InvoiceType(oasis.names.specification.ubl.schema.xsd.invoice_22.InvoiceType) Test(org.junit.Test)

Aggregations

ValidationResult (com.helger.phive.api.result.ValidationResult)9 ErrorList (com.helger.commons.error.list.ErrorList)7 ValidationResultList (com.helger.phive.api.result.ValidationResultList)4 IError (com.helger.commons.error.IError)3 FileSystemResource (com.helger.commons.io.resource.FileSystemResource)3 IValidationArtefact (com.helger.phive.api.artefact.IValidationArtefact)3 File (java.io.File)3 Serializable (java.io.Serializable)3 Nonnull (javax.annotation.Nonnull)3 Test (org.junit.Test)3 CrossIndustryInvoiceType (un.unece.uncefact.data.standard.crossindustryinvoice._100.CrossIndustryInvoiceType)3 IErrorLevel (com.helger.commons.error.level.IErrorLevel)2 SimpleLocation (com.helger.commons.location.SimpleLocation)2 IJsonArray (com.helger.json.IJsonArray)2 IJsonObject (com.helger.json.IJsonObject)2 Schema (javax.xml.validation.Schema)2 SAXParseException (org.xml.sax.SAXParseException)2 IReadableResource (com.helger.commons.io.resource.IReadableResource)1 ETriState (com.helger.commons.state.ETriState)1 Wrapper (com.helger.commons.wrapper.Wrapper)1