Search in sources :

Example 1 with ValidationResult

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

the class JsonValidationResultListHelper method applyTo.

/**
 * Apply the results of a full validation onto a JSON object.The layout of the
 * response object is very similar to the one created by
 * {@link PhiveJsonHelper#applyGlobalError(IJsonObject, String, long)}.<br>
 *
 * <pre>
 * {
 *   "ves" : object as defined by {@link PhiveJsonHelper#getJsonVES(IValidationExecutorSet)}
 *   "success" : boolean,
 *   "interrupted" : boolean,
 *   "mostSevereErrorLevel" : string,
 *   "results" : array {
 *     "success" : string,  // as defined by {@link PhiveJsonHelper#getJsonTriState(ETriState)}
 *     "artifactType" : string,
 *     "artifactPathType" : string?,
 *     "artifactPath" : string,
 *     "items" : array {
 *       error structure as in {@link PhiveJsonHelper#getJsonError(IError, Locale)}
 *     }
 *   },
 *   "durationMS" : number
 * }
 * </pre>
 *
 * @param aResponse
 *        The response JSON object to add to. May not be <code>null</code>.
 * @param aValidationResultList
 *        The validation result list containing the validation results per
 *        layer. May not be <code>null</code>.
 * @param aDisplayLocale
 *        The display locale to be used. May not be <code>null</code>.
 * @param nDurationMilliseconds
 *        The duration of the validation in milliseconds. Must be &ge; 0.
 */
public void applyTo(@Nonnull final IJsonObject aResponse, @Nonnull final List<? extends ValidationResult> aValidationResultList, @Nonnull final Locale aDisplayLocale, @Nonnegative final long nDurationMilliseconds) {
    ValueEnforcer.notNull(aResponse, "Response");
    ValueEnforcer.notNull(aValidationResultList, "ValidationResultList");
    ValueEnforcer.notNull(aDisplayLocale, "DisplayLocale");
    ValueEnforcer.isGE0(nDurationMilliseconds, "DurationMilliseconds");
    if (m_aVES != null && m_aVESToJson != null)
        aResponse.addIfNotNull(PhiveJsonHelper.JSON_VES, m_aVESToJson.apply(m_aVES));
    int nWarnings = 0;
    int nErrors = 0;
    boolean bValidationInterrupted = false;
    IErrorLevel aMostSevere = EErrorLevel.LOWEST;
    final IJsonArray aResultArray = new JsonArray();
    for (final ValidationResult aVR : aValidationResultList) {
        final IJsonObject aVRT = new JsonObject();
        if (aVR.isIgnored()) {
            bValidationInterrupted = true;
            aVRT.add(PhiveJsonHelper.JSON_SUCCESS, PhiveJsonHelper.getJsonTriState(ETriState.UNDEFINED));
        } else {
            aVRT.add(PhiveJsonHelper.JSON_SUCCESS, PhiveJsonHelper.getJsonTriState(aVR.isSuccess()));
        }
        aVRT.add(PhiveJsonHelper.JSON_ARTIFACT_TYPE, aVR.getValidationArtefact().getValidationArtefactType().getID());
        if (m_aArtifactPathTypeToJson != null)
            aVRT.addIfNotNull(PhiveJsonHelper.JSON_ARTIFACT_PATH_TYPE, m_aArtifactPathTypeToJson.apply(aVR.getValidationArtefact().getRuleResource()));
        aVRT.add(PhiveJsonHelper.JSON_ARTIFACT_PATH, aVR.getValidationArtefact().getRuleResourcePath());
        final IJsonArray aItemArray = new JsonArray();
        for (final IError aError : aVR.getErrorList()) {
            if (aError.getErrorLevel().isGT(aMostSevere))
                aMostSevere = aError.getErrorLevel();
            if (PhiveJsonHelper.isConsideredError(aError.getErrorLevel()))
                nErrors++;
            else if (PhiveJsonHelper.isConsideredWarning(aError.getErrorLevel()))
                nWarnings++;
            if (m_aErrorToJson != null)
                aItemArray.add(m_aErrorToJson.apply(aError, aDisplayLocale));
        }
        aVRT.addJson(PhiveJsonHelper.JSON_ITEMS, aItemArray);
        aResultArray.add(aVRT);
    }
    // Success if the worst that happened is a warning
    aResponse.add(PhiveJsonHelper.JSON_SUCCESS, aMostSevere.isLE(EErrorLevel.WARN));
    aResponse.add(PhiveJsonHelper.JSON_INTERRUPTED, bValidationInterrupted);
    if (m_aErrorLevelToJson != null)
        aResponse.addIfNotNull(PhiveJsonHelper.JSON_MOST_SEVERE_ERROR_LEVEL, m_aErrorLevelToJson.apply(aMostSevere));
    aResponse.addJson(PhiveJsonHelper.JSON_RESULTS, aResultArray);
    aResponse.add(PhiveJsonHelper.JSON_DURATION_MS, nDurationMilliseconds);
    // Set consumer values
    if (m_aWarningCount != null)
        m_aWarningCount.set(nWarnings);
    if (m_aErrorCount != null)
        m_aErrorCount.set(nErrors);
}
Also used : JsonArray(com.helger.json.JsonArray) IJsonArray(com.helger.json.IJsonArray) IJsonObject(com.helger.json.IJsonObject) IErrorLevel(com.helger.commons.error.level.IErrorLevel) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IJsonArray(com.helger.json.IJsonArray) ValidationResult(com.helger.phive.api.result.ValidationResult) IError(com.helger.commons.error.IError)

