Search in sources :

Example 1 with JsonObject

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

use of com.helger.json.JsonObject 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 3 with JsonObject

use of com.helger.json.JsonObject in project phoss-directory by phax.

the class PDExtendedBusinessCard method getAsJson.

@Nonnull
public IJsonObject getAsJson() {
    final IJsonObject ret = new JsonObject();
    ret.addJson("businesscard", m_aBusinessCard.getAsJson());
    ret.addJson("doctypes", new JsonArray().addAllMapped(m_aDocumentTypeIDs, x -> PDIdentifier.getAsJson(x.getScheme(), x.getValue())));
    return ret;
}
Also used : JsonArray(com.helger.json.JsonArray) Nonnegative(javax.annotation.Nonnegative) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) SimpleDocumentTypeIdentifier(com.helger.peppolid.simple.doctype.SimpleDocumentTypeIdentifier) IHasJson(com.helger.json.IHasJson) PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) Predicate(java.util.function.Predicate) IJsonObject(com.helger.json.IJsonObject) ToStringGenerator(com.helger.commons.string.ToStringGenerator) JsonObject(com.helger.json.JsonObject) Serializable(java.io.Serializable) ValueEnforcer(com.helger.commons.ValueEnforcer) JsonArray(com.helger.json.JsonArray) PDIdentifier(com.helger.pd.businesscard.generic.PDIdentifier) ICommonsList(com.helger.commons.collection.impl.ICommonsList) IJson(com.helger.json.IJson) ReturnsMutableObject(com.helger.commons.annotation.ReturnsMutableObject) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull) Immutable(javax.annotation.concurrent.Immutable) Nullable(javax.annotation.Nullable) IJsonObject(com.helger.json.IJsonObject) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) Nonnull(javax.annotation.Nonnull)

Example 4 with JsonObject

use of com.helger.json.JsonObject in project phoss-directory by phax.

the class PDName method getAsJson.

@Nonnull
public IJsonObject getAsJson() {
    final IJsonObject ret = new JsonObject();
    ret.add("name", m_sName);
    if (m_sLanguageCode != null)
        ret.add("language", m_sLanguageCode);
    return ret;
}
Also used : IJsonObject(com.helger.json.IJsonObject) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) Nonnull(javax.annotation.Nonnull)

Example 5 with JsonObject

use of com.helger.json.JsonObject in project phoss-directory by phax.

the class AjaxExecutorPublicLogin method handleRequest.

public void handleRequest(@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final PhotonUnifiedResponse aAjaxResponse) throws Exception {
    final LayoutExecutionContext aLEC = LayoutExecutionContext.createForAjaxOrAction(aRequestScope);
    final String sLoginName = aRequestScope.params().getAsString(CLogin.REQUEST_ATTR_USERID);
    final String sPassword = aRequestScope.params().getAsString(CLogin.REQUEST_ATTR_PASSWORD);
    // Main login
    final ELoginResult eLoginResult = LoggedInUserManager.getInstance().loginUser(sLoginName, sPassword, AppSecurity.REQUIRED_ROLE_IDS_VIEW);
    if (eLoginResult.isSuccess()) {
        aAjaxResponse.json(new JsonObject().add(JSON_LOGGEDIN, true));
    } else {
        // Get the rendered content of the menu area
        if (GlobalDebug.isDebugMode())
            LOGGER.warn("Login of '" + sLoginName + "' failed because " + eLoginResult);
        final Locale aDisplayLocale = aLEC.getDisplayLocale();
        final IHCNode aRoot = new BootstrapErrorBox().addChild(EPhotonCoreText.LOGIN_ERROR_MSG.getDisplayText(aDisplayLocale) + " " + eLoginResult.getDisplayText(aDisplayLocale));
        // Set as result property
        aAjaxResponse.json(new JsonObject().add(JSON_LOGGEDIN, false).add(JSON_HTML, HCRenderer.getAsHTMLStringWithoutNamespaces(aRoot)));
    }
}
Also used : Locale(java.util.Locale) LayoutExecutionContext(com.helger.photon.core.execcontext.LayoutExecutionContext) ELoginResult(com.helger.photon.security.login.ELoginResult) BootstrapErrorBox(com.helger.photon.bootstrap4.alert.BootstrapErrorBox) JsonObject(com.helger.json.JsonObject) IHCNode(com.helger.html.hc.IHCNode)

Aggregations

JsonObject (com.helger.json.JsonObject)40 IJsonObject (com.helger.json.IJsonObject)38 Nonnull (javax.annotation.Nonnull)27 JsonArray (com.helger.json.JsonArray)16 IJsonArray (com.helger.json.IJsonArray)13 Map (java.util.Map)5 ReturnsMutableCopy (com.helger.commons.annotation.ReturnsMutableCopy)3 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)3 ICommonsList (com.helger.commons.collection.impl.ICommonsList)3 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)3 StopWatch (com.helger.commons.timing.StopWatch)3 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)3 ZonedDateTime (java.time.ZonedDateTime)3 Locale (java.util.Locale)3 Nonempty (com.helger.commons.annotation.Nonempty)2 CommonsTreeMap (com.helger.commons.collection.impl.CommonsTreeMap)2 IError (com.helger.commons.error.IError)2 ClassPathResource (com.helger.commons.io.resource.ClassPathResource)2 IHCNode (com.helger.html.hc.IHCNode)2 JsonWriter (com.helger.json.serialize.JsonWriter)2