Search in sources :

Example 1 with ISMLConfiguration

use of com.helger.peppol.domain.ISMLConfiguration in project peppol-practical by phax.

the class PagePublicToolsParticipantInformation method fillContent.

@Override
protected void fillContent(@Nonnull final WebPageExecutionContext aWPEC) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
    final FormErrorList aFormErrors = new FormErrorList();
    final boolean bShowInput = true;
    String sParticipantIDScheme = DEFAULT_ID_SCHEME;
    String sParticipantIDValue = null;
    if (aWPEC.hasAction(CPageParam.ACTION_PERFORM)) {
        // Validate fields
        sParticipantIDScheme = StringHelper.trim(aWPEC.params().getAsString(FIELD_ID_SCHEME));
        sParticipantIDValue = StringHelper.trim(aWPEC.params().getAsString(FIELD_ID_VALUE));
        final String sSMLID = StringHelper.trim(aWPEC.params().getAsString(FIELD_SML));
        final ISMLConfiguration aSMLConfiguration = aSMLConfigurationMgr.getSMLInfoOfID(sSMLID);
        final boolean bSMLAutoDetect = ISMLConfigurationManager.ID_AUTO_DETECT.equals(sSMLID);
        final boolean bQueryBusinessCard = aWPEC.params().isCheckBoxChecked(PARAM_QUERY_BUSINESS_CARD, DEFAULT_QUERY_BUSINESS_CARD);
        final boolean bShowTime = aWPEC.params().isCheckBoxChecked(PARAM_SHOW_TIME, DEFAULT_SHOW_TIME);
        final boolean bXSDValidation = aWPEC.params().isCheckBoxChecked(PARAM_XSD_VALIDATION, DEFAULT_XSD_VALIDATION);
        final boolean bVerifySignatures = aWPEC.params().isCheckBoxChecked(PARAM_VERIFY_SIGNATURES, DEFAULT_VERIFY_SIGNATURES);
        final IIdentifierFactory aIF = aSMLConfiguration != null ? aSMLConfiguration.getSMPIdentifierType().getIdentifierFactory() : SimpleIdentifierFactory.INSTANCE;
        // Legacy URL params?
        if (aWPEC.params().containsKey("idscheme") && aWPEC.params().containsKey("idvalue")) {
            sParticipantIDScheme = DEFAULT_ID_SCHEME;
            sParticipantIDValue = StringHelper.trim(aWPEC.params().getAsString("idscheme")) + ":" + StringHelper.trim(aWPEC.params().getAsString("idvalue"));
        }
        if (StringHelper.hasNoText(sParticipantIDScheme))
            aFormErrors.addFieldError(FIELD_ID_SCHEME, "Please provide an identifier scheme");
        else if (!aIF.isParticipantIdentifierSchemeValid(sParticipantIDScheme))
            aFormErrors.addFieldError(FIELD_ID_SCHEME, "The participant identifier scheme '" + sParticipantIDScheme + "' is not valid!");
        if (StringHelper.hasNoText(sParticipantIDValue))
            aFormErrors.addFieldError(FIELD_ID_VALUE, "Please provide an identifier value");
        else if (!aIF.isParticipantIdentifierValueValid(sParticipantIDValue))
            aFormErrors.addFieldError(FIELD_ID_VALUE, "The participant identifier value '" + sParticipantIDValue + "' is not valid!");
        if (aSMLConfiguration == null && !bSMLAutoDetect)
            aFormErrors.addFieldError(FIELD_SML, "A valid SML must be selected!");
        if (aFormErrors.isEmpty()) {
            _queryParticipant(aWPEC, sParticipantIDScheme, sParticipantIDValue, aSMLConfiguration, bSMLAutoDetect, bQueryBusinessCard, bShowTime, bXSDValidation, bVerifySignatures);
        }
    }
    if (bShowInput) {
        final BootstrapForm aForm = aNodeList.addAndReturnChild(getUIHandler().createFormSelf(aWPEC).setMethod(EHCFormMethod.GET).setLeft(3));
        aForm.addChild(info().addChildren(div("Show all processes, document types and endpoints of a participant."), div("You may want to try scheme ").addChild(code(DEFAULT_ID_SCHEME)).addChild(" and value ").addChild(code("9915:test")).addChild(" on ").addChild(code("SMK")).addChild(" as an example.")));
        aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Identifier scheme").setCtrl(new HCEdit(new RequestField(FIELD_ID_SCHEME, sParticipantIDScheme)).setPlaceholder("Identifier scheme")).setHelpText(div("The most common identifier scheme is ").addChild(code(DEFAULT_ID_SCHEME))).setErrorList(aFormErrors.getListOfField(FIELD_ID_SCHEME)));
        aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Identifier value").setCtrl(new HCEdit(new RequestField(FIELD_ID_VALUE, sParticipantIDValue)).setPlaceholder("Identifier value")).setHelpText(div("The identifier value must look like ").addChild(code("9915:test"))).setErrorList(aFormErrors.getListOfField(FIELD_ID_VALUE)));
        aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("SML to use").setCtrl(new SMLConfigurationSelect(new RequestField(FIELD_SML, ISMLConfigurationManager.ID_AUTO_DETECT), true)).setErrorList(aFormErrors.getListOfField(FIELD_SML)));
        aForm.addFormGroup(new BootstrapFormGroup().setLabel("Query Business Card?").setCtrl(new HCCheckBox(new RequestFieldBoolean(PARAM_QUERY_BUSINESS_CARD, DEFAULT_QUERY_BUSINESS_CARD))).setErrorList(aFormErrors.getListOfField(PARAM_QUERY_BUSINESS_CARD)));
        aForm.addFormGroup(new BootstrapFormGroup().setLabel("Show query duration?").setCtrl(new HCCheckBox(new RequestFieldBoolean(PARAM_SHOW_TIME, DEFAULT_SHOW_TIME))).setErrorList(aFormErrors.getListOfField(PARAM_SHOW_TIME)));
        aForm.addFormGroup(new BootstrapFormGroup().setLabel("Enable XML Schema validation of responses?").setCtrl(new HCCheckBox(new RequestFieldBoolean(PARAM_XSD_VALIDATION, DEFAULT_XSD_VALIDATION))).setErrorList(aFormErrors.getListOfField(PARAM_XSD_VALIDATION)));
        aForm.addFormGroup(new BootstrapFormGroup().setLabel("Verify signatures of SMP responses?").setCtrl(new HCCheckBox(new RequestFieldBoolean(PARAM_VERIFY_SIGNATURES, DEFAULT_VERIFY_SIGNATURES))).setErrorList(aFormErrors.getListOfField(PARAM_VERIFY_SIGNATURES)));
        final BootstrapButtonToolbar aToolbar = aForm.addAndReturnChild(new BootstrapButtonToolbar(aWPEC));
        aToolbar.addHiddenField(CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM);
        aToolbar.addSubmitButton("Show details");
    }
}
Also used : HCNodeList(com.helger.html.hc.impl.HCNodeList) RequestFieldBoolean(com.helger.photon.core.form.RequestFieldBoolean) FormErrorList(com.helger.photon.core.form.FormErrorList) HCEdit(com.helger.html.hc.html.forms.HCEdit) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) SMLConfigurationSelect(com.helger.peppol.ui.select.SMLConfigurationSelect) PDTToString(com.helger.commons.datetime.PDTToString) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) ISMLConfigurationManager(com.helger.peppol.app.mgr.ISMLConfigurationManager) HCCheckBox(com.helger.html.hc.html.forms.HCCheckBox) BootstrapButtonToolbar(com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) RequestField(com.helger.photon.core.form.RequestField)