Example 2 with ValidationResult

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

the class PhiveJsonHelper method getAsValidationResultList.

/**
 * Try to parse a JSON structure and convert it back to a
 * {@link ValidationResultList}.
 *
 * @param aJson
 *        The JSON to be read. May be <code>null</code>.
 * @param aValidationTypeResolver
 *        The validation type resolver to be used. May not be
 *        <code>null</code>.
 * @return <code>null</code> in case reverse operation fails.
 */
@Nullable
public static ValidationResultList getAsValidationResultList(@Nullable final IJsonObject aJson, @Nonnull final Function<String, IValidationType> aValidationTypeResolver) {
    ValueEnforcer.notNull(aValidationTypeResolver, "ValidationTypeResolver");
    if (aJson == null)
        return null;
    final IJsonArray aResults = aJson.getAsArray(JSON_RESULTS);
    if (aResults == null)
        return null;
    final ValidationResultList ret = new ValidationResultList();
    for (final IJson aResult : aResults) {
        final IJsonObject aResultObj = aResult.getAsObject();
        if (aResultObj != null) {
            final String sSuccess = aResultObj.getAsString(JSON_SUCCESS);
            final ETriState eSuccess = getAsTriState(sSuccess);
            if (eSuccess == null) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Failed to resolve TriState '" + sSuccess + "'");
                continue;
            }
            final String sValidationType = aResultObj.getAsString(JSON_ARTIFACT_TYPE);
            final IValidationType aValidationType = aValidationTypeResolver.apply(sValidationType);
            if (aValidationType == null) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Failed to resolve ValidationType '" + sValidationType + "'");
                continue;
            }
            final String sArtefactPathType = aResultObj.getAsString(JSON_ARTIFACT_PATH_TYPE);
            final String sArtefactPath = aResultObj.getAsString(JSON_ARTIFACT_PATH);
            final IReadableResource aRes = getAsValidationResource(sArtefactPathType, sArtefactPath);
            if (aRes == null) {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Failed to resolve ValidationArtefact '" + sArtefactPathType + "' with path '" + sArtefactPath + "'");
                continue;
            }
            final ValidationArtefact aVA = new ValidationArtefact(aValidationType, aRes);
            if (eSuccess.isUndefined()) {
                // Ignored level
                ret.add(ValidationResult.createIgnoredResult(aVA));
            } else {
                // We have results
                final IJsonArray aItems = aResultObj.getAsArray(JSON_ITEMS);
                final ErrorList aErrorList = new ErrorList();
                for (final IJson aItem : aItems) {
                    final IJsonObject aItemObj = aItem.getAsObject();
                    if (aItemObj != null) {
                        final IError aError = getAsIError(aItemObj);
                        aErrorList.add(aError);
                    }
                }
                final ValidationResult aVR = new ValidationResult(aVA, aErrorList);
                ret.add(aVR);
            }
        }
    }
    return ret;
}
Also used : IValidationType(com.helger.phive.api.IValidationType) ETriState(com.helger.commons.state.ETriState) ErrorList(com.helger.commons.error.list.ErrorList) IJsonObject(com.helger.json.IJsonObject) ValidationResultList(com.helger.phive.api.result.ValidationResultList) IReadableResource(com.helger.commons.io.resource.IReadableResource) ValidationArtefact(com.helger.phive.api.artefact.ValidationArtefact) IJson(com.helger.json.IJson) IJsonArray(com.helger.json.IJsonArray) IError(com.helger.commons.error.IError) ValidationResult(com.helger.phive.api.result.ValidationResult) Nullable(javax.annotation.Nullable)

Example 3 with ValidationResult

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

the class ValidationExecutorXSD method applyValidation.

@Nonnull
public ValidationResult applyValidation(@Nonnull final IValidationSourceXML aSource, @Nullable final Locale aLocale) {
    ValueEnforcer.notNull(aSource, "Source");
    final IValidationArtefact aVA = getValidationArtefact();
    // Find the XML schema required for validation
    // as we don't have a node, we need to trust the implementation class
    final Schema aSchema = m_aSchemaProvider.get();
    assert aSchema != null;
    final ErrorList aErrorList = new ErrorList();
    try {
        // Apply the XML schema validation
        XMLSchemaValidationHelper.validate(aSchema, aSource.getAsTransformSource(), aErrorList, aLocale);
    } catch (final IllegalArgumentException ex) {
        // Happens when non-XML document is trying to be parsed
        if (ex.getCause() instanceof SAXParseException) {
            aErrorList.add(AbstractSAXErrorHandler.getSaxParseError(EErrorLevel.FATAL_ERROR, (SAXParseException) ex.getCause()));
        } else {
            aErrorList.add(SingleError.builderFatalError().errorLocation(new SimpleLocation(aVA.getRuleResourcePath())).errorText("The document to be validated is not an XML document").linkedException(ex).build());
        }
    }
    // Build result object
    return new ValidationResult(aVA, aErrorList.getAllFailures());
}
Also used : ErrorList(com.helger.commons.error.list.ErrorList) IValidationArtefact(com.helger.phive.api.artefact.IValidationArtefact) SAXParseException(org.xml.sax.SAXParseException) Schema(javax.xml.validation.Schema) SimpleLocation(com.helger.commons.location.SimpleLocation) ValidationResult(com.helger.phive.api.result.ValidationResult) Nonnull(javax.annotation.Nonnull)

