Search in sources :

Example 11 with ISMPSettings

use of com.helger.phoss.smp.settings.ISMPSettings in project phoss-smp by phax.

the class PageSecureTasksProblems method _checkSMLConfiguration.

private void _checkSMLConfiguration(@Nonnull final HCOL aOL) {
    final ISMPSettings aSMPSettings = SMPMetaManager.getSettings();
    final String sSMPID = SMPServerConfiguration.getSMLSMPID();
    if (aSMPSettings.isSMLEnabled()) {
        final ISMLInfo aSMLInfo = aSMPSettings.getSMLInfo();
        if (aSMLInfo == null) {
            aOL.addItem(_createError("No SML is selected in the SMP settings."), div("All creations and deletions of service groups needs to be repeated when the SML connection is active!"));
        } else {
            // Check if this SMP is already registered
            final String sPublisherDNSName = sSMPID + "." + aSMLInfo.getPublisherDNSZone();
            try {
                InetAddress.getByName(sPublisherDNSName);
            // On success, ignore
            } catch (final UnknownHostException ex) {
                // continue
                aOL.addItem(_createWarning("It seems like this SMP was not yet registered to the SML."), div("This is a one-time action that should be performed once. It requires a valid SMP certificate to work."), div("The registration check was performed with the URL ").addChild(new HCA().setHref(new SimpleURL("http://" + sPublisherDNSName)).setTargetBlank().addChild(code(sPublisherDNSName))));
            }
        }
    } else {
        if (aSMPSettings.isSMLRequired())
            aOL.addItem(_createError("The connection to the SML is not enabled."), div("All creations and deletions of service groups needs to be repeated when the SML connection is active!"));
    }
}
Also used : ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) UnknownHostException(java.net.UnknownHostException) ISMLInfo(com.helger.peppol.sml.ISMLInfo) HCA(com.helger.html.hc.html.textlevel.HCA) PDTToString(com.helger.commons.datetime.PDTToString) SimpleURL(com.helger.commons.url.SimpleURL)

Example 12 with ISMPSettings

use of com.helger.phoss.smp.settings.ISMPSettings in project phoss-smp by phax.

the class ServiceGroupImport method importXMLVer10.

