Search in sources :

Example 1 with IErrorLevel

use of com.helger.commons.error.level.IErrorLevel in project ph-schematron by phax.

the class Schematron method execute.

@Override
public void execute() throws BuildException {
    boolean bCanRun = false;
    if (m_aSchematronFile == null)
        _errorOrFail("No Schematron file specified!");
    else if (m_aSchematronFile.exists() && !m_aSchematronFile.isFile())
        _errorOrFail("The specified Schematron file " + m_aSchematronFile + " is not a file!");
    else if (m_eSchematronProcessingEngine == null)
        _errorOrFail("An invalid Schematron processing instance is specified! Only one of the following values is allowed: " + StringHelper.getImplodedMapped(", ", ESchematronMode.values(), x -> "'" + x.getID() + "'"));
    else if (m_aResCollections.isEmpty())
        _errorOrFail("No XML resources to be validated specified! Add e.g. a <fileset> element.");
    else if (m_aSvrlDirectory != null && !m_aSvrlDirectory.exists() && !m_aSvrlDirectory.mkdirs())
        _errorOrFail("Failed to create the SVRL directory " + m_aSvrlDirectory);
    else
        bCanRun = true;
    if (bCanRun) {
        // Set error level
        if (m_aErrorRoles.isNotEmpty()) {
            // Set global default error level determinator
            SVRLHelper.setErrorLevelDeterminator(new DefaultSVRLErrorLevelDeterminator() {

                @Override
                @Nonnull
                public IErrorLevel getErrorLevelFromString(@Nullable final String sFlag) {
                    if (sFlag != null) {
                        // Check custom error roles; #66
                        for (final Schematron.ErrorRole aCustomRole : m_aErrorRoles) if (aCustomRole.equalsIgnoreCase(sFlag))
                            return EErrorLevel.ERROR;
                    }
                    // Fall back to default
                    return super.getErrorLevelFromString(sFlag);
                }
            });
        }
        // 1. Parse Schematron file
        final Locale aDisplayLocale = Locale.US;
        ISchematronResource aSch = null;
        IErrorList aSCHErrors = null;
        switch(m_eSchematronProcessingEngine) {
            case PURE:
                {
                    // pure
                    final CollectingPSErrorHandler aErrorHdl = new CollectingPSErrorHandler();
                    final SchematronResourcePure aRealSCH = new SchematronResourcePure(new FileSystemResource(m_aSchematronFile));
                    aRealSCH.setPhase(m_sPhaseName);
                    aRealSCH.setErrorHandler(aErrorHdl);
                    aRealSCH.setEntityResolver(getEntityResolver());
                    aRealSCH.validateCompletely();
                    aSch = aRealSCH;
                    aSCHErrors = aErrorHdl.getAllErrors();
                    break;
                }
            case SCHEMATRON:
                {
                    // SCH
                    final IStringMap aParams = new StringMap();
                    m_aParameters.forEach(x -> x.addToMap(aParams));
                    if (aParams.isNotEmpty())
                        _info("Using the following custom parameters: " + aParams);
                    final CollectingTransformErrorListener aErrorHdl = new CollectingTransformErrorListener();
                    final SchematronResourceSCH aRealSCH = new SchematronResourceSCH(new FileSystemResource(m_aSchematronFile));
                    aRealSCH.setPhase(m_sPhaseName);
                    aRealSCH.setLanguageCode(m_sLanguageCode);
                    aRealSCH.setForceCacheResult(m_bForceCacheResult);
                    aRealSCH.setErrorListener(aErrorHdl);
                    aRealSCH.setURIResolver(getURIResolver());
                    aRealSCH.setEntityResolver(getEntityResolver());
                    aRealSCH.parameters().setAll(aParams);
                    aRealSCH.isValidSchematron();
                    aSch = aRealSCH;
                    aSCHErrors = aErrorHdl.getErrorList();
                    break;
                }
            case SCHXSLT_XSLT2:
                {
                    // SchXslt
                    final IStringMap aParams = new StringMap();
                    m_aParameters.forEach(x -> x.addToMap(aParams));
                    if (aParams.isNotEmpty())
                        _info("Using the following custom parameters: " + aParams);
                    final CollectingTransformErrorListener aErrorHdl = new CollectingTransformErrorListener();
                    final SchematronResourceSchXslt_XSLT2 aRealSCH = new SchematronResourceSchXslt_XSLT2(new FileSystemResource(m_aSchematronFile));
                    aRealSCH.setPhase(m_sPhaseName);
                    aRealSCH.setLanguageCode(m_sLanguageCode);
                    aRealSCH.setForceCacheResult(m_bForceCacheResult);
                    aRealSCH.setErrorListener(aErrorHdl);
                    aRealSCH.setURIResolver(getURIResolver());
                    aRealSCH.setEntityResolver(getEntityResolver());
                    aRealSCH.parameters().setAll(aParams);
                    aRealSCH.isValidSchematron();
                    aSch = aRealSCH;
                    aSCHErrors = aErrorHdl.getErrorList();
                    break;
                }
            case XSLT:
                {
                    // XSLT
                    final IStringMap aParams = new StringMap();
                    m_aParameters.forEach(x -> x.addToMap(aParams));
                    if (aParams.isNotEmpty())
                        _info("Using the following custom parameters: " + aParams);
                    final CollectingTransformErrorListener aErrorHdl = new CollectingTransformErrorListener();
                    final SchematronResourceXSLT aRealSCH = new SchematronResourceXSLT(new FileSystemResource(m_aSchematronFile));
                    // phase and language are ignored because this was decided when the
                    // XSLT was created
                    aRealSCH.setErrorListener(aErrorHdl);
                    aRealSCH.setURIResolver(getURIResolver());
                    aRealSCH.setEntityResolver(getEntityResolver());
                    aRealSCH.parameters().setAll(aParams);
                    aRealSCH.isValidSchematron();
                    aSch = aRealSCH;
                    aSCHErrors = aErrorHdl.getErrorList();
                    break;
                }
            default:
                _errorOrFail("No handler for processing engine '" + m_eSchematronProcessingEngine + "'");
                break;
        }
        boolean bAnyParsingError = false;
        if (aSCHErrors != null)
            // Error validating the Schematrons!!
            for (final IError aError : aSCHErrors) if (aError.getErrorLevel().isGE(EErrorLevel.ERROR)) {
                _error("Error in Schematron: " + aError.getAsString(aDisplayLocale));
                bAnyParsingError = true;
            } else if (aError.getErrorLevel().isGE(EErrorLevel.WARN))
                _warn("Warning in Schematron: " + aError.getAsString(aDisplayLocale));
            else
                _info("Information in Schematron: " + aError.getAsString(aDisplayLocale));
        if (bAnyParsingError)
            _errorOrFail("The provided Schematron file contains errors. See log for details.");
        else {
            // Schematron is okay
            _info("Successfully parsed Schematron file '" + m_aSchematronFile.getPath() + "'");
            // Start validation
            _performValidation(aSch, m_aResCollections, m_aSvrlDirectory, m_bExpectSuccess);
        }
    }
}
Also used : FileResource(org.apache.tools.ant.types.resources.FileResource) SchematronResourceXSLT(com.helger.schematron.xslt.SchematronResourceXSLT) ESchematronMode(com.helger.schematron.ESchematronMode) Locale(java.util.Locale) Map(java.util.Map) TransformSourceFactory(com.helger.xml.transform.TransformSourceFactory) EntityResolver(org.xml.sax.EntityResolver) ErrorTextProvider(com.helger.commons.error.ErrorTextProvider) DefaultSVRLErrorLevelDeterminator(com.helger.schematron.svrl.DefaultSVRLErrorLevelDeterminator) Resource(org.apache.tools.ant.types.Resource) SVRLMarshaller(com.helger.schematron.svrl.SVRLMarshaller) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) SVRLResourceError(com.helger.schematron.svrl.SVRLResourceError) Serializable(java.io.Serializable) ISchematronResource(com.helger.schematron.ISchematronResource) SchematronResourceSchXslt_XSLT2(com.helger.schematron.schxslt.xslt2.SchematronResourceSchXslt_XSLT2) ICommonsList(com.helger.commons.collection.impl.ICommonsList) FileProvider(org.apache.tools.ant.types.resources.FileProvider) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) IErrorList(com.helger.commons.error.list.IErrorList) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) OverrideOnDemand(com.helger.commons.annotation.OverrideOnDemand) SchematronResourceSCH(com.helger.schematron.sch.SchematronResourceSCH) IError(com.helger.commons.error.IError) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) URIResolver(javax.xml.transform.URIResolver) UsedViaReflection(com.helger.commons.annotation.UsedViaReflection) ResourceCollection(org.apache.tools.ant.types.ResourceCollection) StringMap(com.helger.commons.collection.attr.StringMap) AbstractSVRLMessage(com.helger.schematron.svrl.AbstractSVRLMessage) TransformerCustomizerSCH(com.helger.schematron.sch.TransformerCustomizerSCH) SVRLHelper(com.helger.schematron.svrl.SVRLHelper) IErrorLevel(com.helger.commons.error.level.IErrorLevel) CollectingTransformErrorListener(com.helger.xml.transform.CollectingTransformErrorListener) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) SVRLNamespaceContext(com.helger.schematron.svrl.SVRLNamespaceContext) EErrorLevel(com.helger.commons.error.level.EErrorLevel) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) FileOperations(com.helger.commons.io.file.FileOperations) StringHelper(com.helger.commons.string.StringHelper) CollectingPSErrorHandler(com.helger.schematron.pure.errorhandler.CollectingPSErrorHandler) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) XMLCatalog(org.apache.tools.ant.types.XMLCatalog) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) SchematronOutputType(com.helger.schematron.svrl.jaxb.SchematronOutputType) IStringMap(com.helger.commons.collection.attr.IStringMap) SchematronResourcePure(com.helger.schematron.pure.SchematronResourcePure) ResourceUtils(org.apache.tools.ant.util.ResourceUtils) Locale(java.util.Locale) StringMap(com.helger.commons.collection.attr.StringMap) IStringMap(com.helger.commons.collection.attr.IStringMap) ISchematronResource(com.helger.schematron.ISchematronResource) Nonnull(javax.annotation.Nonnull) FileSystemResource(com.helger.commons.io.resource.FileSystemResource) CollectingTransformErrorListener(com.helger.xml.transform.CollectingTransformErrorListener) IError(com.helger.commons.error.IError) SchematronResourceXSLT(com.helger.schematron.xslt.SchematronResourceXSLT) SchematronResourceSCH(com.helger.schematron.sch.SchematronResourceSCH) SchematronResourceSchXslt_XSLT2(com.helger.schematron.schxslt.xslt2.SchematronResourceSchXslt_XSLT2) IStringMap(com.helger.commons.collection.attr.IStringMap) IErrorLevel(com.helger.commons.error.level.IErrorLevel) IErrorList(com.helger.commons.error.list.IErrorList) DefaultSVRLErrorLevelDeterminator(com.helger.schematron.svrl.DefaultSVRLErrorLevelDeterminator) SchematronResourcePure(com.helger.schematron.pure.SchematronResourcePure) CollectingPSErrorHandler(com.helger.schematron.pure.errorhandler.CollectingPSErrorHandler)