Example 4 with ValidationResult

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

the class ValidationExecutorXSDPartial method applyValidation.

@Nonnull
public ValidationResult applyValidation(@Nonnull final IValidationSourceXML aSource, @Nullable final Locale aLocale) {
    ValueEnforcer.notNull(aSource, "Source");
    final IValidationArtefact aVA = getValidationArtefact();
    NodeList aNodeSet;
    try {
        aNodeSet = (NodeList) m_aPartialContext.getXPathExpression().evaluate(aSource.getNode(), XPathConstants.NODESET);
    } catch (final XPathExpressionException ex) {
        throw new IllegalStateException(ex);
    }
    final ErrorList aErrorList = new ErrorList();
    final int nMatchingNodes = aNodeSet.getLength();
    if (m_aPartialContext.hasMinNodeCount())
        if (nMatchingNodes < m_aPartialContext.getMinNodeCount()) {
            // Too little matches found
            aErrorList.add(SingleError.builderFatalError().errorLocation(aVA.getRuleResourcePath()).errorText("The minimum number of result nodes (" + m_aPartialContext.getMinNodeCount() + ") is not met").build());
        }
    if (m_aPartialContext.hasMaxNodeCount())
        if (nMatchingNodes > m_aPartialContext.getMaxNodeCount()) {
            // Too little matches found
            aErrorList.add(SingleError.builderFatalError().errorLocation(aVA.getRuleResourcePath()).errorText("The maximum number of result nodes (" + m_aPartialContext.getMaxNodeCount() + ") is not met").build());
        }
    if (nMatchingNodes == 0) {
        // No match found - nothing to do
        return new ValidationResult(aVA, aErrorList);
    }
    // Find the XML schema required for validation
    // as we don't have a node, we need to trust the implementation class
    final Schema aSchema = m_aSchemaProvider.get();
    assert aSchema != null;
    for (int i = 0; i < aNodeSet.getLength(); ++i) {
        // Build a partial source
        final IValidationSourceXML aRealSource = new ValidationSourceXML(aSource.getSystemID(), aNodeSet.item(i), true);
        try {
            // Apply the XML schema validation
            XMLSchemaValidationHelper.validate(aSchema, aRealSource.getAsTransformSource(), aErrorList, aLocale);
        } catch (final IllegalArgumentException ex) {
            // Happens when non-XML document is trying to be parsed
            if (ex.getCause() instanceof SAXParseException) {
                aErrorList.add(AbstractSAXErrorHandler.getSaxParseError(EErrorLevel.FATAL_ERROR, (SAXParseException) ex.getCause()));
            } else {
                aErrorList.add(SingleError.builderFatalError().errorLocation(aVA.getRuleResourcePath()).errorFieldName("Context[" + i + "]").errorText("The document to be validated is not an XML document").linkedException(ex).build());
            }
        }
    }
    // Build result object
    return new ValidationResult(aVA, aErrorList.getAllFailures());
}
Also used : ErrorList(com.helger.commons.error.list.ErrorList) IValidationArtefact(com.helger.phive.api.artefact.IValidationArtefact) XPathExpressionException(javax.xml.xpath.XPathExpressionException) SAXParseException(org.xml.sax.SAXParseException) NodeList(org.w3c.dom.NodeList) Schema(javax.xml.validation.Schema) ValidationSourceXML(com.helger.phive.engine.source.ValidationSourceXML) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) ValidationResult(com.helger.phive.api.result.ValidationResult) Nonnull(javax.annotation.Nonnull)

Example 5 with ValidationResult

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

the class CIIToUBL21ConverterTest 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.1");
        // Main conversion
        final ErrorList aErrorList = new ErrorList();
        final Serializable aInvoice = new CIIToUBL21Converter().convertCIItoUBL(aFile, aErrorList);
        assertTrue("Errors: " + aErrorList.toString(), aErrorList.isEmpty());
        assertNotNull(aInvoice);
        final File aDestFile = new File("toubl21/" + 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 UBL21WriterBuilder<InvoiceType> aWriter = UBL21Writer.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 UBL21WriterBuilder<CreditNoteType> aWriter = UBL21Writer.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_21.CreditNoteType) CrossIndustryInvoiceType(un.unece.uncefact.data.standard.crossindustryinvoice._100.CrossIndustryInvoiceType) InvoiceType(oasis.names.specification.ubl.schema.xsd.invoice_21.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