public static void importXMLVer10(@Nonnull final IMicroElement eRoot, final boolean bOverwriteExisting, @Nonnull final IUser aDefaultOwner, @Nonnull final ICommonsSet<String> aAllExistingServiceGroupIDs, @Nonnull final ICommonsSet<String> aAllExistingBusinessCardIDs, @Nonnull final ICommonsList<ImportActionItem> aActionList, @Nonnull final ImportSummary aSummary) {
    ValueEnforcer.notNull(eRoot, "Root");
    ValueEnforcer.notNull(aDefaultOwner, "DefaultOwner");
    ValueEnforcer.notNull(aAllExistingServiceGroupIDs, "AllExistingServiceGroupIDs");
    ValueEnforcer.notNull(aAllExistingBusinessCardIDs, "AllExistingBusinessCardIDs");
    ValueEnforcer.notNull(aActionList, "ActionList");
    ValueEnforcer.notNull(aSummary, "Summary");
    final String sLogPrefix = "[SG-IMPORT-" + COUNTER.incrementAndGet() + "] ";
    final BiConsumer<String, String> aLoggerSuccess = (pi, msg) -> {
        LOGGER.info(sLogPrefix + "[" + pi + "] " + msg);
        aActionList.add(ImportActionItem.createSuccess(pi, msg));
    };
    final BiConsumer<String, String> aLoggerInfo = (pi, msg) -> {
        LOGGER.info(sLogPrefix + (pi == null ? "" : "[" + pi + "] ") + msg);
        aActionList.add(ImportActionItem.createInfo(pi, msg));
    };
    final BiConsumer<String, String> aLoggerWarn = (pi, msg) -> {
        LOGGER.info(sLogPrefix + (pi == null ? "" : "[" + pi + "] ") + msg);
        aActionList.add(ImportActionItem.createWarning(pi, msg));
    };
    final Consumer<String> aLoggerError = msg -> {
        LOGGER.error(sLogPrefix + msg);
        aActionList.add(ImportActionItem.createError(null, msg, null));
    };
    final BiConsumer<String, Exception> aLoggerErrorEx = (msg, ex) -> {
        LOGGER.error(sLogPrefix + msg, ex);
        aActionList.add(ImportActionItem.createError(null, msg, ex));
    };
    final BiConsumer<String, String> aLoggerErrorPI = (pi, msg) -> {
        LOGGER.error(sLogPrefix + "[" + pi + "] " + msg);
        aActionList.add(ImportActionItem.createError(pi, msg, null));
    };
    final ITriConsumer<String, String, Exception> aLoggerErrorPIEx = (pi, msg, ex) -> {
        LOGGER.error(sLogPrefix + "[" + pi + "] " + msg, ex);
        aActionList.add(ImportActionItem.createError(pi, msg, ex));
    };
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Starting import of Service Groups from XML v1.0, overwrite is " + (bOverwriteExisting ? "enabled" : "disabled"));
    final ISMPSettings aSettings = SMPMetaManager.getSettings();
    final IUserManager aUserMgr = PhotonSecurityManager.getUserMgr();
    final ICommonsOrderedMap<ISMPServiceGroup, InternalImportData> aImportServiceGroups = new CommonsLinkedHashMap<>();
    final ICommonsMap<String, ISMPServiceGroup> aDeleteServiceGroups = new CommonsHashMap<>();
    // First read all service groups as they are dependents of the
    // business cards
    int nSGIndex = 0;
    for (final IMicroElement eServiceGroup : eRoot.getAllChildElements(CSMPExchange.ELEMENT_SERVICEGROUP)) {
        // Read service group and service information
        final ISMPServiceGroup aServiceGroup;
        try {
            aServiceGroup = SMPServiceGroupMicroTypeConverter.convertToNative(eServiceGroup, x -> {
                IUser aOwner = aUserMgr.getUserOfID(x);
                if (aOwner == null) {
                    // Select the default owner if an unknown user is contained
                    aOwner = aDefaultOwner;
                    LOGGER.warn("Failed to resolve stored owner '" + x + "' - using default owner '" + aDefaultOwner.getID() + "'");
                }
                // If the user is deleted, but existing - keep the deleted user
                return aOwner;
            });
        } catch (final RuntimeException ex) {
            aLoggerErrorEx.accept("Error parsing the Service Group at index " + nSGIndex + ". Ignoring this Service Group.", ex);
            continue;
        }
        final String sServiceGroupID = aServiceGroup.getID();
        final boolean bIsServiceGroupContained = aAllExistingServiceGroupIDs.contains(sServiceGroupID);
        if (!bIsServiceGroupContained || bOverwriteExisting) {
            if (aImportServiceGroups.containsKey(aServiceGroup)) {
                aLoggerErrorPI.accept(sServiceGroupID, "The Service Group at index " + nSGIndex + " is already contained in the file. Will overwrite the previous definition.");
            }
            // Remember to create/overwrite the service group
            final InternalImportData aImportData = new InternalImportData();
            aImportServiceGroups.put(aServiceGroup, aImportData);
            if (bIsServiceGroupContained)
                aDeleteServiceGroups.put(sServiceGroupID, aServiceGroup);
            aLoggerSuccess.accept(sServiceGroupID, "Will " + (bIsServiceGroupContained ? "overwrite" : "import") + " Service Group");
            // read all contained service information
            {
                int nSICount = 0;
                for (final IMicroElement eServiceInfo : eServiceGroup.getAllChildElements(CSMPExchange.ELEMENT_SERVICEINFO)) {
                    final ISMPServiceInformation aServiceInfo = SMPServiceInformationMicroTypeConverter.convertToNative(eServiceInfo, x -> aServiceGroup);
                    aImportData.addServiceInfo(aServiceInfo);
                    ++nSICount;
                }
                aLoggerInfo.accept(sServiceGroupID, "Read " + nSICount + " Service Information " + (nSICount == 1 ? "element" : "elements") + " of Service Group");
            }
            // read all contained redirects
            {
                int nRDCount = 0;
                for (final IMicroElement eRedirect : eServiceGroup.getAllChildElements(CSMPExchange.ELEMENT_REDIRECT)) {
                    final ISMPRedirect aRedirect = SMPRedirectMicroTypeConverter.convertToNative(eRedirect, x -> aServiceGroup);
                    aImportData.addRedirect(aRedirect);
                    ++nRDCount;
                }
                aLoggerInfo.accept(sServiceGroupID, "Read " + nRDCount + " Redirect " + (nRDCount == 1 ? "element" : "elements") + " of Service Group");
            }
        } else {
            aLoggerWarn.accept(sServiceGroupID, "Ignoring already existing Service Group");
        }
        ++nSGIndex;
    }
    // Now read the business cards
    final ICommonsOrderedSet<ISMPBusinessCard> aImportBusinessCards = new CommonsLinkedHashSet<>();
    final ICommonsMap<String, ISMPBusinessCard> aDeleteBusinessCards = new CommonsHashMap<>();
    if (aSettings.isDirectoryIntegrationEnabled()) {
        // Read them only if the Peppol Directory integration is enabled
        int nBCIndex = 0;
        for (final IMicroElement eBusinessCard : eRoot.getAllChildElements(CSMPExchange.ELEMENT_BUSINESSCARD)) {
            // Read business card
            ISMPBusinessCard aBusinessCard = null;
            try {
                aBusinessCard = new SMPBusinessCardMicroTypeConverter().convertToNative(eBusinessCard);
            } catch (final RuntimeException ex) {
                // Service group not found
                aLoggerError.accept("Business Card at index " + nBCIndex + " contains an invalid/unknown Service Group!");
            }
            if (aBusinessCard == null) {
                aLoggerError.accept("Failed to read Business Card at index " + nBCIndex);
            } else {
                final String sBusinessCardID = aBusinessCard.getID();
                final boolean bIsBusinessCardContained = aAllExistingBusinessCardIDs.contains(sBusinessCardID);
                if (!bIsBusinessCardContained || bOverwriteExisting) {
                    if (aImportBusinessCards.removeIf(x -> x.getID().equals(sBusinessCardID))) {
                        aLoggerErrorPI.accept(sBusinessCardID, "The Business Card already contained in the file. Will overwrite the previous definition.");
                    }
                    aImportBusinessCards.add(aBusinessCard);
                    if (bIsBusinessCardContained) {
                        // BCs are deleted when the SGs are deleted
                        if (!aDeleteServiceGroups.containsKey(sBusinessCardID))
                            aDeleteBusinessCards.put(sBusinessCardID, aBusinessCard);
                    }
                    aLoggerSuccess.accept(sBusinessCardID, "Will " + (bIsBusinessCardContained ? "overwrite" : "import") + " Business Card");
                } else {
                    aLoggerWarn.accept(sBusinessCardID, "Ignoring already existing Business Card");
                }
            }
            ++nBCIndex;
        }
    }
    if (aImportServiceGroups.isEmpty() && aImportBusinessCards.isEmpty()) {
        aLoggerWarn.accept(null, aSettings.isDirectoryIntegrationEnabled() ? "Found neither a Service Group nor a Business Card to import." : "Found no Service Group to import.");
    } else if (aActionList.containsAny(ImportActionItem::isError)) {
        aLoggerError.accept("Nothing will be imported because of the previous errors.");
    } else {
        // Start importing
        aLoggerInfo.accept(null, "Import is performed!");
        final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
        final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
        final ISMPRedirectManager aRedirectMgr = SMPMetaManager.getRedirectMgr();
        final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
        // 1. delete all existing service groups to be imported (if overwrite);
        // this may implicitly delete business cards
        final ICommonsSet<IParticipantIdentifier> aDeletedServiceGroups = new CommonsHashSet<>();
        for (final Map.Entry<String, ISMPServiceGroup> aEntry : aDeleteServiceGroups.entrySet()) {
            final String sServiceGroupID = aEntry.getKey();
            final ISMPServiceGroup aDeleteServiceGroup = aEntry.getValue();
            final IParticipantIdentifier aPI = aDeleteServiceGroup.getParticipantIdentifier();
            try {
                // Delete locally only
                if (aServiceGroupMgr.deleteSMPServiceGroup(aPI, false).isChanged()) {
                    aLoggerSuccess.accept(sServiceGroupID, "Successfully deleted Service Group");
                    aDeletedServiceGroups.add(aPI);
                    aSummary.onSuccess(EImportSummaryAction.DELETE_SG);
                } else {
                    aLoggerErrorPI.accept(sServiceGroupID, "Failed to delete Service Group");
                    aSummary.onError(EImportSummaryAction.DELETE_SG);
                }
            } catch (final SMPServerException ex) {
                aLoggerErrorPIEx.accept(sServiceGroupID, "Failed to delete Service Group", ex);
                aSummary.onError(EImportSummaryAction.DELETE_SG);
            }
        }
        // 2. create all service groups
        for (final Map.Entry<ISMPServiceGroup, InternalImportData> aEntry : aImportServiceGroups.entrySet()) {
            final ISMPServiceGroup aImportServiceGroup = aEntry.getKey();
            final String sServiceGroupID = aImportServiceGroup.getID();
            ISMPServiceGroup aNewServiceGroup = null;
            try {
                final boolean bIsOverwrite = aDeleteServiceGroups.containsKey(sServiceGroupID);
                // Create in SML only for newly created entries
                aNewServiceGroup = aServiceGroupMgr.createSMPServiceGroup(aImportServiceGroup.getOwnerID(), aImportServiceGroup.getParticipantIdentifier(), aImportServiceGroup.getExtensionsAsString(), !bIsOverwrite);
                aLoggerSuccess.accept(sServiceGroupID, "Successfully created Service Group");
                aSummary.onSuccess(EImportSummaryAction.CREATE_SG);
            } catch (final Exception ex) {
                // E.g. if SML connection failed
                aLoggerErrorPIEx.accept(sServiceGroupID, "Error creating the new Service Group", ex);
                // Delete Business Card again, if already present
                aImportBusinessCards.removeIf(x -> x.getID().equals(sServiceGroupID));
                aSummary.onError(EImportSummaryAction.CREATE_SG);
            }
            if (aNewServiceGroup != null) {
                // 3a. create all endpoints
                for (final ISMPServiceInformation aImportServiceInfo : aEntry.getValue().getServiceInfo()) {
                    try {
                        if (aServiceInfoMgr.mergeSMPServiceInformation(aImportServiceInfo).isSuccess()) {
                            aLoggerSuccess.accept(sServiceGroupID, "Successfully created Service Information");
                            aSummary.onSuccess(EImportSummaryAction.CREATE_SI);
                        } else {
                            aLoggerErrorPI.accept(sServiceGroupID, "Error creating the new Service Information");
                            aSummary.onError(EImportSummaryAction.CREATE_SI);
                        }
                    } catch (final Exception ex) {
                        aLoggerErrorPIEx.accept(sServiceGroupID, "Error creating the new Service Information", ex);
                        aSummary.onError(EImportSummaryAction.CREATE_SI);
                    }
                }
                // 3b. create all redirects
                for (final ISMPRedirect aImportRedirect : aEntry.getValue().getRedirects()) {
                    try {
                        if (aRedirectMgr.createOrUpdateSMPRedirect(aNewServiceGroup, aImportRedirect.getDocumentTypeIdentifier(), aImportRedirect.getTargetHref(), aImportRedirect.getSubjectUniqueIdentifier(), aImportRedirect.getCertificate(), aImportRedirect.getExtensionsAsString()) != null) {
                            aLoggerSuccess.accept(sServiceGroupID, "Successfully created Redirect");
                            aSummary.onSuccess(EImportSummaryAction.CREATE_REDIRECT);
                        } else {
                            aLoggerErrorPI.accept(sServiceGroupID, "Error creating the new Redirect");
                            aSummary.onError(EImportSummaryAction.CREATE_REDIRECT);
                        }
                    } catch (final Exception ex) {
                        aLoggerErrorPIEx.accept(sServiceGroupID, "Error creating the new Redirect", ex);
                        aSummary.onError(EImportSummaryAction.CREATE_REDIRECT);
                    }
                }
            }
        }
        // Note: if PD integration is disabled, the list is empty
        for (final Map.Entry<String, ISMPBusinessCard> aEntry : aDeleteBusinessCards.entrySet()) {
            final String sServiceGroupID = aEntry.getKey();
            final ISMPBusinessCard aDeleteBusinessCard = aEntry.getValue();
            try {
                if (aBusinessCardMgr.deleteSMPBusinessCard(aDeleteBusinessCard).isChanged()) {
                    aLoggerSuccess.accept(sServiceGroupID, "Successfully deleted Business Card");
                    aSummary.onSuccess(EImportSummaryAction.DELETE_BC);
                } else {
                    aSummary.onError(EImportSummaryAction.DELETE_BC);
                    // was automatically deleted afterwards
                    if (!aDeletedServiceGroups.contains(aDeleteBusinessCard.getParticipantIdentifier()))
                        aLoggerErrorPI.accept(sServiceGroupID, "Failed to delete Business Card");
                }
            } catch (final Exception ex) {
                aLoggerErrorPIEx.accept(sServiceGroupID, "Failed to delete Business Card", ex);
                aSummary.onError(EImportSummaryAction.DELETE_BC);
            }
        }
        // Note: if PD integration is disabled, the list is empty
        for (final ISMPBusinessCard aImportBusinessCard : aImportBusinessCards) {
            final String sBusinessCardID = aImportBusinessCard.getID();
            try {
                if (aBusinessCardMgr.createOrUpdateSMPBusinessCard(aImportBusinessCard.getParticipantIdentifier(), aImportBusinessCard.getAllEntities()) != null) {
                    aLoggerSuccess.accept(sBusinessCardID, "Successfully created Business Card");
                    aSummary.onSuccess(EImportSummaryAction.CREATE_BC);
                } else {
                    aLoggerErrorPI.accept(sBusinessCardID, "Failed to create Business Card");
                    aSummary.onError(EImportSummaryAction.CREATE_BC);
                }
            } catch (final Exception ex) {
                aLoggerErrorPIEx.accept(sBusinessCardID, "Failed to create Business Card", ex);
                aSummary.onError(EImportSummaryAction.CREATE_BC);
            }
        }
    }
}
Also used : SMPBusinessCardMicroTypeConverter(com.helger.phoss.smp.domain.businesscard.SMPBusinessCardMicroTypeConverter) ISMPBusinessCard(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCard) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) ICommonsSet(com.helger.commons.collection.impl.ICommonsSet) SMPServiceInformationMicroTypeConverter(com.helger.phoss.smp.domain.serviceinfo.SMPServiceInformationMicroTypeConverter) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) SMPRedirectMicroTypeConverter(com.helger.phoss.smp.domain.redirect.SMPRedirectMicroTypeConverter) LoggerFactory(org.slf4j.LoggerFactory) ISMPRedirectManager(com.helger.phoss.smp.domain.redirect.ISMPRedirectManager) IUserManager(com.helger.photon.security.user.IUserManager) SMPServiceGroupMicroTypeConverter(com.helger.phoss.smp.domain.servicegroup.SMPServiceGroupMicroTypeConverter) ICommonsIterable(com.helger.commons.collection.impl.ICommonsIterable) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) SMPServerException(com.helger.phoss.smp.exception.SMPServerException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IUser(com.helger.photon.security.user.IUser) IMicroElement(com.helger.xml.microdom.IMicroElement) Map(java.util.Map) ISMPRedirect(com.helger.phoss.smp.domain.redirect.ISMPRedirect) BiConsumer(java.util.function.BiConsumer) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) Nonnull(javax.annotation.Nonnull) ITriConsumer(com.helger.commons.functional.ITriConsumer) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) SMPMetaManager(com.helger.phoss.smp.domain.SMPMetaManager) CommonsLinkedHashSet(com.helger.commons.collection.impl.CommonsLinkedHashSet) ICommonsOrderedMap(com.helger.commons.collection.impl.ICommonsOrderedMap) ValueEnforcer(com.helger.commons.ValueEnforcer) Consumer(java.util.function.Consumer) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ICommonsOrderedSet(com.helger.commons.collection.impl.ICommonsOrderedSet) ISMPServiceInformationManager(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager) CommonsHashSet(com.helger.commons.collection.impl.CommonsHashSet) ICommonsList(com.helger.commons.collection.impl.ICommonsList) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) Immutable(javax.annotation.concurrent.Immutable) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) PhotonSecurityManager(com.helger.photon.security.mgr.PhotonSecurityManager) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) IUserManager(com.helger.photon.security.user.IUserManager) SMPBusinessCardMicroTypeConverter(com.helger.phoss.smp.domain.businesscard.SMPBusinessCardMicroTypeConverter) ISMPBusinessCard(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCard) ISMPRedirectManager(com.helger.phoss.smp.domain.redirect.ISMPRedirectManager) ISMPRedirect(com.helger.phoss.smp.domain.redirect.ISMPRedirect) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) IUser(com.helger.photon.security.user.IUser) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap) ISMPServiceInformationManager(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) SMPServerException(com.helger.phoss.smp.exception.SMPServerException) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) ICommonsSet(com.helger.commons.collection.impl.ICommonsSet) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) IMicroElement(com.helger.xml.microdom.IMicroElement) CommonsLinkedHashSet(com.helger.commons.collection.impl.CommonsLinkedHashSet) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) SMPServerException(com.helger.phoss.smp.exception.SMPServerException)

