Search in sources :

Example 16 with IJsonObject

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

the class APIExecutorQueryGetServiceMetadata method invokeAPI.

public void invokeAPI(@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 String sPathServiceGroupID = aPathVariables.get(SMPRestFilter.PARAM_SERVICE_GROUP_ID);
    final ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, sPathServiceGroupID);
    // Is the remote query API disabled?
    if (SMPServerConfiguration.isRestRemoteQueryAPIDisabled()) {
        throw new SMPPreconditionFailedException("The remote query API is disabled. getRemoteServiceInformation will not be executed", aDataProvider.getCurrentURI());
    }
    final IIdentifierFactory aIF = SMPMetaManager.getIdentifierFactory();
    final ESMPAPIType eAPIType = SMPServerConfiguration.getRESTType().getAPIType();
    final IParticipantIdentifier aParticipantID = aIF.parseParticipantIdentifier(sPathServiceGroupID);
    if (aParticipantID == null) {
        throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, aDataProvider.getCurrentURI());
    }
    final SMPQueryParams aQueryParams = SMPQueryParams.create(eAPIType, aParticipantID);
    final String sDocTypeID = aPathVariables.get(SMPRestFilter.PARAM_DOCUMENT_TYPE_ID);
    final IDocumentTypeIdentifier aDocTypeID = aIF.parseDocumentTypeIdentifier(sDocTypeID);
    if (aDocTypeID == null)
        throw SMPBadRequestException.failedToParseDocType(sDocTypeID, null);
    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();
    final String sLogPrefix = "[QueryAPI] ";
    LOGGER.info(sLogPrefix + "Participant information of '" + aParticipantID.getURIEncoded() + "' is queried using SMP API '" + eAPIType + "' from '" + aQueryParams.getSMPHostURI() + "' for document type '" + aDocTypeID.getURIEncoded() + "'; XSD validation=" + bXMLSchemaValidation + "; signature verification=" + bVerifySignature);
    IJsonObject aJson = null;
    switch(eAPIType) {
        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(sLogPrefix + "Failed to perform the SMP lookup");
        aUnifiedResponse.setStatus(CHttp.HTTP_NOT_FOUND);
    } else {
        LOGGER.info(sLogPrefix + "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(1 * CGlobal.SECONDS_PER_HOUR);
    }
}
Also used : SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) BDXRClientReadOnly(com.helger.smpclient.bdxr1.BDXRClientReadOnly) JsonWriter(com.helger.json.serialize.JsonWriter) ESMPAPIType(com.helger.peppol.sml.ESMPAPIType) StopWatch(com.helger.commons.timing.StopWatch) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) ZonedDateTime(java.time.ZonedDateTime) IJsonObject(com.helger.json.IJsonObject) ISMPServerAPIDataProvider(com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 17 with IJsonObject

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

the class SMPStatusProvider method getDefaultStatusData.

@Nonnull
@ReturnsMutableCopy
public static IJsonObject getDefaultStatusData(final boolean bDisableLongRunningOperations) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Building status data");
    final StopWatch aSW = StopWatch.createdStarted();
    final ISMPSettings aSettings = SMPMetaManager.getSettings();
    final LocalDateTime aNow = PDTFactory.getCurrentLocalDateTime();
    final ISMLInfo aSMLInfo = aSettings.getSMLInfo();
    final IJsonObject aStatusData = new JsonObject();
    // Since 5.0.7
    aStatusData.add("build.timestamp", CSMPServer.getBuildTimestamp());
    // Since 5.3.3
    aStatusData.addIfNotNull("startup.datetime", PDTWebDateHelper.getAsStringXSD(SMPWebAppListener.getStartupDateTime()));
    aStatusData.add("status.datetime", PDTWebDateHelper.getAsStringXSD(PDTFactory.getCurrentOffsetDateTimeUTC()));
    aStatusData.add("version.smp", CSMPServer.getVersionNumber());
    aStatusData.add("version.java", SystemProperties.getJavaVersion());
    aStatusData.add("global.debug", GlobalDebug.isDebugMode());
    aStatusData.add("global.production", GlobalDebug.isProductionMode());
    aStatusData.add("smp.backend", SMPServerConfiguration.getBackend());
    aStatusData.add("smp.mode", SMPWebAppConfiguration.isTestVersion() ? "test" : "production");
    aStatusData.add("smp.resttype", SMPServerConfiguration.getRESTType().getID());
    aStatusData.add("smp.identifiertype", SMPServerConfiguration.getIdentifierType().getID());
    aStatusData.add("smp.id", SMPServerConfiguration.getSMLSMPID());
    aStatusData.add("smp.writable-rest-api.enabled", !aSettings.isRESTWritableAPIDisabled());
    // New in 5.1.0
    aStatusData.add("smp.publicurl", SMPServerConfiguration.getPublicServerURL());
    // New in 5.1.0
    aStatusData.add("smp.forceroot", SMPServerConfiguration.isForceRoot());
    // New in 5.2.0
    aStatusData.add("smp.rest.log-exceptions", SMPServerConfiguration.isRESTLogExceptions());
    // New in 5.2.1
    aStatusData.add("smp.rest.payload-on-error", SMPServerConfiguration.isRESTPayloadOnError());
    // SML information
    aStatusData.add("smp.sml.enabled", aSettings.isSMLEnabled());
    aStatusData.add("smp.sml.needed", aSettings.isSMLRequired());
    if (aSMLInfo != null) {
        aStatusData.add("smp.sml.url", aSMLInfo.getManagementServiceURL());
        aStatusData.add("smp.sml.dnszone", aSMLInfo.getDNSZone());
    }
    aStatusData.addIfNotNull("smp.sml.connection-timeout-ms", SMPServerConfiguration.getSMLConnectionTimeoutMS());
    aStatusData.add("smp.sml.request-timeout-ms", SMPServerConfiguration.getSMLRequestTimeoutMS());
    // Directory information
    aStatusData.add("smp.pd.enabled", aSettings.isDirectoryIntegrationEnabled());
    // New in 5.1.0
    aStatusData.add("smp.pd.needed", aSettings.isDirectoryIntegrationRequired());
    aStatusData.add("smp.pd.auto-update", aSettings.isDirectoryIntegrationAutoUpdate());
    aStatusData.add("smp.pd.hostname", aSettings.getDirectoryHostName());
    // Certificate information
    final boolean bCertConfigOk = SMPKeyManager.isKeyStoreValid();
    aStatusData.add("smp.certificate.configuration-valid", bCertConfigOk);
    if (bCertConfigOk) {
        final SMPKeyManager aKeyMgr = SMPKeyManager.getInstance();
        final PrivateKeyEntry aKeyEntry = aKeyMgr.getPrivateKeyEntry();
        if (aKeyEntry != null) {
            final Certificate[] aChain = aKeyEntry.getCertificateChain();
            if (aChain.length > 0 && aChain[0] instanceof X509Certificate) {
                final X509Certificate aX509Cert = (X509Certificate) aChain[0];
                aStatusData.add("smp.certificate.issuer", aX509Cert.getIssuerX500Principal().getName());
                aStatusData.add("smp.certificate.subject", aX509Cert.getSubjectX500Principal().getName());
                final LocalDateTime aNotAfter = PDTFactory.createLocalDateTime(aX509Cert.getNotAfter());
                final boolean bIsExpired = aNow.isAfter(aNotAfter);
                aStatusData.add("smp.certificate.expired", bIsExpired);
            }
        }
    }
    // Proxy configuration (since 5.2.0)
    aStatusData.add("proxy.http.configured", SMPServerConfiguration.getAsHttpProxySettings() != null);
    aStatusData.add("proxy.https.configured", SMPServerConfiguration.getAsHttpsProxySettings() != null);
    aStatusData.add("proxy.username.configured", StringHelper.hasText(SMPServerConfiguration.getProxyUsername()));
    // CSP configuration (since 5.2.6)
    aStatusData.add("csp.enabled", SMPWebAppConfiguration.isCSPEnabled());
    aStatusData.add("csp.reporting.only", SMPWebAppConfiguration.isCSPReportingOnly());
    aStatusData.add("csp.reporting.enabled", SMPWebAppConfiguration.isCSPReportingEnabled());
    // Add SPI data as well
    for (final ISMPStatusProviderExtensionSPI aImpl : LIST) {
        final ICommonsOrderedMap<String, ?> aMap = aImpl.getAdditionalStatusData(bDisableLongRunningOperations);
        aStatusData.addAll(aMap);
    }
    final long nMillis = aSW.stopAndGetMillis();
    if (nMillis > 100)
        LOGGER.info("Finished building status data after " + nMillis + " milliseconds which is considered to be too long");
    else if (LOGGER.isDebugEnabled())
        LOGGER.debug("Finished building status data");
    return aStatusData;
}
Also used : LocalDateTime(java.time.LocalDateTime) ISMLInfo(com.helger.peppol.sml.ISMLInfo) IJsonObject(com.helger.json.IJsonObject) JsonObject(com.helger.json.JsonObject) X509Certificate(java.security.cert.X509Certificate) StopWatch(com.helger.commons.timing.StopWatch) SMPKeyManager(com.helger.phoss.smp.security.SMPKeyManager) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) IJsonObject(com.helger.json.IJsonObject) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull)

