Search in sources :

Example 6 with IUser

use of com.helger.photon.security.user.IUser in project phoss-smp by phax.

the class PageSecureServiceGroupImport method fillContent.

@Override
protected void fillContent(@Nonnull final WebPageExecutionContext aWPEC) {
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final ISMPSettings aSettings = SMPMetaManager.getSettings();
    final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
    final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
    final IUserManager aUserMgr = PhotonSecurityManager.getUserMgr();
    final ICommonsSet<String> aAllServiceGroupIDs = aServiceGroupMgr.getAllSMPServiceGroupIDs();
    final ICommonsSet<String> aAllBusinessCardIDs = aBusinessCardMgr.getAllSMPBusinessCardIDs();
    final FormErrorList aFormErrors = new FormErrorList();
    final HCUL aImportResultUL = new HCUL();
    if (aWPEC.hasAction(CPageParam.ACTION_PERFORM)) {
        // Start import
        final IFileItem aImportFile = aWPEC.params().getAsFileItem(FIELD_IMPORT_FILE);
        final boolean bOverwriteExisting = aWPEC.params().isCheckBoxChecked(FIELD_OVERWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING);
        final String sDefaultOwnerID = aWPEC.params().getAsString(FIELD_DEFAULT_OWNER);
        final IUser aDefaultOwner = aUserMgr.getActiveUserOfID(sDefaultOwnerID);
        if (aImportFile == null || aImportFile.getSize() == 0)
            aFormErrors.addFieldError(FIELD_IMPORT_FILE, "A file to import must be selected!");
        if (StringHelper.hasNoText(sDefaultOwnerID))
            aFormErrors.addFieldError(FIELD_DEFAULT_OWNER, "A default owner must be selected!");
        else if (aDefaultOwner == null)
            aFormErrors.addFieldError(FIELD_DEFAULT_OWNER, "A valid default owner must be selected!");
        if (aFormErrors.isEmpty()) {
            final SAXReaderSettings aSRS = new SAXReaderSettings();
            final IMicroDocument aDoc = MicroReader.readMicroXML(aImportFile, aSRS);
            if (aDoc == null || aDoc.getDocumentElement() == null)
                aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file is not a valid XML file!");
            else {
                // Start interpreting
                final String sVersion = aDoc.getDocumentElement().getAttributeValue(CSMPExchange.ATTR_VERSION);
                if (CSMPExchange.VERSION_10.equals(sVersion)) {
                    // Version 1.0
                    final ICommonsList<ImportActionItem> aActionList = new CommonsArrayList<>();
                    final ImportSummary aImportSummary = new ImportSummary();
                    ServiceGroupImport.importXMLVer10(aDoc.getDocumentElement(), bOverwriteExisting, aDefaultOwner, aAllServiceGroupIDs, aAllBusinessCardIDs, aActionList, aImportSummary);
                    for (final ImportActionItem aAction : aActionList) {
                        final IErrorLevel aErrorLevel = aAction.getErrorLevel();
                        final EBootstrapBadgeType eBadgeType;
                        if (aErrorLevel.isGE(EErrorLevel.ERROR))
                            eBadgeType = EBootstrapBadgeType.DANGER;
                        else if (aErrorLevel.isGE(EErrorLevel.WARN))
                            eBadgeType = EBootstrapBadgeType.WARNING;
                        else if (aErrorLevel.isGE(EErrorLevel.INFO))
                            eBadgeType = EBootstrapBadgeType.INFO;
                        else
                            eBadgeType = EBootstrapBadgeType.SUCCESS;
                        // By default is is centered
                        aImportResultUL.addItem(new BootstrapBadge(eBadgeType).addChild((aAction.hasParticipantID() ? "[" + aAction.getParticipantID() + "] " : "") + aAction.getMessage()).addChild(SMPCommonUI.getTechnicalDetailsUI(aAction.getLinkedException())).addClass(CBootstrapCSS.TEXT_LEFT));
                    }
                } else {
                    // Unsupported or no version present
                    if (sVersion == null)
                        aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file cannot be imported because it has the wrong layout.");
                    else
                        aFormErrors.addFieldError(FIELD_IMPORT_FILE, "The provided file contains the unsupported version '" + sVersion + "'.");
                }
            }
        }
    }
    final boolean bHandleBusinessCards = aSettings.isDirectoryIntegrationEnabled();
    if (aImportResultUL.hasChildren()) {
        final BootstrapCard aPanel = new BootstrapCard();
        aPanel.createAndAddHeader().addChild("Import results");
        aPanel.createAndAddBody().addChild(aImportResultUL);
        aNodeList.addChild(aPanel);
    }
    aNodeList.addChild(info("Import service groups incl. all endpoints" + (bHandleBusinessCards ? " and business cards" : "") + " from a file."));
    final BootstrapForm aForm = aNodeList.addAndReturnChild(getUIHandler().createFormFileUploadSelf(aWPEC));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("File to import").setCtrl(new BootstrapFileUpload(FIELD_IMPORT_FILE, aDisplayLocale)).setErrorList(aFormErrors.getListOfField(FIELD_IMPORT_FILE)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabel("Overwrite existing elements").setCtrl(new HCCheckBox(new RequestFieldBoolean(FIELD_OVERWRITE_EXISTING, DEFAULT_OVERWRITE_EXISTING))).setHelpText("If this box is checked, all existing endpoints etc. of a service group are deleted and new endpoints are created! If the " + SMPWebAppConfiguration.getDirectoryName() + " integration is enabled, existing business cards contained in the import are also overwritten!").setErrorList(aFormErrors.getListOfField(FIELD_OVERWRITE_EXISTING)));
    aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Owner of the new service groups").setCtrl(new HCUserSelect(new RequestField(FIELD_DEFAULT_OWNER), aDisplayLocale)).setHelpText("This owner is only selected, if the owner contained in the import file is unknown.").setErrorList(aFormErrors.getListOfField(FIELD_DEFAULT_OWNER)));
    final BootstrapButtonToolbar aToolbar = aForm.addAndReturnChild(getUIHandler().createToolbar(aWPEC));
    aToolbar.addHiddenField(CPageParam.PARAM_ACTION, CPageParam.ACTION_PERFORM);
    aToolbar.addChild(new BootstrapSubmitButton().addChild("Import Service Groups").setIcon(EDefaultIcon.ADD));
}
Also used : Locale(java.util.Locale) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) HCNodeList(com.helger.html.hc.impl.HCNodeList) IUserManager(com.helger.photon.security.user.IUserManager) ImportSummary(com.helger.phoss.smp.exchange.ImportSummary) RequestFieldBoolean(com.helger.photon.core.form.RequestFieldBoolean) FormErrorList(com.helger.photon.core.form.FormErrorList) ImportActionItem(com.helger.phoss.smp.exchange.ImportActionItem) SAXReaderSettings(com.helger.xml.serialize.read.SAXReaderSettings) BootstrapFileUpload(com.helger.photon.bootstrap4.uictrls.ext.BootstrapFileUpload) IFileItem(com.helger.web.fileupload.IFileItem) IUser(com.helger.photon.security.user.IUser) BootstrapButtonToolbar(com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar) RequestField(com.helger.photon.core.form.RequestField) BootstrapCard(com.helger.photon.bootstrap4.card.BootstrapCard) BootstrapBadge(com.helger.photon.bootstrap4.badge.BootstrapBadge) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) HCUserSelect(com.helger.phoss.smp.ui.secure.hc.HCUserSelect) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) HCUL(com.helger.html.hc.html.grouping.HCUL) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) EBootstrapBadgeType(com.helger.photon.bootstrap4.badge.EBootstrapBadgeType) IErrorLevel(com.helger.commons.error.level.IErrorLevel) IMicroDocument(com.helger.xml.microdom.IMicroDocument) HCCheckBox(com.helger.html.hc.html.forms.HCCheckBox) BootstrapSubmitButton(com.helger.photon.bootstrap4.button.BootstrapSubmitButton) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList)