Example 13 with ISMPSettings

use of com.helger.phoss.smp.settings.ISMPSettings in project phoss-smp by phax.

the class V14__MigrateSettingsToDB method migrate.

public void migrate(@Nonnull final Context context) throws Exception {
    try (final WebScoped aWS = new WebScoped()) {
        LOGGER.info("Migrating all settings to the DB");
        final String sFilename = "smp-settings.xml";
        final File aFile = WebFileIO.getDataIO().getFile(sFilename);
        if (aFile.exists()) {
            final SMPSettingsManagerXML aMgrXML = new SMPSettingsManagerXML(sFilename);
            final ISMPSettings aSettings = aMgrXML.getSettings();
            final SMPSettingsManagerJDBC aMgrNew = new SMPSettingsManagerJDBC(SMPDBExecutor::new);
            if (aMgrNew.updateSettings(aSettings.isRESTWritableAPIDisabled(), aSettings.isDirectoryIntegrationEnabled(), aSettings.isDirectoryIntegrationRequired(), aSettings.isDirectoryIntegrationAutoUpdate(), aSettings.getDirectoryHostName(), aSettings.isSMLEnabled(), aSettings.isSMLRequired(), aSettings.getSMLInfoID()).isUnchanged())
                throw new IllegalStateException("Failed to migrate SMP settings to DB");
            // Rename to avoid later inconsistencies
            WebFileIO.getDataIO().renameFile(sFilename, sFilename + ".migrated");
            LOGGER.info("Finished migrating all SMP settings to the DB");
        } else {
            LOGGER.info("No SMP settings file found");
        }
    }
}
Also used : WebScoped(com.helger.web.scope.mgr.WebScoped) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) SMPSettingsManagerJDBC(com.helger.phoss.smp.backend.sql.mgr.SMPSettingsManagerJDBC) File(java.io.File) SMPSettingsManagerXML(com.helger.phoss.smp.settings.SMPSettingsManagerXML) SMPDBExecutor(com.helger.phoss.smp.backend.sql.SMPDBExecutor)