Example 2 with ISMLConfiguration

use of com.helger.peppol.domain.ISMLConfiguration in project peppol-practical by phax.

the class PagePublicToolsSMPSML method _registerSMPtoSML.

private void _registerSMPtoSML(@Nonnull final WebPageExecutionContext aWPEC, @Nonnull final FormErrorList aFormErrors) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
    final String sSMLID = aWPEC.params().getAsString(FIELD_SML_ID);
    final ISMLConfiguration aSMLInfo = aSMLConfigurationMgr.getSMLInfoOfID(sSMLID);
    final String sSMPID = aWPEC.params().getAsString(FIELD_SMP_ID);
    final String sPhysicalAddress = aWPEC.params().getAsString(FIELD_PHYSICAL_ADDRESS);
    final String sLogicalAddress = aWPEC.params().getAsString(FIELD_LOGICAL_ADDRESS);
    final IFileItem aKeyStoreFile = aWPEC.params().getAsFileItem(FIELD_KEYSTORE);
    final String sKeyStorePassword = aWPEC.params().getAsString(FIELD_KEYSTORE_PW);
    final boolean bIsPeppol = aSMLInfo != null && aSMLInfo.getSMPAPIType() == ESMPAPIType.PEPPOL;
    if (aSMLInfo == null)
        aFormErrors.addFieldError(FIELD_SML_ID, "A valid SML must be selected!");
    if (StringHelper.hasNoText(sSMPID))
        aFormErrors.addFieldError(FIELD_SMP_ID, "A non-empty SMP ID must be provided!");
    else if (!RegExHelper.stringMatchesPattern(CPPApp.PATTERN_SMP_ID, sSMPID))
        aFormErrors.addFieldError(FIELD_SMP_ID, "The provided SMP ID contains invalid characters. It must match the following regular expression: " + CPPApp.PATTERN_SMP_ID);
    if (StringHelper.hasNoText(sPhysicalAddress))
        aFormErrors.addFieldError(FIELD_PHYSICAL_ADDRESS, "A physical address must be provided!");
    else if (!RegExHelper.stringMatchesPattern(IPV4Addr.PATTERN_IPV4, sPhysicalAddress))
        aFormErrors.addFieldError(FIELD_PHYSICAL_ADDRESS, "The provided physical address does not seem to be an IPv4 address!");
    else {
        final String[] aParts = StringHelper.getExplodedArray('.', sPhysicalAddress, 4);
        final byte[] aBytes = new byte[] { (byte) StringParser.parseInt(aParts[0], -1), (byte) StringParser.parseInt(aParts[1], -1), (byte) StringParser.parseInt(aParts[2], -1), (byte) StringParser.parseInt(aParts[3], -1) };
        try {
            InetAddress.getByAddress(aBytes);
        } catch (final UnknownHostException ex) {
            final String sMsg = "The provided IP address does not resolve to a valid host. ";
            aFormErrors.addFieldError(FIELD_PHYSICAL_ADDRESS, sMsg + AppCommonUI.getTechnicalDetailsString(ex, false));
        }
    }
    if (StringHelper.hasNoText(sLogicalAddress))
        aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "A logical address must be provided in the form 'http://smp.example.org'!");
    else {
        final URL aURL = URLHelper.getAsURL(sLogicalAddress);
        if (aURL == null)
            aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "The provided logical address seems not be a URL! Please use the form 'http://smp.example.org'");
        else {
            if (bIsPeppol) {
                if (!"http".equals(aURL.getProtocol()) && !"https".equals(aURL.getProtocol()))
                    aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "The provided logical address must use the 'http' protocol and may not use the '" + aURL.getProtocol() + "' protocol. According to the Peppol SMP specification, no other protocols than 'http' are allowed!");
                // -1 means default port
                if (aURL.getPort() != 80 && aURL.getPort() != -1)
                    aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "The provided logical address must use the default http port 80 and not port " + aURL.getPort() + ". According to the Peppol SMP specification, no other ports are allowed!");
                if (StringHelper.hasText(aURL.getPath()) && !"/".equals(aURL.getPath()))
                    aFormErrors.addFieldError(FIELD_LOGICAL_ADDRESS, "The provided logical address may not contain a path (" + aURL.getPath() + ") because according to the Peppol SMP specifications it must run in the root (/) path!");
            }
        }
    }
    final SSLSocketFactory aSocketFactory = _loadKeyStoreAndCreateSSLSocketFactory(EKeyStoreType.JKS, SECURITY_PROVIDER, aKeyStoreFile, sKeyStorePassword, aFormErrors, aDisplayLocale);
    if (aFormErrors.isEmpty()) {
        try {
            final ManageServiceMetadataServiceCaller aCaller = _create(aSMLInfo.getSMLInfo(), aSocketFactory);
            aCaller.create(sSMPID, sPhysicalAddress, sLogicalAddress);
            final String sMsg = "Successfully registered SMP '" + sSMPID + "' with physical address '" + sPhysicalAddress + "' and logical address '" + sLogicalAddress + "' to the SML '" + aSMLInfo.getManagementServiceURL() + "'.";
            LOGGER.info(sMsg);
            aNodeList.addChild(success(sMsg));
            AuditHelper.onAuditExecuteSuccess("smp-sml-create", sSMPID, sPhysicalAddress, sLogicalAddress, aSMLInfo.getManagementServiceURL());
        } catch (final Exception ex) {
            final String sMsg = "Error registering SMP '" + sSMPID + "' with physical address '" + sPhysicalAddress + "' and logical address '" + sLogicalAddress + "' to the SML '" + aSMLInfo.getManagementServiceURL() + "'.";
            aNodeList.addChild(error(sMsg).addChild(AppCommonUI.getTechnicalDetailsUI(ex, true)));
            AuditHelper.onAuditExecuteFailure("smp-sml-create", sSMPID, sPhysicalAddress, sLogicalAddress, aSMLInfo.getManagementServiceURL(), ex.getClass(), ex.getMessage());
        }
    } else
        aNodeList.addChild(BootstrapWebPageUIHandler.INSTANCE.createIncorrectInputBox(aWPEC));
}
Also used : Locale(java.util.Locale) ISMLConfigurationManager(com.helger.peppol.app.mgr.ISMLConfigurationManager) HCNodeList(com.helger.html.hc.impl.HCNodeList) ManageServiceMetadataServiceCaller(com.helger.peppol.smlclient.ManageServiceMetadataServiceCaller) UnknownHostException(java.net.UnknownHostException) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) IFileItem(com.helger.web.fileupload.IFileItem) PDTToString(com.helger.commons.datetime.PDTToString) PDTFromString(com.helger.commons.datetime.PDTFromString) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) URL(java.net.URL) SimpleURL(com.helger.commons.url.SimpleURL) CertificateExpiredException(java.security.cert.CertificateExpiredException) ClientTransportException(com.sun.xml.ws.client.ClientTransportException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) UnknownHostException(java.net.UnknownHostException)

