Search in sources :

Example 1 with IJsonObject

use of com.helger.json.IJsonObject 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 IJsonObject

use of com.helger.json.IJsonObject 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 IJsonObject

use of com.helger.json.IJsonObject in project phive by phax.

the class PhiveJsonHelperTest method testValidationResultsBackAndForth.

@Test
public void testValidationResultsBackAndForth() {
    // Register
    final ValidationExecutorSetRegistry<IValidationSourceXML> aRegistry = new ValidationExecutorSetRegistry<>();
    final VESID aVESID = new VESID("group", "art", "1.0");
    final ValidationExecutorSet<IValidationSourceXML> aVES = new ValidationExecutorSet<>(aVESID, "name", false);
    aVES.addExecutor(ValidationExecutorXSD.create(new ClassPathResource("test/schema1.xsd")));
    aRegistry.registerValidationExecutorSet(aVES);
    // Validate
    final ValidationResultList aVRL = ValidationExecutionManager.executeValidation(aVES, ValidationSourceXML.create(new ClassPathResource("test/schema1.xml")));
    assertTrue(aVRL.containsAtLeastOneError());
    // To JSON
    final Locale aDisplayLocale = Locale.US;
    final IJsonObject aObj = new JsonObject();
    PhiveJsonHelper.applyValidationResultList(aObj, aVES, aVRL, aDisplayLocale, 123, null, null);
    // And back
    final IValidationExecutorSet<IValidationSourceXML> aVES2 = PhiveJsonHelper.getAsVES(aRegistry, aObj);
    assertNotNull(aVES2);
    assertSame(aVES, aVES2);
    final ValidationResultList aVRL2 = PhiveJsonHelper.getAsValidationResultList(aObj);
    assertNotNull(aVRL2);
    // direct equals doesn't work, because of the restored exception
    assertEquals(aVRL.size(), aVRL2.size());
    assertEquals(1, aVRL.size());
    assertEquals(aVRL.get(0).getErrorList().size(), aVRL2.get(0).getErrorList().size());
    // and forth
    final IJsonObject aObj2 = new JsonObject();
    PhiveJsonHelper.applyValidationResultList(aObj2, aVES2, aVRL2, aDisplayLocale, 123, null, null);
    CommonsTestHelper.testDefaultImplementationWithEqualContentObject(aObj, aObj2);
}
Also used : ValidationExecutorSet(com.helger.phive.api.executorset.ValidationExecutorSet) IValidationExecutorSet(com.helger.phive.api.executorset.IValidationExecutorSet) Locale(java.util.Locale) VESID(com.helger.phive.api.executorset.VESID) IJsonObject(com.helger.json.IJsonObject) ValidationResultList(com.helger.phive.api.result.ValidationResultList) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) ClassPathResource(com.helger.commons.io.resource.ClassPathResource) ValidationExecutorSetRegistry(com.helger.phive.api.executorset.ValidationExecutorSetRegistry) Test(org.junit.Test)

Example 4 with IJsonObject

use of com.helger.json.IJsonObject 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 5 with IJsonObject

use of com.helger.json.IJsonObject in project phive by phax.

the class PhiveJsonHelperTest method testException.

@Test
public void testException() {
    final Exception ex = new IllegalArgumentException("bla foo");
    // to Json
    final IJsonObject aObj = PhiveJsonHelper.getJsonStackTrace(ex);
    assertNotNull(aObj);
}
Also used : IJsonObject(com.helger.json.IJsonObject) Test(org.junit.Test)

Aggregations

IJsonObject (com.helger.json.IJsonObject)67 JsonObject (com.helger.json.JsonObject)38 Nonnull (javax.annotation.Nonnull)34 IJsonArray (com.helger.json.IJsonArray)16 JsonArray (com.helger.json.JsonArray)16 Test (org.junit.Test)15 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)7 IError (com.helger.commons.error.IError)6 StopWatch (com.helger.commons.timing.StopWatch)5 IJson (com.helger.json.IJson)5 JsonWriter (com.helger.json.serialize.JsonWriter)5 Map (java.util.Map)5 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)4 ZonedDateTime (java.time.ZonedDateTime)4 Nullable (javax.annotation.Nullable)4 ReturnsMutableCopy (com.helger.commons.annotation.ReturnsMutableCopy)3 CommonsLinkedHashMap (com.helger.commons.collection.impl.CommonsLinkedHashMap)3 ICommonsList (com.helger.commons.collection.impl.ICommonsList)3 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)3 SimpleLocation (com.helger.commons.location.SimpleLocation)3