Example 14 with ISMPSettings

use of com.helger.phoss.smp.settings.ISMPSettings in project phoss-smp by phax.

the class SMPSettingsManagerMongoDBTest method testBasic.

@Test
public void testBasic() {
    final ISMLInfoManager aSMLInfoMgr = SMPMetaManager.getSMLInfoMgr();
    final ISMLInfo aSMLInfo = aSMLInfoMgr.createSMLInfo("bla", "foo", "http://bar", true);
    assertNotNull(aSMLInfo);
    try (final SMPSettingsManagerMongoDB aMgr = new SMPSettingsManagerMongoDB()) {
        final ISMPSettings aSettings = aMgr.getSettings();
        assertNotNull(aSettings);
        aMgr.updateSettings(true, true, true, true, "v1", true, true, aSMLInfo.getID());
        assertTrue(aSettings.isRESTWritableAPIDisabled());
        assertTrue(aSettings.isDirectoryIntegrationRequired());
        assertTrue(aSettings.isDirectoryIntegrationEnabled());
        assertTrue(aSettings.isDirectoryIntegrationAutoUpdate());
        assertEquals("v1", aSettings.getDirectoryHostName());
        assertTrue(aSettings.isSMLRequired());
        assertTrue(aSettings.isSMLEnabled());
        assertEquals(aSMLInfo, aSettings.getSMLInfo());
        aMgr.updateSettings(false, false, false, false, "v2", false, false, aSMLInfo.getID());
        assertFalse(aSettings.isRESTWritableAPIDisabled());
        assertFalse(aSettings.isDirectoryIntegrationRequired());
        assertFalse(aSettings.isDirectoryIntegrationEnabled());
        assertFalse(aSettings.isDirectoryIntegrationAutoUpdate());
        assertEquals("v2", aSettings.getDirectoryHostName());
        assertFalse(aSettings.isSMLRequired());
        assertFalse(aSettings.isSMLEnabled());
        assertEquals(aSMLInfo, aSettings.getSMLInfo());
    } finally {
        aSMLInfoMgr.deleteSMLInfo(aSMLInfo.getID());
    }
}
Also used : ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) ISMLInfo(com.helger.peppol.sml.ISMLInfo) ISMLInfoManager(com.helger.phoss.smp.domain.sml.ISMLInfoManager) Test(org.junit.Test)