Example 2 with IErrorLevel

use of com.helger.commons.error.level.IErrorLevel 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 3 with IErrorLevel

use of com.helger.commons.error.level.IErrorLevel in project phoss-smp by phax.

the class PageSecureServiceGroupImport method fillContent.

@Override
protected void fillContent(@Nonnull final WebPageExecutionContext aWPEC) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final ISMPSettings aSettings = SMPMetaManager.getSettings();
    final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
    final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
    final IUserManager aUserMgr = PhotonSecurityManager.getUserMgr();
    final ICommonsSet<String> aAllServiceGroupIDs = aServiceGroupMgr.getAllSMPServiceGroupIDs();
    final ICommonsSet<String> aAllBusinessCardIDs = aBusinessCardMgr.getAllSMPBusinessCardIDs();
    final FormErrorList aFormErrors = new FormErrorList();
    final HCUL aImportResultUL = new HCUL();
    if (aWPEC.hasAction(CPageParam.ACTION_PERFORM)) {
        // Start import
        final IFileItem aImportFile = aWPEC.params().getAsFileItem(FIELD_IMPORT_FILE);
        final boolean bOverwriteExisting = aWPEC.params().isCheckBoxChecked(FIELD_OVERWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING);
        final String sDefaultOwnerID = aWPEC.params().getAsString(FIELD_DEFAULT_OWNER);
        final IUser aDefaultOwner = aUserMgr.getActiveUserOfID(sDefaultOwnerID);
        if (aImportFile == null || aImportFile.getSize() == 0)
            aFormErrors.addFieldError(FIELD_IMPORT_FILE, "A file to import must be selected!");
        if (StringHelper.hasNoText(sDefaultOwnerID))
            aFormErrors.addFieldError(FIELD_DEFAULT_OWNER, "A default owner must be selected!");
        else if (aDefaultOwner == null)
            aFormErrors.addFieldError(FIELD_DEFAULT_OWNER, "A valid default owner must be selected!");
        if (aFormErrors.isEmpty()) {
            final SAXReaderSettings aSRS = new SAXReaderSettings();
            final IMicroDocument aDoc = MicroReader.readMicroXML(aImportFile, aSRS);
            if (aDoc == null || aDoc.getDocumentElement() == null)
                aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file is not a valid XML file!");
            else {
                // Start interpreting
                final String sVersion = aDoc.getDocumentElement().getAttributeValue(CSMPExchange.ATTR_VERSION);
                if (CSMPExchange.VERSION_10.equals(sVersion)) {
                    // Version 1.0
                    final ICommonsList<ImportActionItem> aActionList = new CommonsArrayList<>();
                    final ImportSummary aImportSummary = new ImportSummary();
                    ServiceGroupImport.importXMLVer10(aDoc.getDocumentElement(), bOverwriteExisting, aDefaultOwner, aAllServiceGroupIDs, aAllBusinessCardIDs, aActionList, aImportSummary);
                    for (final ImportActionItem aAction : aActionList) {
                        final IErrorLevel aErrorLevel = aAction.getErrorLevel();
                        final EBootstrapBadgeType eBadgeType;
                        if (aErrorLevel.isGE(EErrorLevel.ERROR))
                            eBadgeType = EBootstrapBadgeType.DANGER;
                        else if (aErrorLevel.isGE(EErrorLevel.WARN))
                            eBadgeType = EBootstrapBadgeType.WARNING;
                        else if (aErrorLevel.isGE(EErrorLevel.INFO))
                            eBadgeType = EBootstrapBadgeType.INFO;
                        else
                            eBadgeType = EBootstrapBadgeType.SUCCESS;
                        // By default is is centered
                        aImportResultUL.addItem(new BootstrapBadge(eBadgeType).addChild((aAction.hasParticipantID() ? "[" + aAction.getParticipantID() + "] " : "") + aAction.getMessage()).addChild(SMPCommonUI.getTechnicalDetailsUI(aAction.getLinkedException())).addClass(CBootstrapCSS.TEXT_LEFT));
                    }
                } else {
                    // Unsupported or no version present
                    if (sVersion == null)
                        aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file cannot be imported because it has the wrong layout.");
                    else
                        aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file contains the unsupported version '" + sVersion + "'.");
                }
            }
        }
    }
    final boolean bHandleBusinessCards = aSettings.isDirectoryIntegrationEnabled();
    if (aImportResultUL.hasChildren()) {
        final BootstrapCard aPanel = new BootstrapCard();
        aPanel.createAndAddHeader().addChild("Import results");
        aPanel.createAndAddBody().addChild(aImportResultUL);
        aNodeList.addChild(aPanel);
    }
    aNodeList.addChild(info("Import service groups incl. all endpoints" + (bHandleBusinessCards ? " and business cards" : "") + " from a file."));
    final BootstrapForm aForm = aNodeList.addAndReturnChild(getUIHandler().createFormFileUploadSelf(aWPEC));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("File to import").setCtrl(new BootstrapFileUpload(FIELD_IMPORT_FILE, aDisplayLocale)).setErrorList(aFormErrors.getListOfField(FIELD_IMPORT_FILE)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabel("Overwrite existing elements").setCtrl(new HCCheckBox(new RequestFieldBoolean(FIELD_OVERWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING))).setHelpText("If this box is checked, all existing endpoints etc. of a service group are deleted and new endpoints are created! If the " + SMPWebAppConfiguration.getDirectoryName() + " integration is enabled, existing business cards contained in the import are also overwritten!").setErrorList(aFormErrors.getListOfField(FIELD_OVERWRITE_EXISTING)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Owner of the new service groups").setCtrl(new HCUserSelect(new RequestField(FIELD_DEFAULT_OWNER), aDisplayLocale)).setHelpText("This owner is only selected, if the owner contained in the import file is unknown.").setErrorList(aFormErrors.getListOfField(FIELD_DEFAULT_OWNER)));
    final BootstrapButtonToolbar aToolbar = aForm.addAndReturnChild(getUIHandler().createToolbar(aWPEC));
    aToolbar.addHiddenField(CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM);
    aToolbar.addChild(new BootstrapSubmitButton().addChild("Import Service Groups").setIcon(EDefaultIcon.ADD));
}
Also used : Locale(java.util.Locale) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) HCNodeList(com.helger.html.hc.impl.HCNodeList) IUserManager(com.helger.photon.security.user.IUserManager) ImportSummary(com.helger.phoss.smp.exchange.ImportSummary) RequestFieldBoolean(com.helger.photon.core.form.RequestFieldBoolean) FormErrorList(com.helger.photon.core.form.FormErrorList) ImportActionItem(com.helger.phoss.smp.exchange.ImportActionItem) SAXReaderSettings(com.helger.xml.serialize.read.SAXReaderSettings) BootstrapFileUpload(com.helger.photon.bootstrap4.uictrls.ext.BootstrapFileUpload) IFileItem(com.helger.web.fileupload.IFileItem) IUser(com.helger.photon.security.user.IUser) BootstrapButtonToolbar(com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar) RequestField(com.helger.photon.core.form.RequestField) BootstrapCard(com.helger.photon.bootstrap4.card.BootstrapCard) BootstrapBadge(com.helger.photon.bootstrap4.badge.BootstrapBadge) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) HCUserSelect(com.helger.phoss.smp.ui.secure.hc.HCUserSelect) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) HCUL(com.helger.html.hc.html.grouping.HCUL) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) EBootstrapBadgeType(com.helger.photon.bootstrap4.badge.EBootstrapBadgeType) IErrorLevel(com.helger.commons.error.level.IErrorLevel) IMicroDocument(com.helger.xml.microdom.IMicroDocument) HCCheckBox(com.helger.html.hc.html.forms.HCCheckBox) BootstrapSubmitButton(com.helger.photon.bootstrap4.button.BootstrapSubmitButton) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList)