Example 3 with ISMLConfiguration

use of com.helger.peppol.domain.ISMLConfiguration in project peppol-practical by phax.

the class PagePublicToolsSMPSML method _updateSMPCertAtSML.

private void _updateSMPCertAtSML(@Nonnull final WebPageExecutionContext aWPEC, @Nonnull final FormErrorList aFormErrors) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final ISMLConfigurationManager aSMLConfigurationMgr = PPMetaManager.getSMLConfigurationMgr();
    final LocalDate aNow = PDTFactory.getCurrentLocalDate();
    final String sSMLID = aWPEC.params().getAsString(FIELD_SML_ID);
    final ISMLConfiguration aSML = aSMLConfigurationMgr.getSMLInfoOfID(sSMLID);
    final IFileItem aKeyStoreFile = aWPEC.params().getAsFileItem(FIELD_KEYSTORE);
    final String sKeyStorePassword = aWPEC.params().getAsString(FIELD_KEYSTORE_PW);
    final String sMigrationDate = aWPEC.params().getAsString(FIELD_PM_MIGRATION_DATE);
    final LocalDate aMigrationDate = PDTFromString.getLocalDateFromString(sMigrationDate, aDisplayLocale);
    final String sMigrationPublicCert = aWPEC.params().getAsStringTrimmed(FIELD_PM_PUBLIC_CERT);
    X509Certificate aMigrationPublicCert = null;
    if (aSML == null)
        aFormErrors.addFieldError(FIELD_SML_ID, "A valid SML must be selected!");
    if (StringHelper.hasText(sMigrationDate)) {
        if (aMigrationDate == null)
            aFormErrors.addFieldError(FIELD_PM_MIGRATION_DATE, "The provided certificate migration date '" + sMigrationDate + "' is invalid!");
        else if (aMigrationDate.compareTo(aNow) <= 0)
            aFormErrors.addFieldError(FIELD_PM_MIGRATION_DATE, "The certificate migration date must be in the future!");
    }
    if (StringHelper.hasNoText(sMigrationPublicCert)) {
        aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "A new public certificate must be provided.");
    } else {
        try {
            aMigrationPublicCert = CertificateHelper.convertStringToCertficate(sMigrationPublicCert);
        } catch (final Exception ex) {
        // Fall through
        }
        if (aMigrationPublicCert == null)
            aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The provided public certificate cannot be parsed as a X.509 certificate.");
        else {
            try {
                aMigrationPublicCert.checkValidity();
            } catch (final CertificateExpiredException ex) {
                aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The provided public certificate is already expired!");
                aMigrationPublicCert = null;
            } catch (final CertificateNotYetValidException ex) {
            // That's okay
            }
            if (!sMigrationPublicCert.startsWith(CertificateHelper.BEGIN_CERTIFICATE))
                aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The provided value must start with '" + CertificateHelper.BEGIN_CERTIFICATE + "' (without the quotes)");
            if (!sMigrationPublicCert.endsWith(CertificateHelper.END_CERTIFICATE))
                aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The provided value must end with '" + CertificateHelper.END_CERTIFICATE + "' (without the quotes)");
        }
    }
    if (aMigrationPublicCert != null) {
        final LocalDate aNotBefore = PDTFactory.createLocalDate(aMigrationPublicCert.getNotBefore());
        final LocalDate aNotAfter = PDTFactory.createLocalDate(aMigrationPublicCert.getNotAfter());
        if (aMigrationDate != null) {
            if (aMigrationDate.isBefore(aNotBefore))
                aFormErrors.addFieldError(FIELD_PM_MIGRATION_DATE, "The provided certificate migration date " + PDTToString.getAsString(aMigrationDate, aDisplayLocale) + " must not be before the certificate NotBefore date " + PDTToString.getAsString(aNotBefore, aDisplayLocale) + "!");
            if (aMigrationDate.isAfter(aNotAfter))
                aFormErrors.addFieldError(FIELD_PM_MIGRATION_DATE, "The provided certificate migration date " + PDTToString.getAsString(aMigrationDate, aDisplayLocale) + " must not be after the certificate NotAfter date " + PDTToString.getAsString(aNotAfter, aDisplayLocale) + "!");
        } else {
            if (aNotBefore.compareTo(aNow) <= 0)
                aFormErrors.addFieldError(FIELD_PM_PUBLIC_CERT, "The effective certificate migration date (" + PDTToString.getAsString(aNotBefore, aDisplayLocale) + " - taken from the new public certificate) must be in the future!");
        }
    }
    final SSLSocketFactory aSocketFactory = _loadKeyStoreAndCreateSSLSocketFactory(EKeyStoreType.JKS, SECURITY_PROVIDER, aKeyStoreFile, sKeyStorePassword, aFormErrors, aDisplayLocale);
    if (aFormErrors.isEmpty()) {
        final BDMSLClient aCaller = new BDMSLClient(aSML.getSMLInfo());
        aCaller.setSSLSocketFactory(aSocketFactory);
        try {
            aCaller.prepareChangeCertificate(sMigrationPublicCert, aMigrationDate);
            final LocalDateTime aNotBefore = PDTFactory.createLocalDateTime(aMigrationPublicCert.getNotBefore());
            final LocalDateTime aNotAfter = PDTFactory.createLocalDateTime(aMigrationPublicCert.getNotAfter());
            final LocalDate aEffectiveMigrationDate = aMigrationDate != null ? aMigrationDate : aNotBefore.toLocalDate();
            final String sMsg = "Successfully prepared migration of SMP certificate at SML '" + aSML.getManagementServiceURL() + "'" + " to be exchanged at " + PDTToString.getAsString(aEffectiveMigrationDate, aDisplayLocale) + ".";
            LOGGER.info(sMsg);
            aNodeList.addChild(success().addChildren(div(sMsg), div("Issuer: " + aMigrationPublicCert.getIssuerX500Principal().getName()), div("Subject: " + aMigrationPublicCert.getSubjectX500Principal().getName()), div("Not before: " + PDTToString.getAsString(aNotBefore, aDisplayLocale)), div("Not after: " + PDTToString.getAsString(aNotAfter, aDisplayLocale))));
            AuditHelper.onAuditExecuteSuccess("smp-sml-update-cert", aSML.getManagementServiceURL(), sMigrationPublicCert, aMigrationDate);
        } catch (final com.helger.peppol.smlclient.bdmsl.BadRequestFault | com.helger.peppol.smlclient.bdmsl.InternalErrorFault | com.helger.peppol.smlclient.bdmsl.NotFoundFault | com.helger.peppol.smlclient.bdmsl.UnauthorizedFault | ClientTransportException ex) {
            final String sMsg = "Error preparing migration of SMP certificate at SML '" + aSML.getManagementServiceURL() + "'.";
            aNodeList.addChild(error(sMsg).addChild(AppCommonUI.getTechnicalDetailsUI(ex, true)));
            AuditHelper.onAuditExecuteFailure("smp-sml-update-cert", aSML.getManagementServiceURL(), sMigrationPublicCert, aMigrationDate, ex.getClass(), ex.getMessage());
        }
    } else
        aNodeList.addChild(BootstrapWebPageUIHandler.INSTANCE.createIncorrectInputBox(aWPEC));
}
Also used : Locale(java.util.Locale) LocalDateTime(java.time.LocalDateTime) ClientTransportException(com.sun.xml.ws.client.ClientTransportException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) HCNodeList(com.helger.html.hc.impl.HCNodeList) CertificateExpiredException(java.security.cert.CertificateExpiredException) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) PDTToString(com.helger.commons.datetime.PDTToString) PDTFromString(com.helger.commons.datetime.PDTFromString) LocalDate(java.time.LocalDate) X509Certificate(java.security.cert.X509Certificate) CertificateExpiredException(java.security.cert.CertificateExpiredException) ClientTransportException(com.sun.xml.ws.client.ClientTransportException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) UnknownHostException(java.net.UnknownHostException) BDMSLClient(com.helger.peppol.smlclient.BDMSLClient) ISMLConfigurationManager(com.helger.peppol.app.mgr.ISMLConfigurationManager) IFileItem(com.helger.web.fileupload.IFileItem) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 4 with ISMLConfiguration