Example 15 with ISMPSettings

use of com.helger.phoss.smp.settings.ISMPSettings in project phoss-smp by phax.

the class APIExecutorMigrationInboundFromPathPut method migrationInbound.

public static void migrationInbound(@Nonnull final String sServiceGroupID, @Nonnull final String sMigrationKey, @Nonnull final String sLogPrefix, @Nonnull final IRequestWebScopeWithoutResponse aRequestScope, @Nonnull final UnifiedResponse aUnifiedResponse) throws SMPServerException, GeneralSecurityException {
    LOGGER.info(sLogPrefix + "Starting inbound migration for Service Group ID '" + sServiceGroupID + "' and migration key '" + sMigrationKey + "'");
    // Only authenticated user may do so
    final BasicAuthClientCredentials aBasicAuth = getMandatoryAuth(aRequestScope.headers());
    final IUser aOwningUser = SMPUserManagerPhoton.validateUserCredentials(aBasicAuth);
    final ISMPServerAPIDataProvider aDataProvider = new SMPRestDataProvider(aRequestScope, sServiceGroupID);
    final ISMPSettings aSettings = SMPMetaManager.getSettings();
    final ISMLInfo aSMLInfo = aSettings.getSMLInfo();
    final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
    final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
    final ISMPParticipantMigrationManager aParticipantMigrationMgr = SMPMetaManager.getParticipantMigrationMgr();
    if (aSMLInfo == null) {
        throw new SMPPreconditionFailedException("Currently no SML is available. Please select it in the UI at the 'SMP Settings' page", aDataProvider.getCurrentURI());
    }
    if (!aSettings.isSMLEnabled()) {
        throw new SMPPreconditionFailedException("SML Connection is not enabled hence no participant can be migrated", aDataProvider.getCurrentURI());
    }
    final IParticipantIdentifier aParticipantID = aIdentifierFactory.parseParticipantIdentifier(sServiceGroupID);
    if (aParticipantID == null) {
        // Invalid identifier
        throw SMPBadRequestException.failedToParseSG(sServiceGroupID, aDataProvider.getCurrentURI());
    }
    // Check that service group does not exist yet
    if (aServiceGroupMgr.containsSMPServiceGroupWithID(aParticipantID)) {
        throw new SMPBadRequestException("The Service Group '" + sServiceGroupID + "' already exists.", aDataProvider.getCurrentURI());
    }
    if (false) {
        // valid
        if (aParticipantMigrationMgr.containsInboundMigration(aParticipantID)) {
            throw new SMPBadRequestException("The inbound migration of the Service Group '" + sServiceGroupID + "' is already contained.", aDataProvider.getCurrentURI());
        }
    }
    // create the Service Group locally
    try {
        final ManageParticipantIdentifierServiceCaller aCaller = new ManageParticipantIdentifierServiceCaller(aSettings.getSMLInfo());
        aCaller.setSSLSocketFactory(SMPKeyManager.getInstance().createSSLContext().getSocketFactory());
        // SML call
        aCaller.migrate(aParticipantID, sMigrationKey, SMPServerConfiguration.getSMLSMPID());
        LOGGER.info(sLogPrefix + "Successfully migrated '" + aParticipantID.getURIEncoded() + "' in the SML to this SMP using migration key '" + sMigrationKey + "'");
    } catch (final BadRequestFault | InternalErrorFault | NotFoundFault | UnauthorizedFault | ClientTransportException ex) {
        throw new SMPSMLException("Failed to confirm the migration for participant '" + aParticipantID.getURIEncoded() + "' in SML, hence the migration failed." + " Please check the participant identifier and the migration key.", ex);
    }
    // Now create the service group locally (it was already checked that the
    // PID is available on this SMP)
    ISMPServiceGroup aSG = null;
    Exception aCaughtEx = null;
    try {
        // Do not allow any Extension here
        // Do NOT create in SMK/SML
        aSG = aServiceGroupMgr.createSMPServiceGroup(aOwningUser.getID(), aParticipantID, (String) null, false);
    } catch (final Exception ex) {
        aCaughtEx = ex;
    }
    if (aSG != null) {
        LOGGER.info(sLogPrefix + "The new SMP Service Group for participant '" + aParticipantID.getURIEncoded() + "' was successfully created.");
    } else {
        // No exception here
        LOGGER.error(sLogPrefix + "Error creating the new SMP Service Group for participant '" + aParticipantID.getURIEncoded() + "'.", aCaughtEx);
    }
    // Remember internally
    final ISMPParticipantMigration aMigration = aParticipantMigrationMgr.createInboundParticipantMigration(aParticipantID, sMigrationKey);
    if (aMigration != null) {
        LOGGER.info(sLogPrefix + "The participant migration for '" + aParticipantID.getURIEncoded() + "' with migration key '" + sMigrationKey + "' was successfully performed. Please inform the source SMP that the migration was successful.");
    } else {
        // No exception here
        LOGGER.error(sLogPrefix + "Failed to store the participant migration for '" + aParticipantID.getURIEncoded() + "'.");
    }
    final IMicroDocument aResponseDoc = new MicroDocument();
    final IMicroElement eRoot = aResponseDoc.appendElement("migrationInboundResponse");
    eRoot.setAttribute("success", aSG != null && aMigration != null);
    eRoot.setAttribute("serviceGroupCreated", aSG != null);
    eRoot.setAttribute("migrationCreated", aMigration != null);
    final XMLWriterSettings aXWS = new XMLWriterSettings().setIndent(EXMLSerializeIndent.INDENT_AND_ALIGN);
    aUnifiedResponse.setContentAndCharset(MicroWriter.getNodeAsString(aResponseDoc, aXWS), aXWS.getCharset()).setMimeType(new MimeType(CMimeType.APPLICATION_XML).addParameter(CMimeType.PARAMETER_NAME_CHARSET, aXWS.getCharset().name())).disableCaching();
}
Also used : ClientTransportException(com.sun.xml.ws.client.ClientTransportException) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) BadRequestFault(com.helger.peppol.smlclient.participant.BadRequestFault) ISMLInfo(com.helger.peppol.sml.ISMLInfo) NotFoundFault(com.helger.peppol.smlclient.participant.NotFoundFault) SMPSMLException(com.helger.phoss.smp.exception.SMPSMLException) CMimeType(com.helger.commons.mime.CMimeType) MimeType(com.helger.commons.mime.MimeType) IMicroDocument(com.helger.xml.microdom.IMicroDocument) MicroDocument(com.helger.xml.microdom.MicroDocument) ISMPParticipantMigration(com.helger.phoss.smp.domain.pmigration.ISMPParticipantMigration) ISMPServerAPIDataProvider(com.helger.phoss.smp.restapi.ISMPServerAPIDataProvider) IUser(com.helger.photon.security.user.IUser) ISMPParticipantMigrationManager(com.helger.phoss.smp.domain.pmigration.ISMPParticipantMigrationManager) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) XMLWriterSettings(com.helger.xml.serialize.write.XMLWriterSettings) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) ManageParticipantIdentifierServiceCaller(com.helger.peppol.smlclient.ManageParticipantIdentifierServiceCaller) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) SMPSMLException(com.helger.phoss.smp.exception.SMPSMLException) GeneralSecurityException(java.security.GeneralSecurityException) SMPServerException(com.helger.phoss.smp.exception.SMPServerException) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) ClientTransportException(com.sun.xml.ws.client.ClientTransportException) UnauthorizedFault(com.helger.peppol.smlclient.participant.UnauthorizedFault) SMPPreconditionFailedException(com.helger.phoss.smp.exception.SMPPreconditionFailedException) BasicAuthClientCredentials(com.helger.http.basicauth.BasicAuthClientCredentials) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) IMicroElement(com.helger.xml.microdom.IMicroElement) IMicroDocument(com.helger.xml.microdom.IMicroDocument) InternalErrorFault(com.helger.peppol.smlclient.participant.InternalErrorFault) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Aggregations