Example 7 with IUser

use of com.helger.photon.security.user.IUser in project phoss-smp by phax.

the class PageSecureServiceGroupMigrationInbound method validateAndSaveInputParameters.

@Override
protected void validateAndSaveInputParameters(@Nonnull final WebPageExecutionContext aWPEC, @Nullable final ISMPParticipantMigration aSelectedObject, @Nonnull final FormErrorList aFormErrors, @Nonnull final EWebPageFormAction eFormAction) {
    final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
    final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
    final ISMPSettings aSettings = SMPMetaManager.getSettings();
    final ISMPParticipantMigrationManager aParticipantMigrationMgr = SMPMetaManager.getParticipantMigrationMgr();
    final String sMigrationKey = aWPEC.params().getAsStringTrimmed(FIELD_MIGRATION_KEY);
    final String sParticipantIDScheme = aWPEC.params().getAsStringTrimmed(FIELD_PARTICIPANT_ID_SCHEME);
    final String sParticipantIDValue = aWPEC.params().getAsStringTrimmed(FIELD_PARTICIPANT_ID_VALUE);
    IParticipantIdentifier aParticipantID = null;
    final String sOwningUserID = aWPEC.params().getAsStringTrimmed(FIELD_OWNING_USER_ID);
    final IUser aOwningUser = PhotonSecurityManager.getUserMgr().getUserOfID(sOwningUserID);
    final String sExtension = aWPEC.params().getAsStringTrimmed(FIELD_EXTENSION);
    // validations
    if (StringHelper.hasNoText(sMigrationKey))
        aFormErrors.addFieldError(FIELD_MIGRATION_KEY, "The migration key must not be empty!");
    else if (!SMPParticipantMigration.isValidMigrationKey(sMigrationKey))
        aFormErrors.addFieldError(FIELD_MIGRATION_KEY, "The migration key is not valid. Please verify the received code is correct.");
    if (aIdentifierFactory.isParticipantIdentifierSchemeMandatory() && StringHelper.hasNoText(sParticipantIDScheme))
        aFormErrors.addFieldError(FIELD_PARTICIPANT_ID_SCHEME, "Participant ID scheme must not be empty!");
    else if (StringHelper.hasNoText(sParticipantIDValue))
        aFormErrors.addFieldError(FIELD_PARTICIPANT_ID_VALUE, "Participant ID value must not be empty!");
    else {
        aParticipantID = aIdentifierFactory.createParticipantIdentifier(sParticipantIDScheme, sParticipantIDValue);
        if (aParticipantID == null)
            aFormErrors.addFieldError(FIELD_PARTICIPANT_ID_VALUE, "The provided participant ID has an invalid syntax!");
        else if (aServiceGroupMgr.getSMPServiceGroupOfID(aParticipantID) != null)
            aFormErrors.addFieldError(FIELD_PARTICIPANT_ID_VALUE, "Another service group for the same participant ID is already present (may be case insensitive)!");
    }
    if (StringHelper.hasNoText(sOwningUserID))
        aFormErrors.addFieldError(FIELD_OWNING_USER_ID, "Owning User must not be empty!");
    else if (aOwningUser == null)
        aFormErrors.addFieldError(FIELD_OWNING_USER_ID, "Provided owning user does not exist!");
    if (StringHelper.hasText(sExtension)) {
        final IMicroDocument aDoc = MicroReader.readMicroXML(sExtension);
        if (aDoc == null)
            aFormErrors.addFieldError(FIELD_EXTENSION, "The extension must be XML content.");
    }
    final HCNodeList aRedirectNotes = new HCNodeList();
    if (aFormErrors.isEmpty()) {
        // 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("Successfully migrated '" + aParticipantID.getURIEncoded() + "' in the SML to this SMP using migration key '" + sMigrationKey + "'");
            aRedirectNotes.addChild(success("Successfully migrated '" + aParticipantID.getURIEncoded() + "' in SML to this SMP using migration key ").addChild(code(sMigrationKey)));
        } catch (final Exception ex) {
            LOGGER.error("Error invoking migrate on SML", ex);
            // Use a global field error here, to avoid that users must enter the
            // values over and over in case of error
            aFormErrors.add(SingleError.builderError().errorText("Failed to confirm the migration for participant '" + aParticipantID.getURIEncoded() + "' in SML, hence the migration failed." + " Please check the participant identifier and the migration key.\n" + BootstrapTechnicalUI.getTechnicalDetailsString(ex, CSMPServer.DEFAULT_LOCALE)).build());
            if (false)
                aWPEC.postRedirectGetInternal(error("Failed to confirm the migration for participant '" + aParticipantID.getURIEncoded() + "' in SML, hence the migration failed." + " Please check the participant identifier and the migration key.").addChild(SMPCommonUI.getTechnicalDetailsUI(ex)));
        }
    }
    if (aFormErrors.isEmpty()) {
        // 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 create in SMK/SML
            aSG = aServiceGroupMgr.createSMPServiceGroup(aOwningUser.getID(), aParticipantID, sExtension, false);
        } catch (final Exception ex) {
            aCaughtEx = ex;
        }
        if (aSG != null) {
            aRedirectNotes.addChild(success("The new SMP Service Group for participant '" + aParticipantID.getURIEncoded() + "' was successfully created."));
        } else {
            aRedirectNotes.addChild(error("Error creating the new SMP Service Group for participant '" + aParticipantID.getURIEncoded() + "'.").addChild(SMPCommonUI.getTechnicalDetailsUI(aCaughtEx)));
        }
        // Remember internally
        if (aParticipantMigrationMgr.createInboundParticipantMigration(aParticipantID, sMigrationKey) != null) {
            aRedirectNotes.addChild(success().addChild(div("The participant migration for '" + aParticipantID.getURIEncoded() + "' with migration key ").addChild(code(sMigrationKey)).addChild(" was successfully performed.")).addChild(div("Please inform the source SMP that the migration was successful.")));
        } else {
            aRedirectNotes.addChild(error("Failed to store the participant migration for '" + aParticipantID.getURIEncoded() + "'."));
        }
        aWPEC.postRedirectGetInternal(aRedirectNotes);
    }
}
Also used : ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) HCNodeList(com.helger.html.hc.impl.HCNodeList) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) IUser(com.helger.photon.security.user.IUser) ISMPParticipantMigrationManager(com.helger.phoss.smp.domain.pmigration.ISMPParticipantMigrationManager) PDTToString(com.helger.commons.datetime.PDTToString) IMicroDocument(com.helger.xml.microdom.IMicroDocument) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) ManageParticipantIdentifierServiceCaller(com.helger.peppol.smlclient.ManageParticipantIdentifierServiceCaller) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 8 with IUser