use of com.helger.peppol.domain.ISMLConfiguration in project peppol-practical by phax.

the class APISMPQueryGetBusinessCard 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 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 String sLogPrefix = "[API] ";
    LOGGER.info(sLogPrefix + "BusinessCard of '" + aParticipantID.getURIEncoded() + "' is queried using SMP API '" + aQueryParams.getSMPAPIType() + "' from '" + aQueryParams.getSMPHostURI() + "' using SML '" + aSML + "'");
    IJsonObject aJson = null;
    final String sBCURL = aQueryParams.getSMPHostURI().toString() + "/businesscard/" + aParticipantID.getURIEncoded();
    LOGGER.info(sLogPrefix + "Querying BC from '" + sBCURL + "'");
    byte[] aData;
    try (HttpClientManager aHttpClientMgr = new HttpClientManager()) {
        final HttpGet aGet = new HttpGet(sBCURL);
        aData = aHttpClientMgr.execute(aGet, new ResponseHandlerByteArray());
    } catch (final Exception ex) {
        aData = null;
    }
    if (aData == null)
        LOGGER.warn(sLogPrefix + "No Business Card is available for that participant.");
    else {
        final PDBusinessCard aBC = PDBusinessCardHelper.parseBusinessCard(aData, StandardCharsets.UTF_8);
        if (aBC == null) {
            LOGGER.error(sLogPrefix + "Failed to parse BC:\n" + new String(aData));
        } else {
            // Business Card found
            aJson = aBC.getAsJson();
        }
    }
    aSW.stop();
    if (aJson == null) {
        LOGGER.error("[API] Failed to perform the BusinessCard SMP lookup");
        aUnifiedResponse.setStatus(CHttp.HTTP_NOT_FOUND);
    } else {
        LOGGER.info("[API] Succesfully finished BusinessCard 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 : PDBusinessCard(com.helger.pd.businesscard.generic.PDBusinessCard) UnknownHostException(java.net.UnknownHostException) ResponseHandlerByteArray(com.helger.httpclient.response.ResponseHandlerByteArray) HttpGet(org.apache.http.client.methods.HttpGet) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) HttpResponseException(org.apache.http.client.HttpResponseException) JsonWriter(com.helger.json.serialize.JsonWriter) HttpResponseException(org.apache.http.client.HttpResponseException) UnknownHostException(java.net.UnknownHostException) StopWatch(com.helger.commons.timing.StopWatch) SMPQueryParams(com.helger.peppol.domain.SMPQueryParams) ISMLConfigurationManager(com.helger.peppol.app.mgr.ISMLConfigurationManager) HttpClientManager(com.helger.httpclient.HttpClientManager) ZonedDateTime(java.time.ZonedDateTime) IJsonObject(com.helger.json.IJsonObject) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 5 with ISMLConfiguration

use of com.helger.peppol.domain.ISMLConfiguration in project peppol-practical by phax.

the class SMLConfigurationManager method createSMLInfo.

@Nonnull
public ISMLConfiguration createSMLInfo(@Nonnull @Nonempty final String sSMLInfoID, @Nonnull @Nonempty final String sDisplayName, @Nonnull @Nonempty final String sDNSZone, @Nonnull @Nonempty final String sManagementServiceURL, final boolean bClientCertificateRequired, @Nonnull final ESMPAPIType eSMPAPIType, @Nonnull final ESMPIdentifierType eSMPIdentifierType, final boolean bProduction) {
    final SMLInfo aSMLInfo = new SMLInfo(sSMLInfoID, sDisplayName, sDNSZone, sManagementServiceURL, bClientCertificateRequired);
    final SMLConfiguration aExtSMLInfo = new SMLConfiguration(aSMLInfo, eSMPAPIType, eSMPIdentifierType, bProduction);
    m_aRWLock.writeLocked(() -> {
        internalCreateItem(aExtSMLInfo);
    });
    AuditHelper.onAuditCreateSuccess(SMLInfo.OT, sSMLInfoID, sDisplayName, sDNSZone, sManagementServiceURL, Boolean.valueOf(bClientCertificateRequired), eSMPAPIType, eSMPIdentifierType, Boolean.valueOf(bProduction));
    return aExtSMLInfo;
}
Also used : SMLConfiguration(com.helger.peppol.domain.SMLConfiguration) ISMLConfiguration(com.helger.peppol.domain.ISMLConfiguration) SMLInfo(com.helger.peppol.sml.SMLInfo) Nonnull(javax.annotation.Nonnull)

Aggregations

ISMLConfiguration (com.helger.peppol.domain.ISMLConfiguration)14 ISMLConfigurationManager (com.helger.peppol.app.mgr.ISMLConfigurationManager)12 UnknownHostException (java.net.UnknownHostException)8 HCNodeList (com.helger.html.hc.impl.HCNodeList)7 PDTToString (com.helger.commons.datetime.PDTToString)6 Locale (java.util.Locale)6 PDTFromString (com.helger.commons.datetime.PDTFromString)4 StopWatch (com.helger.commons.timing.StopWatch)4 SMPQueryParams (com.helger.peppol.domain.SMPQueryParams)4 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)4 IFileItem (com.helger.web.fileupload.IFileItem)4 ClientTransportException (com.sun.xml.ws.client.ClientTransportException)4 URL (java.net.URL)4 CertificateExpiredException (java.security.cert.CertificateExpiredException)4 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)4 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)4 SimpleURL (com.helger.commons.url.SimpleURL)3 HttpClientManager (com.helger.httpclient.HttpClientManager)3 ResponseHandlerByteArray (com.helger.httpclient.response.ResponseHandlerByteArray)3 IJsonObject (com.helger.json.IJsonObject)3