ISMPSettings (com.helger.phoss.smp.settings.ISMPSettings)22 ISMPServiceGroupManager (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager)12 HCNodeList (com.helger.html.hc.impl.HCNodeList)10 Nonnull (javax.annotation.Nonnull)9 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)8 PDTToString (com.helger.commons.datetime.PDTToString)7 IIdentifierFactory (com.helger.peppolid.factory.IIdentifierFactory)7 HCA (com.helger.html.hc.html.textlevel.HCA)6 ManageParticipantIdentifierServiceCaller (com.helger.peppol.smlclient.ManageParticipantIdentifierServiceCaller)6 ISMPParticipantMigrationManager (com.helger.phoss.smp.domain.pmigration.ISMPParticipantMigrationManager)6 BootstrapButtonToolbar (com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar)6 ISMLInfo (com.helger.peppol.sml.ISMLInfo)5 SMPMetaManager (com.helger.phoss.smp.domain.SMPMetaManager)5 ISMPBusinessCardManager (com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager)5 ISMPServiceGroup (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup)5 BootstrapButton (com.helger.photon.bootstrap4.button.BootstrapButton)5 Locale (java.util.Locale)5 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)4 ICommonsList (com.helger.commons.collection.impl.ICommonsList)4 ISMPBusinessCard (com.helger.phoss.smp.domain.businesscard.ISMPBusinessCard)4