Search in sources :

Example 76 with IJsonObject

use of com.helger.json.IJsonObject in project peppol-practical by phax.

the class APISMPQueryGetServiceInformation method rateLimitedInvokeAPI.

@Override
protected void rateLimitedInvokeAPI(@Nonnull final IAPIDescriptor aAPIDescriptor, @Nonnull @Nonempty final String sPath, @Nonnull final Map<String, String> aPathVariables, @Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) throws Exception {
    final ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
    final String sSMLID = aPathVariables.get(PPAPI.PARAM_SML_ID);
    final boolean bSMLAutoDetect = ISMLConfigurationManager.ID_AUTO_DETECT.equals(sSMLID);
    ISMLConfiguration aSML = aSMLConfigurationMgr.getSMLInfoOfID(sSMLID);
    if (aSML == null && !bSMLAutoDetect)
        throw new APIParamException("Unsupported SML ID '" + sSMLID + "' provided.");
    final String sParticipantID = aPathVariables.get(PPAPI.PARAM_PARTICIPANT_ID);
    final IParticipantIdentifier aPID = SimpleIdentifierFactory.INSTANCE.parseParticipantIdentifier(sParticipantID);
    if (aPID == null)
        throw new APIParamException("Invalid participant ID '" + sParticipantID + "' provided.");
    final String sDocTypeID = aPathVariables.get(PPAPI.PARAM_DOCTYPE_ID);
    final IDocumentTypeIdentifier aDTID = SimpleIdentifierFactory.INSTANCE.parseDocumentTypeIdentifier(sDocTypeID);
    if (aDTID == null)
        throw new APIParamException("Invalid document type ID '" + sDocTypeID + "' provided.");
    final boolean bXMLSchemaValidation = aRequestScope.params().getAsBoolean("xmlSchemaValidation", true);
    final boolean bVerifySignature = aRequestScope.params().getAsBoolean("verifySignature", true);
    final ZonedDateTime aQueryDT = PDTFactory.getCurrentZonedDateTimeUTC();
    final StopWatch aSW = StopWatch.createdStarted();
    SMPQueryParams aQueryParams = null;
    if (bSMLAutoDetect) {
        for (final ISMLConfiguration aCurSML : aSMLConfigurationMgr.getAllSorted()) {
            aQueryParams = SMPQueryParams.createForSML(aCurSML, aPID.getScheme(), aPID.getValue(), false);
            if (aQueryParams == null)
                continue;
            try {
                InetAddress.getByName(aQueryParams.getSMPHostURI().getHost());
                // Found it
                aSML = aCurSML;
                break;
            } catch (final UnknownHostException ex) {
            // continue
            }
        }
        // Ensure to go into the exception handler
        if (aSML == null)
            throw new HttpResponseException(CHttp.HTTP_NOT_FOUND, "The participant identifier '" + sParticipantID + "' could not be found in any SML.");
    } else {
        aQueryParams = SMPQueryParams.createForSML(aSML, aPID.getScheme(), aPID.getValue(), true);
    }
    if (aQueryParams == null)
        throw new APIParamException("Failed to resolve participant ID '" + sParticipantID + "' for the provided SML '" + aSML.getID() + "'");
    final IParticipantIdentifier aParticipantID = aQueryParams.getParticipantID();
    final IDocumentTypeIdentifier aDocTypeID = aQueryParams.getIF().createDocumentTypeIdentifier(aDTID.getScheme(), aDTID.getValue());
    if (aDocTypeID == null)
        throw new APIParamException("Invalid document type ID '" + sDocTypeID + "' provided.");
    LOGGER.info("[API] Participant information of '" + aParticipantID.getURIEncoded() + "' is queried using SMP API '" + aQueryParams.getSMPAPIType() + "' from '" + aQueryParams.getSMPHostURI() + "' using SML '" + aSML.getID() + "' for document type '" + aDocTypeID.getURIEncoded() + "'; XSD validation=" + bXMLSchemaValidation + "; signature verification=" + bVerifySignature);
    IJsonObject aJson = null;
    switch(aQueryParams.getSMPAPIType()) {
        case PEPPOL:
            {
                final SMPClientReadOnly aSMPClient = new SMPClientReadOnly(aQueryParams.getSMPHostURI());
                aSMPClient.setXMLSchemaValidation(bXMLSchemaValidation);
                aSMPClient.setVerifySignature(bVerifySignature);
                final com.helger.xsds.peppol.smp1.SignedServiceMetadataType aSSM = aSMPClient.getServiceMetadataOrNull(aParticipantID, aDocTypeID);
                if (aSSM != null) {
                    final com.helger.xsds.peppol.smp1.ServiceMetadataType aSM = aSSM.getServiceMetadata();
                    aJson = SMPJsonResponse.convert(aParticipantID, aDocTypeID, aSM);
                }
                break;
            }
        case OASIS_BDXR_V1:
            {
                final BDXRClientReadOnly aBDXR1Client = new BDXRClientReadOnly(aQueryParams.getSMPHostURI());
                aBDXR1Client.setXMLSchemaValidation(bXMLSchemaValidation);
                aBDXR1Client.setVerifySignature(bVerifySignature);
                final com.helger.xsds.bdxr.smp1.SignedServiceMetadataType aSSM = aBDXR1Client.getServiceMetadataOrNull(aParticipantID, aDocTypeID);
                if (aSSM != null) {
                    final com.helger.xsds.bdxr.smp1.ServiceMetadataType aSM = aSSM.getServiceMetadata();
                    aJson = SMPJsonResponse.convert(aParticipantID, aDocTypeID, aSM);
                }
                break;
            }
    }
    aSW.stop();
    if (aJson == null) {
        LOGGER.error("[API] Failed to perform the SMP lookup");
        aUnifiedResponse.setStatus(CHttp.HTTP_NOT_FOUND);
    } else {
        LOGGER.info("[API] Succesfully finished lookup lookup after " + aSW.getMillis() + " milliseconds");
        aJson.add("queryDateTime", DateTimeFormatter.ISO_ZONED_DATE_TIME.format(aQueryDT));
        aJson.add("queryDurationMillis", aSW.getMillis());
        final String sRet = new JsonWriter(JsonWriterSettings.DEFAULT_SETTINGS_FORMATTED).writeAsString(aJson);
        aUnifiedResponse.setContentAndCharset(sRet, StandardCharsets.UTF_8).setMimeType(CMimeType.APPLICATION_JSON).enableCaching(3 * CGlobal.SECONDS_PER_HOUR);
    }
}
Also used : SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) UnknownHostException(java.net.UnknownHostException) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) HttpResponseException(org.apache.http.client.HttpResponseException) BDXRClientReadOnly(com.helger.smpclient.bdxr1.BDXRClientReadOnly) JsonWriter(com.helger.json.serialize.JsonWriter) StopWatch(com.helger.commons.timing.StopWatch) SMPQueryParams(com.helger.peppol.domain.SMPQueryParams) ISMLConfigurationManager(com.helger.peppol.app.mgr.ISMLConfigurationManager) ZonedDateTime(java.time.ZonedDateTime) IJsonObject(com.helger.json.IJsonObject) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 77 with IJsonObject