use of com.helger.photon.security.user.IUser in project phoss-smp by phax.

the class SMPRendererSecure method _getNavbar.

@Nonnull
private static IHCNode _getNavbar(@Nonnull final ILayoutExecutionContext aLEC) {
    final Locale aDisplayLocale = aLEC.getDisplayLocale();
    final IRequestWebScopeWithoutResponse aRequestScope = aLEC.getRequestScope();
    final ISimpleURL aLinkToStartPage = aLEC.getLinkToMenuItem(aLEC.getMenuTree().getDefaultMenuItemID());
    final BootstrapNavbar aNavbar = new BootstrapNavbar();
    aNavbar.addBrand(SMPRendererPublic.createLogo(aLEC), aLinkToStartPage);
    aNavbar.addBrand(new HCSpan().addChild(CSMP.getApplicationSuffix() + " Administration"), aLinkToStartPage);
    aNavbar.addAndReturnText().addChild(" [" + SMPServerConfiguration.getSMLSMPID() + "]");
    final BootstrapNavbarToggleable aToggleable = aNavbar.addAndReturnToggleable();
    {
        aToggleable.addChild(new BootstrapButton().addClass(CBootstrapCSS.ML_AUTO).addClass(CBootstrapCSS.MR_2).setOnClick(LinkHelper.getURLWithContext(AbstractPublicApplicationServlet.SERVLET_DEFAULT_PATH + "/")).addChild("Goto public view"));
        final IUser aUser = aLEC.getLoggedInUser();
        aToggleable.addAndReturnText().addClass(CBootstrapCSS.MX_2).addChild("Logged in as ").addChild(new HCStrong().addChild(SecurityHelper.getUserDisplayName(aUser, aDisplayLocale)));
        aToggleable.addChild(new BootstrapButton().addClass(CBootstrapCSS.MX_2).setOnClick(LinkHelper.getURLWithContext(aRequestScope, LogoutServlet.SERVLET_DEFAULT_PATH)).addChild(EPhotonCoreText.LOGIN_LOGOUT.getDisplayText(aDisplayLocale)));
    }
    return aNavbar;
}
Also used : Locale(java.util.Locale) IRequestWebScopeWithoutResponse(com.helger.web.scope.IRequestWebScopeWithoutResponse) HCSpan(com.helger.html.hc.html.textlevel.HCSpan) HCStrong(com.helger.html.hc.html.textlevel.HCStrong) BootstrapNavbar(com.helger.photon.bootstrap4.navbar.BootstrapNavbar) ISimpleURL(com.helger.commons.url.ISimpleURL) BootstrapNavbarToggleable(com.helger.photon.bootstrap4.navbar.BootstrapNavbarToggleable) IUser(com.helger.photon.security.user.IUser) BootstrapButton(com.helger.photon.bootstrap4.button.BootstrapButton) Nonnull(javax.annotation.Nonnull)