Example 18 with IJsonObject

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

the class SMPStatusXServletHandler method handleRequest.

public void handleRequest(@Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) throws Exception {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Status information requested");
    // Build data to provide
    final IJsonObject aStatusData;
    if (SMPServerConfiguration.isStatusEnabled()) {
        // Special boolean parameter to ensure status works as health check
        final boolean bDisableLongRunningOperations = aRequestScope.params().getAsBoolean("disable-long-running", false);
        aStatusData = SMPStatusProvider.getDefaultStatusData(bDisableLongRunningOperations);
    } else {
        // Status is disabled in the configuration
        aStatusData = SMPStatusProvider.getStatusDisabledData();
    }
    // Put JSON on response
    aUnifiedResponse.disableCaching();
    aUnifiedResponse.setMimeType(new MimeType(CMimeType.APPLICATION_JSON).addParameter(CMimeType.PARAMETER_NAME_CHARSET, CHARSET.name()));
    aUnifiedResponse.setContentAndCharset(aStatusData.getAsJsonString(), CHARSET);
}
Also used : IJsonObject(com.helger.json.IJsonObject) CMimeType(com.helger.commons.mime.CMimeType) MimeType(com.helger.commons.mime.MimeType)

Example 19 with IJsonObject

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

Example 20 with IJsonObject

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