Example 4 with IErrorLevel

use of com.helger.commons.error.level.IErrorLevel 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 5 with IErrorLevel

use of com.helger.commons.error.level.IErrorLevel 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)

Aggregations

IErrorLevel (com.helger.commons.error.level.IErrorLevel)5 IError (com.helger.commons.error.IError)3 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)2 SimpleLocation (com.helger.commons.location.SimpleLocation)2 ValidationResult (com.helger.phive.api.result.ValidationResult)2 Locale (java.util.Locale)2 Nonnull (javax.annotation.Nonnull)2 OverrideOnDemand (com.helger.commons.annotation.OverrideOnDemand)1 UsedViaReflection (com.helger.commons.annotation.UsedViaReflection)1 IStringMap (com.helger.commons.collection.attr.IStringMap)1 StringMap (com.helger.commons.collection.attr.StringMap)1 CommonsHashMap (com.helger.commons.collection.impl.CommonsHashMap)1 ICommonsList (com.helger.commons.collection.impl.ICommonsList)1 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)1 ErrorTextProvider (com.helger.commons.error.ErrorTextProvider)1 SingleError (com.helger.commons.error.SingleError)1 EErrorLevel (com.helger.commons.error.level.EErrorLevel)1 ErrorList (com.helger.commons.error.list.ErrorList)1 IErrorList (com.helger.commons.error.list.IErrorList)1 ConstantHasErrorText (com.helger.commons.error.text.ConstantHasErrorText)1