use of com.helger.json.IJsonObject in project peppol-practical by phax.

the class SMPJsonResponseExt 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) {
    final IJsonObject aJson = SMPJsonResponse.convert(eSMPAPIType, aParticipantID, aSGHrefs, aIF);
    final IJsonArray aURLsArray = aJson.getAsArray(SMPJsonResponse.JSON_URLS);
    if (aURLsArray != null)
        for (final IJson aEntry : aURLsArray) if (aEntry.isObject()) {
            final IJsonObject aUrlEntry = aEntry.getAsObject();
            final String sDocType = aUrlEntry.getAsString(SMPJsonResponse.JSON_DOCUMENT_TYPE_ID);
            if (sDocType != null) {
                final NiceNameEntry aNN = AppCommonUI.getDocTypeNames().get(sDocType);
                if (aNN != null) {
                    aUrlEntry.add(JSON_NICE_NAME, aNN.getName());
                    aUrlEntry.add(JSON_IS_DEPRECATED, aNN.isDeprecated());
                }
            }
        }
    return aJson;
}
Also used : IJsonObject(com.helger.json.IJsonObject) IJson(com.helger.json.IJson) IJsonArray(com.helger.json.IJsonArray) NiceNameEntry(com.helger.peppol.domain.NiceNameEntry) Nonnull(javax.annotation.Nonnull)

