Search in sources :

Example 1 with IJsonArray

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

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

use of com.helger.json.IJsonArray in project peppol-commons by phax.

the class SMPJsonResponse method convert.

@Nonnull
public static IJsonObject convert(@Nonnull final IParticipantIdentifier aParticipantID, @Nonnull final IDocumentTypeIdentifier aDocTypeID, @Nonnull final com.helger.xsds.bdxr.smp1.ServiceMetadataType aSM) {
    ValueEnforcer.notNull(aParticipantID, "ParticipantID");
    ValueEnforcer.notNull(aDocTypeID, "DocTypeID");
    ValueEnforcer.notNull(aSM, "SM");
    final IJsonObject ret = new JsonObject();
    ret.add(JSON_SMPTYPE, ESMPAPIType.OASIS_BDXR_V1.getID());
    ret.add(JSON_PARTICIPANT_ID, aParticipantID.getURIEncoded());
    ret.add(JSON_DOCUMENT_TYPE_ID, aDocTypeID.getURIEncoded());
    final com.helger.xsds.bdxr.smp1.RedirectType aRedirect = aSM.getRedirect();
    if (aRedirect != null) {
        final IJsonObject aJsonRedirect = new JsonObject().add(JSON_HREF, aRedirect.getHref()).add(JSON_CERTIFICATE_UID, aRedirect.getCertificateUID()).addIfNotNull(JSON_EXTENSION, BDXR1ExtensionConverter.convertToJson(aRedirect.getExtension()));
        ret.addJson(JSON_REDIRECT, aJsonRedirect);
    } else {
        final com.helger.xsds.bdxr.smp1.ServiceInformationType aSI = aSM.getServiceInformation();
        final IJsonObject aJsonSI = new JsonObject();
        {
            final IJsonArray aJsonProcs = new JsonArray();
            // For all processes
            if (aSI.getProcessList() != null)
                for (final com.helger.xsds.bdxr.smp1.ProcessType aProcess : aSI.getProcessList().getProcess()) if (aProcess.getProcessIdentifier() != null) {
                    final IJsonObject aJsonProc = new JsonObject().add(JSON_PROCESS_ID, CIdentifier.getURIEncoded(aProcess.getProcessIdentifier()));
                    final IJsonArray aJsonEPs = new JsonArray();
                    // For all endpoints
                    if (aProcess.getServiceEndpointList() != null)
                        for (final com.helger.xsds.bdxr.smp1.EndpointType aEndpoint : aProcess.getServiceEndpointList().getEndpoint()) {
                            aJsonEPs.add(convertEndpoint(aEndpoint));
                        }
                    aJsonProc.addJson(JSON_ENDPOINTS, aJsonEPs).addIfNotNull(JSON_EXTENSION, BDXR1ExtensionConverter.convertToJson(aProcess.getExtension()));
                    aJsonProcs.add(aJsonProc);
                }
            aJsonSI.addJson(JSON_PROCESSES, aJsonProcs).addIfNotNull(JSON_EXTENSION, BDXR1ExtensionConverter.convertToJson(aSI.getExtension()));
        }
        ret.addJson(JSON_SERVICEINFO, aJsonSI);
    }
    return ret;
}
Also used : JsonArray(com.helger.json.JsonArray) IJsonArray(com.helger.json.IJsonArray) IJsonObject(com.helger.json.IJsonObject) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IJsonArray(com.helger.json.IJsonArray) Nonnull(javax.annotation.Nonnull)

Example 4 with IJsonArray

use of com.helger.json.IJsonArray in project peppol-commons by phax.

the class SMPJsonResponse method convert.