the class PModeMicroTypeConverterTest method _testPMode.

private static void _testPMode(@Nonnull final PMode aPMode) {
    XMLTestHelper.testMicroTypeConversion(aPMode);
    if (aPMode.hasInitiator())
        XMLTestHelper.testMicroTypeConversion(aPMode.getInitiator());
    if (aPMode.hasResponder())
        XMLTestHelper.testMicroTypeConversion(aPMode.getResponder());
    if (aPMode.hasLeg1())
        XMLTestHelper.testMicroTypeConversion(aPMode.getLeg1());
    if (aPMode.hasLeg2())
        XMLTestHelper.testMicroTypeConversion(aPMode.getLeg2());
    if (aPMode.hasPayloadService())
        XMLTestHelper.testMicroTypeConversion(aPMode.getPayloadService());
    if (aPMode.hasReceptionAwareness())
        XMLTestHelper.testMicroTypeConversion(aPMode.getReceptionAwareness());
    final IJsonObject o = aPMode.getAsJson();
    assertNotNull(o);
    final PMode aPMode2 = PModeJsonConverter.convertToNative(o);
    assertNotNull(aPMode2);
    CommonsTestHelper.testDefaultImplementationWithEqualContentObject(aPMode, aPMode2);
}
Also used : IJsonObject(com.helger.json.IJsonObject)

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