Example 78 with IJsonObject

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

the class ExportAllManager method writeFileParticipantJSON.

@Nonnull
static ESuccess writeFileParticipantJSON(@Nonnull final EQueryMode eQueryMode) throws IOException {
    final IJsonObject aObj = queryAllContainedParticipantsAsJSON(eQueryMode);
    final File f = _getInternalFileParticipantJSON();
    // Do it in a write lock!
    RW_LOCK.writeLock().lock();
    try (final Writer aWriter = FileHelper.getBufferedWriter(f, StandardCharsets.UTF_8)) {
        new JsonWriter().writeToWriterAndClose(aObj, aWriter);
        LOGGER.info("Successfully wrote all Participants as JSON to " + f.getAbsolutePath());
    } catch (final IOException ex) {
        LOGGER.error("Failed to export all Participants as JSON to " + f.getAbsolutePath(), ex);
    } finally {
        RW_LOCK.writeLock().unlock();
    }
    return ESuccess.SUCCESS;
}
Also used : IJsonObject(com.helger.json.IJsonObject) IOException(java.io.IOException) File(java.io.File) JsonWriter(com.helger.json.serialize.JsonWriter) CSVWriter(com.helger.commons.csv.CSVWriter) Writer(java.io.Writer) JsonWriter(com.helger.json.serialize.JsonWriter) MicroWriter(com.helger.xml.microdom.serialize.MicroWriter) Nonnull(javax.annotation.Nonnull)

Example 79 with IJsonObject

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

the class ExportAllManager method queryAllContainedParticipantsAsJSON.

@Nonnull
public static IJsonObject queryAllContainedParticipantsAsJSON(@Nonnull final EQueryMode eQueryMode) throws IOException {
    final Query aQuery = eQueryMode.getEffectiveQuery(new MatchAllDocsQuery());
    // Query all and group by participant ID
    final ICommonsSortedSet<IParticipantIdentifier> aSet = new CommonsTreeSet<>(Comparator.comparing(IParticipantIdentifier::getURIEncoded));
    PDMetaManager.getStorageMgr().searchAll(aQuery, -1, PDField.PARTICIPANT_ID::getDocValue, aSet::add);
    // XML root
    final IJsonObject aObj = new JsonObject();
    aObj.add("version", 1);
    aObj.add("creationdt", PDTWebDateHelper.getAsStringXSD(PDTFactory.getCurrentZonedDateTimeUTC()));
    aObj.add("count", aSet.size());
    // For all participants
    final IJsonArray aArray = new JsonArray();
    for (final IParticipantIdentifier aParticipantID : aSet) aArray.add(aParticipantID.getURIEncoded());
    aObj.addJson("participants", aArray);
    return aObj;
}
Also used : IJsonArray(com.helger.json.IJsonArray) JsonArray(com.helger.json.JsonArray) Query(org.apache.lucene.search.Query) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) CommonsTreeSet(com.helger.commons.collection.impl.CommonsTreeSet) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) IJsonObject(com.helger.json.IJsonObject) IJsonArray(com.helger.json.IJsonArray) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) Nonnull(javax.annotation.Nonnull)

Aggregations

IJsonObject (com.helger.json.IJsonObject)79 JsonObject (com.helger.json.JsonObject)44 Nonnull (javax.annotation.Nonnull)41 IJsonArray (com.helger.json.IJsonArray)22 JsonArray (com.helger.json.JsonArray)19 Test (org.junit.Test)15 JsonWriter (com.helger.json.serialize.JsonWriter)12 IJson (com.helger.json.IJson)10 Map (java.util.Map)10 StopWatch (com.helger.commons.timing.StopWatch)9 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)9 ZonedDateTime (java.time.ZonedDateTime)9 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)7 IError (com.helger.commons.error.IError)7 PDBusinessCard (com.helger.pd.businesscard.generic.PDBusinessCard)5 IDocumentTypeIdentifier (com.helger.peppolid.IDocumentTypeIdentifier)5 Nullable (javax.annotation.Nullable)5 Nonempty (com.helger.commons.annotation.Nonempty)4 ReturnsMutableCopy (com.helger.commons.annotation.ReturnsMutableCopy)3 CommonsLinkedHashMap (com.helger.commons.collection.impl.CommonsLinkedHashMap)3