@Nonnull
public static IJsonObject convert(@Nonnull final ESMPAPIType eSMPAPIType, @Nonnull final IParticipantIdentifier aParticipantID, @Nonnull final Map<String, String> aSGHrefs, @Nonnull final IIdentifierFactory aIF) {
    ValueEnforcer.notNull(eSMPAPIType, "SMPAPIType");
    ValueEnforcer.notNull(aParticipantID, "ParticipantID");
    ValueEnforcer.notNull(aSGHrefs, "SGHrefs");
    ValueEnforcer.notNull(aIF, "IF");
    final IJsonObject aJson = new JsonObject();
    aJson.add(JSON_SMPTYPE, eSMPAPIType.getID());
    aJson.add(JSON_PARTICIPANT_ID, aParticipantID.getURIEncoded());
    final String sPathStart = "/" + aParticipantID.getURIEncoded() + '/' + BDXRClientReadOnly.URL_PART_SERVICES + '/';
    final IJsonArray aURLsArray = new JsonArray();
    // Show all ServiceGroup hrefs
    for (final Map.Entry<String, String> aEntry : aSGHrefs.entrySet()) {
        final String sHref = aEntry.getKey();
        final String sOriginalHref = aEntry.getValue();
        final IJsonObject aUrlEntry = new JsonObject().add(JSON_HREF, sOriginalHref);
        // Should be case insensitive "indexOf" here
        final int nPathStart = sHref.toLowerCase(Locale.US).indexOf(sPathStart.toLowerCase(Locale.US));
        if (nPathStart >= 0) {
            final String sDocType = sHref.substring(nPathStart + sPathStart.length());
            aUrlEntry.add(JSON_DOCUMENT_TYPE_ID, sDocType);
            final IDocumentTypeIdentifier aDocType = aIF.parseDocumentTypeIdentifier(sDocType);
            if (aDocType == null) {
                aUrlEntry.add(JSON_ERROR, "The document type ID could not be interpreted as a structured document type!");
            }
        } else {
            aUrlEntry.add(JSON_ERROR, "Contained href does not match the rules. Expected path part: '" + sPathStart + "'");
        }
        aURLsArray.add(aUrlEntry);
    }
    aJson.addJson(JSON_URLS, aURLsArray);
    return aJson;
}
Also used : JsonArray(com.helger.json.JsonArray) IJsonArray(com.helger.json.IJsonArray) IJsonObject(com.helger.json.IJsonObject) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) IJsonArray(com.helger.json.IJsonArray) Map(java.util.Map) Nonnull(javax.annotation.Nonnull)

Example 5 with IJsonArray

use of com.helger.json.IJsonArray in project phoss-smp by phax.

the class ImportSummary method appendTo.

public void appendTo(@Nonnull final IJsonObject aJson) {
    ValueEnforcer.notNull(aJson, "JsonObject");
    final IJsonArray aActions = new JsonArray();
    for (final Map.Entry<EImportSummaryAction, ImportSummaryItem> eItem : m_aMap.entrySet()) aActions.add(new JsonObject().add("id", eItem.getKey().getID()).add("success", eItem.getValue().getSuccessCount()).add("error", eItem.getValue().getErrorCount()));
    aJson.addJson("actions", aActions);
}
Also used : IJsonArray(com.helger.json.IJsonArray) JsonArray(com.helger.json.JsonArray) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IJsonArray(com.helger.json.IJsonArray) CommonsEnumMap(com.helger.commons.collection.impl.CommonsEnumMap) Map(java.util.Map) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap)

Aggregations

IJsonArray (com.helger.json.IJsonArray)18 IJsonObject (com.helger.json.IJsonObject)15 JsonArray (com.helger.json.JsonArray)12 JsonObject (com.helger.json.JsonObject)12 Nonnull (javax.annotation.Nonnull)12 Map (java.util.Map)5 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)4 ETriState (com.helger.commons.state.ETriState)4 CommonsLinkedHashMap (com.helger.commons.collection.impl.CommonsLinkedHashMap)3 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)3 IError (com.helger.commons.error.IError)3 Nonempty (com.helger.commons.annotation.Nonempty)2 ICommonsList (com.helger.commons.collection.impl.ICommonsList)2 IJsonValue (com.helger.json.IJsonValue)2 JsonWriterSettings (com.helger.json.serialize.JsonWriterSettings)2 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)2 ValidationResult (com.helger.phive.api.result.ValidationResult)2 IMicroDocument (com.helger.xml.microdom.IMicroDocument)2 IMicroElement (com.helger.xml.microdom.IMicroElement)2 MicroDocument (com.helger.xml.microdom.MicroDocument)2