Example 9 with IUser

use of com.helger.photon.security.user.IUser 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 10 with IUser

use of com.helger.photon.security.user.IUser in project phoss-smp by phax.

the class BDXR1ServerAPI method deleteServiceGroup.

@Nonnull
public EChange deleteServiceGroup(@Nonnull final String sPathServiceGroupID, final boolean bDeleteInSML, @Nonnull final BasicAuthClientCredentials aCredentials) throws SMPServerException {
    final String sLog = LOG_PREFIX + "DELETE /" + sPathServiceGroupID + (bDeleteInSML ? "" : CSMPServer.LOG_SUFFIX_NO_SML_INTERACTION);
    final String sAction = "deleteServiceGroup";
    if (LOGGER.isInfoEnabled())
        LOGGER.info(sLog);
    STATS_COUNTER_INVOCATION.increment(sAction);
    try {
        final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
        final IParticipantIdentifier aPathServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sPathServiceGroupID);
        if (aPathServiceGroupID == null) {
            // Invalid identifier
            throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, m_aAPIDataProvider.getCurrentURI());
        }
        final IUser aSMPUser = SMPUserManagerPhoton.validateUserCredentials(aCredentials);
        SMPUserManagerPhoton.verifyOwnership(aPathServiceGroupID, aSMPUser);
        final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
        final EChange eDeleted = aServiceGroupMgr.deleteSMPServiceGroup(aPathServiceGroupID, bDeleteInSML);
        if (LOGGER.isInfoEnabled())
            LOGGER.info(sLog + " SUCCESS");
        STATS_COUNTER_SUCCESS.increment(sAction);
        return eDeleted;
    } catch (final SMPServerException ex) {
        if (LOGGER.isWarnEnabled())
            LOGGER.warn(sLog + " ERROR - " + ex.getMessage());
        STATS_COUNTER_ERROR.increment(sAction);
        throw ex;
    }
}
Also used : ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) IUser(com.helger.photon.security.user.IUser) EChange(com.helger.commons.state.EChange) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) SMPServerException(com.helger.phoss.smp.exception.SMPServerException) Nonnull(javax.annotation.Nonnull)

Aggregations

IUser (com.helger.photon.security.user.IUser)44 ISMPServiceGroupManager (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager)25 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)22 IIdentifierFactory (com.helger.peppolid.factory.IIdentifierFactory)20 ISMPServiceGroup (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup)19 Nonnull (javax.annotation.Nonnull)18 SMPServerException (com.helger.phoss.smp.exception.SMPServerException)17 Locale (java.util.Locale)14 ISMPRedirectManager (com.helger.phoss.smp.domain.redirect.ISMPRedirectManager)11 IRequestWebScopeWithoutResponse (com.helger.web.scope.IRequestWebScopeWithoutResponse)9 IDocumentTypeIdentifier (com.helger.peppolid.IDocumentTypeIdentifier)8 BootstrapButton (com.helger.photon.bootstrap4.button.BootstrapButton)8 HCStrong (com.helger.html.hc.html.textlevel.HCStrong)7 HCNodeList (com.helger.html.hc.impl.HCNodeList)7 ISMPRedirect (com.helger.phoss.smp.domain.redirect.ISMPRedirect)7 ISMPServiceInformationManager (com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager)7 SMPBadRequestException (com.helger.phoss.smp.exception.SMPBadRequestException)7 SMPNotFoundException (com.helger.phoss.smp.exception.SMPNotFoundException)7 IUserManager (com.helger.photon.security.user.IUserManager)7 IMicroDocument (com.helger.xml.microdom.IMicroDocument)6