Search in sources :

Example 1 with ICommonsSet

use of com.helger.commons.collection.impl.ICommonsSet in project ph-masterdata by phax.

the class ECurrencyTest method testGetMissingCurrencies.

@Test
@Ignore
public void testGetMissingCurrencies() {
    final ICommonsMap<Locale, Currency> aMap = CurrencyHelper.getLocaleToCurrencyMap();
    final ICommonsMap<Currency, ICommonsSet<Locale>> aAllOfCurrency = new CommonsHashMap<>();
    for (final Map.Entry<Locale, Currency> aEntry : aMap.entrySet()) {
        if (ECurrency.findFirst(ECurrency.filterContainsLocale(aEntry.getKey())) == null) {
            aAllOfCurrency.computeIfAbsent(aEntry.getValue(), k -> new CommonsHashSet<>()).add(aEntry.getKey());
        }
    }
    final StringBuilder aSB = new StringBuilder();
    for (final Map.Entry<Currency, ICommonsSet<Locale>> a : aAllOfCurrency.getSortedByKey(Comparator.comparing(Currency::getCurrencyCode)).entrySet()) {
        final StringBuilder aLocale = new StringBuilder();
        for (final Locale aLoc : a.getValue().getSorted(Comparator.comparing(Locale::toString))) {
            if (aLocale.length() > 0)
                aLocale.append(',');
            aLocale.append('"').append(aLoc.toString()).append('"');
        }
        final String sID = a.getKey().getCurrencyCode();
        aSB.append(sID + " (Currency.getInstance (\"" + sID + "\"), ECurrencyName." + sID + ", " + aLocale.toString() + "),");
    }
    LOGGER.info(aSB.toString());
}
Also used : Locale(java.util.Locale) Logger(org.slf4j.Logger) ICommonsSet(com.helger.commons.collection.impl.ICommonsSet) Assert.assertNotNull(org.junit.Assert.assertNotNull) LoggerFactory(org.slf4j.LoggerFactory) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Currency(java.util.Currency) EqualsHelper(com.helger.commons.equals.EqualsHelper) Assert.assertSame(org.junit.Assert.assertSame) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) Ignore(org.junit.Ignore) CommonsHashSet(com.helger.commons.collection.impl.CommonsHashSet) CountryCache(com.helger.commons.locale.country.CountryCache) Assert.assertFalse(org.junit.Assert.assertFalse) Locale(java.util.Locale) Map(java.util.Map) EContinent(com.helger.masterdata.locale.EContinent) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) Comparator(java.util.Comparator) Assert.assertEquals(org.junit.Assert.assertEquals) ICommonsSet(com.helger.commons.collection.impl.ICommonsSet) Currency(java.util.Currency) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) Map(java.util.Map) ICommonsMap(com.helger.commons.collection.impl.ICommonsMap) CommonsHashSet(com.helger.commons.collection.impl.CommonsHashSet) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 2 with ICommonsSet

use of com.helger.commons.collection.impl.ICommonsSet in project phoss-smp by phax.

the class PageSecureEndpointChangeURL method fillContent.

@Override
protected void fillContent(@Nonnull final WebPageExecutionContext aWPEC) {
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final HCNodeList aNodeList = aWPEC.getNodeList();
    final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
    final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
    final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
    boolean bShowList = true;
    final ICommonsMap<String, ICommonsList<ISMPEndpoint>> aEndpointsGroupedPerURL = new CommonsHashMap<>();
    final ICommonsMap<String, ICommonsSet<ISMPServiceGroup>> aServiceGroupsGroupedPerURL = new CommonsHashMap<>();
    final ICommonsList<ISMPServiceInformation> aAllSIs = aServiceInfoMgr.getAllSMPServiceInformation();
    int nTotalEndpointCount = 0;
    int nTotalEndpointCountWithURL = 0;
    for (final ISMPServiceInformation aSI : aAllSIs) {
        final ISMPServiceGroup aSG = aSI.getServiceGroup();
        for (final ISMPProcess aProcess : aSI.getAllProcesses()) for (final ISMPEndpoint aEndpoint : aProcess.getAllEndpoints()) {
            ++nTotalEndpointCount;
            if (aEndpoint.hasEndpointReference()) {
                aEndpointsGroupedPerURL.computeIfAbsent(aEndpoint.getEndpointReference(), k -> new CommonsArrayList<>()).add(aEndpoint);
                aServiceGroupsGroupedPerURL.computeIfAbsent(aEndpoint.getEndpointReference(), k -> new CommonsHashSet<>()).add(aSG);
                ++nTotalEndpointCountWithURL;
            }
        }
    }
    {
        final BootstrapButtonToolbar aToolbar = new BootstrapButtonToolbar(aWPEC);
        aToolbar.addButton("Refresh", aWPEC.getSelfHref(), EDefaultIcon.REFRESH);
        aNodeList.addChild(aToolbar);
        final int nCount = BulkChangeEndpointURL.getRunningJobCount();
        if (nCount > 0) {
            aNodeList.addChild(warn((nCount == 1 ? "1 bulk change is" : nCount + " bulk changes are") + " currently running in the background"));
        }
    }
    if (aWPEC.hasAction(CPageParam.ACTION_EDIT)) {
        bShowList = false;
        final FormErrorList aFormErrors = new FormErrorList();
        final String sOldURL = aWPEC.params().getAsString(FIELD_OLD_URL);
        if (aWPEC.hasSubAction(CPageParam.ACTION_SAVE)) {
            // Find selected service group (if any)
            final String sServiceGroupID = aWPEC.params().getAsString(FIELD_SERVICE_GROUP);
            ISMPServiceGroup aServiceGroup = null;
            if (StringHelper.hasText(sServiceGroupID)) {
                final IParticipantIdentifier aParticipantID = aIdentifierFactory.parseParticipantIdentifier(sServiceGroupID);
                if (aParticipantID != null)
                    aServiceGroup = aServiceGroupMgr.getSMPServiceGroupOfID(aParticipantID);
            }
            final String sNewURL = aWPEC.params().getAsString(FIELD_NEW_URL);
            if (StringHelper.hasNoText(sOldURL))
                aFormErrors.addFieldInfo(FIELD_OLD_URL, "An old URL must be provided");
            else if (!URLValidator.isValid(sOldURL))
                aFormErrors.addFieldInfo(FIELD_OLD_URL, "The old URL is invalid");
            if (StringHelper.hasNoText(sNewURL))
                aFormErrors.addFieldInfo(FIELD_NEW_URL, "A new URL must be provided");
            else if (!URLValidator.isValid(sNewURL))
                aFormErrors.addFieldInfo(FIELD_NEW_URL, "The new URL is invalid");
            else if (sNewURL.equals(sOldURL))
                aFormErrors.addFieldInfo(FIELD_NEW_URL, "The new URL is identical to the old URL");
            // Validate parameters
            if (aFormErrors.isEmpty()) {
                PhotonWorkerPool.getInstance().run("BulkChangeEndpointURL", new BulkChangeEndpointURL(aAllSIs, aServiceGroup, sOldURL, sNewURL));
                aWPEC.postRedirectGetInternal(success("The bulk change of the endpoint URL from '" + sOldURL + "' to '" + sNewURL + "' is now running in the background. Please manually refresh the page to see the update."));
            }
        }
        final ICommonsSet<ISMPServiceGroup> aServiceGroups = aServiceGroupsGroupedPerURL.get(sOldURL);
        final int nSGCount = CollectionHelper.getSize(aServiceGroups);
        final int nEPCount = CollectionHelper.getSize(aEndpointsGroupedPerURL.get(sOldURL));
        aNodeList.addChild(info("The selected old URL '" + sOldURL + "' is currently used in " + nEPCount + " " + (nEPCount == 1 ? "endpoint" : "endpoints") + " of " + nSGCount + " " + (nSGCount == 1 ? "service group" : "service groups") + "."));
        // Show edit screen
        final BootstrapForm aForm = aNodeList.addAndReturnChild(getUIHandler().createFormSelf(aWPEC));
        aForm.addChild(new HCHiddenField(CPageParam.PARAM_ACTION, CPageParam.ACTION_EDIT));
        aForm.addChild(new HCHiddenField(CPageParam.PARAM_SUBACTION, CPageParam.ACTION_SAVE));
        if (nSGCount > 1) {
            // Select the affected service groups if more than one is available
            final HCSelect aSGSelect = new HCSelect(new RequestField(FIELD_SERVICE_GROUP));
            aSGSelect.addOption(SERVICE_GROUP_ALL, "All affected Service Groups");
            if (aServiceGroups != null)
                for (final ISMPServiceGroup aSG : aServiceGroups.getSorted(ISMPServiceGroup.comparator())) aSGSelect.addOption(aSG.getID(), aSG.getParticipantIdentifier().getURIEncoded());
            aForm.addFormGroup(new BootstrapFormGroup().setLabel("Service group").setCtrl(aSGSelect).setHelpText("If a specific service group is selected, the URL change will only happen in the endpoints of the selected service group. Othwerwise the endpoint is changed in ALL service groups with matching endpoints.").setErrorList(aFormErrors.getListOfField(FIELD_OLD_URL)));
        } else {
            // If less than 2 service groups are affected, use the 0/1
            // automatically.
            aForm.addChild(new HCHiddenField(FIELD_SERVICE_GROUP, SERVICE_GROUP_ALL));
        }
        aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Old endpoint URL").setCtrl(new HCEdit(new RequestField(FIELD_OLD_URL, sOldURL))).setHelpText("The old URL that is to be changed in all matching endpoints").setErrorList(aFormErrors.getListOfField(FIELD_OLD_URL)));
        aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("New endpoint URL").setCtrl(new HCEdit(new RequestField(FIELD_NEW_URL, sOldURL))).setHelpText("The new URL that is used instead").setErrorList(aFormErrors.getListOfField(FIELD_NEW_URL)));
        final BootstrapButtonToolbar aToolbar = aForm.addAndReturnChild(getUIHandler().createToolbar(aWPEC));
        aToolbar.addSubmitButton("Save changes", EDefaultIcon.SAVE);
        aToolbar.addButtonCancel(aDisplayLocale);
    }
    if (bShowList) {
        aNodeList.addChild(info().addChildren(div("This page lets you change the URLs of multiple endpoints at once. This is e.g. helpful when the underlying server got a new URL."), div("Currently " + (nTotalEndpointCount == 1 ? "1 endpoint is" : nTotalEndpointCount + " endpoints are") + " registered" + (nTotalEndpointCountWithURL < nTotalEndpointCount ? " of which " + nTotalEndpointCountWithURL + " have an endpoint reference" : "") + ".")));
        final HCTable aTable = new HCTable(new DTCol("Endpoint URL").setInitialSorting(ESortOrder.ASCENDING), new DTCol("Service Group Count").setDisplayType(EDTColType.INT, aDisplayLocale), new DTCol("Endpoint Count").setDisplayType(EDTColType.INT, aDisplayLocale), new BootstrapDTColAction(aDisplayLocale)).setID(getID());
        aEndpointsGroupedPerURL.forEach((sURL, aEndpoints) -> {
            final HCRow aRow = aTable.addBodyRow();
            aRow.addCell(sURL);
            final int nSGCount = CollectionHelper.getSize(aServiceGroupsGroupedPerURL.get(sURL));
            aRow.addCell(Integer.toString(nSGCount));
            aRow.addCell(Integer.toString(aEndpoints.size()));
            final ISimpleURL aEditURL = aWPEC.getSelfHref().add(CPageParam.PARAM_ACTION, CPageParam.ACTION_EDIT).add(FIELD_OLD_URL, sURL);
            aRow.addCell(new HCA(aEditURL).setTitle("Change all endpoints pointing to " + sURL).addChild(EDefaultIcon.EDIT.getAsNode()));
        });
        final DataTables aDataTables = BootstrapDataTables.createDefaultDataTables(aWPEC, aTable);
        aNodeList.addChild(aTable).addChild(aDataTables);
    }
}
Also used : Locale(java.util.Locale) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) ICommonsList(com.helger.commons.collection.impl.ICommonsList) HCNodeList(com.helger.html.hc.impl.HCNodeList) FormErrorList(com.helger.photon.core.form.FormErrorList) HCEdit(com.helger.html.hc.html.forms.HCEdit) HCRow(com.helger.html.hc.html.tabular.HCRow) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ISimpleURL(com.helger.commons.url.ISimpleURL) BootstrapDTColAction(com.helger.photon.bootstrap4.uictrls.datatables.BootstrapDTColAction) BootstrapButtonToolbar(com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) ISMPProcess(com.helger.phoss.smp.domain.serviceinfo.ISMPProcess) BootstrapDataTables(com.helger.photon.bootstrap4.uictrls.datatables.BootstrapDataTables) DataTables(com.helger.photon.uictrls.datatables.DataTables) RequestField(com.helger.photon.core.form.RequestField) ISMPServiceInformationManager(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager) HCHiddenField(com.helger.html.hc.html.forms.HCHiddenField) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) HCA(com.helger.html.hc.html.textlevel.HCA) ISMPEndpoint(com.helger.phoss.smp.domain.serviceinfo.ISMPEndpoint) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) HCSelect(com.helger.html.hc.html.forms.HCSelect) ISMPEndpoint(com.helger.phoss.smp.domain.serviceinfo.ISMPEndpoint) SMPEndpoint(com.helger.phoss.smp.domain.serviceinfo.SMPEndpoint) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) HCTable(com.helger.html.hc.html.tabular.HCTable) ICommonsSet(com.helger.commons.collection.impl.ICommonsSet) DTCol(com.helger.photon.uictrls.datatables.column.DTCol) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 3 with ICommonsSet

use of com.helger.commons.collection.impl.ICommonsSet in project phoss-smp by phax.

the class PageSecureServiceGroupMigrationOutbound method showInputForm.

@Override
protected void showInputForm(@Nonnull final WebPageExecutionContext aWPEC, @Nullable final ISMPParticipantMigration aSelectedObject, @Nonnull final BootstrapForm aForm, final boolean bIsFormSubmitted, @Nonnull final EWebPageFormAction eFormAction, @Nonnull final FormErrorList aFormErrors) {
    final Locale aDisplayLocale = aWPEC.getDisplayLocale();
    final ISMPParticipantMigrationManager aParticipantMigrationMgr = SMPMetaManager.getParticipantMigrationMgr();
    // State is filtered below
    final ICommonsList<ISMPParticipantMigration> aExistingOutgoingMigrations = aParticipantMigrationMgr.getAllOutboundParticipantMigrations(null);
    // Get all participant identifiers for which NO new migration can be
    // initiated (because they were already migrated or migration is currently
    // in progress)
    final ICommonsSet<IParticipantIdentifier> aPIDsThatCannotBeUsed = new CommonsHashSet<>();
    aPIDsThatCannotBeUsed.addAllMapped(aExistingOutgoingMigrations, x -> x.getState().preventsNewMigration(), ISMPParticipantMigration::getParticipantIdentifier);
    // Filter out all for which it makes no sense
    final HCServiceGroupSelect aSGSelect = new HCServiceGroupSelect(new RequestField(FIELD_PARTICIPANT_ID), aDisplayLocale, x -> aPIDsThatCannotBeUsed.containsNone(y -> x.getParticipantIdentifier().hasSameContent(y)));
    if (!aSGSelect.containsAnyServiceGroup()) {
        aForm.addChild(warn("No Service Group on this SMP can currently be migrated."));
    } else {
        aForm.addChild(getUIHandler().createActionHeader("Start a Participant Migration from this SMP to another SMP"));
        aForm.addFormGroup(new BootstrapFormGroup().setLabelMandatory("Service Group").setCtrl(aSGSelect).setHelpText("Select the Service Group to migrate to another SMP. Each Service Group can only be migrated once from this SMP. Only Service Groups registered to the SML can be migrated.").setErrorList(aFormErrors.getListOfField(FIELD_PARTICIPANT_ID)));
    }
}
Also used : Locale(java.util.Locale) HCOL(com.helger.html.hc.html.grouping.HCOL) WebPageExecutionContext(com.helger.photon.uicore.page.WebPageExecutionContext) EDefaultIcon(com.helger.photon.uicore.icon.EDefaultIcon) ISMPSettings(com.helger.phoss.smp.settings.ISMPSettings) LoggerFactory(org.slf4j.LoggerFactory) BootstrapButtonToolbar(com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar) AbstractBootstrapWebPageActionHandlerDelete(com.helger.photon.bootstrap4.pages.handler.AbstractBootstrapWebPageActionHandlerDelete) FormErrorList(com.helger.photon.core.form.FormErrorList) BootstrapForm(com.helger.photon.bootstrap4.form.BootstrapForm) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) ICommonsIterable(com.helger.commons.collection.impl.ICommonsIterable) HCServiceGroupSelect(com.helger.phoss.smp.ui.secure.hc.HCServiceGroupSelect) Nonempty(com.helger.commons.annotation.Nonempty) BootstrapDataTables(com.helger.photon.bootstrap4.uictrls.datatables.BootstrapDataTables) Locale(java.util.Locale) HCA(com.helger.html.hc.html.textlevel.HCA) BootstrapDTColAction(com.helger.photon.bootstrap4.uictrls.datatables.BootstrapDTColAction) CPageParam(com.helger.photon.uicore.css.CPageParam) ISMPParticipantMigrationManager(com.helger.phoss.smp.domain.pmigration.ISMPParticipantMigrationManager) SMPCommonUI(com.helger.phoss.smp.ui.SMPCommonUI) PDTToString(com.helger.commons.datetime.PDTToString) BootstrapViewForm(com.helger.photon.bootstrap4.form.BootstrapViewForm) BootstrapTabBox(com.helger.photon.bootstrap4.nav.BootstrapTabBox) IHCCell(com.helger.html.hc.html.tabular.IHCCell) EWebPageFormAction(com.helger.photon.uicore.page.EWebPageFormAction) BootstrapButton(com.helger.photon.bootstrap4.button.BootstrapButton) ICommonsList(com.helger.commons.collection.impl.ICommonsList) DTCol(com.helger.photon.uictrls.datatables.column.DTCol) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) ManageParticipantIdentifierServiceCaller(com.helger.peppol.smlclient.ManageParticipantIdentifierServiceCaller) ICommonsSet(com.helger.commons.collection.impl.ICommonsSet) DataTables(com.helger.photon.uictrls.datatables.DataTables) HCRow(com.helger.html.hc.html.tabular.HCRow) EValidity(com.helger.commons.state.EValidity) AbstractSMPWebPageForm(com.helger.phoss.smp.ui.AbstractSMPWebPageForm) IHCNode(com.helger.html.hc.IHCNode) EParticipantMigrationState(com.helger.phoss.smp.domain.pmigration.EParticipantMigrationState) SMPKeyManager(com.helger.phoss.smp.security.SMPKeyManager) EDTColType(com.helger.photon.uictrls.datatables.column.EDTColType) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) ISimpleURL(com.helger.commons.url.ISimpleURL) HCNodeList(com.helger.html.hc.impl.HCNodeList) BootstrapWarnBox(com.helger.photon.bootstrap4.alert.BootstrapWarnBox) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) Logger(org.slf4j.Logger) StringHelper(com.helger.commons.string.StringHelper) ISMPParticipantMigration(com.helger.phoss.smp.domain.pmigration.ISMPParticipantMigration) HCTable(com.helger.html.hc.html.tabular.HCTable) SMPMetaManager(com.helger.phoss.smp.domain.SMPMetaManager) RequestField(com.helger.photon.core.form.RequestField) CommonsHashSet(com.helger.commons.collection.impl.CommonsHashSet) SMPServerConfiguration(com.helger.phoss.smp.SMPServerConfiguration) ESortOrder(com.helger.commons.compare.ESortOrder) AbstractBootstrapWebPageActionHandlerWithQuery(com.helger.photon.bootstrap4.pages.handler.AbstractBootstrapWebPageActionHandlerWithQuery) ISMPParticipantMigration(com.helger.phoss.smp.domain.pmigration.ISMPParticipantMigration) HCServiceGroupSelect(com.helger.phoss.smp.ui.secure.hc.HCServiceGroupSelect) ISMPParticipantMigrationManager(com.helger.phoss.smp.domain.pmigration.ISMPParticipantMigrationManager) BootstrapFormGroup(com.helger.photon.bootstrap4.form.BootstrapFormGroup) CommonsHashSet(com.helger.commons.collection.impl.CommonsHashSet) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) RequestField(com.helger.photon.core.form.RequestField)

Example 4 with ICommonsSet

use of com.helger.commons.collection.impl.ICommonsSet 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 5 with ICommonsSet

use of com.helger.commons.collection.impl.ICommonsSet in project ph-web by phax.

the class MailTransport method send.

/**
 * Actually send the given array of MimeMessages via JavaMail.
 *
 * @param aAllMessages
 *        Email data objects to send. May be <code>null</code>.
 * @return A non-<code>null</code> map of the failed messages
 */
@Nonnull
public ICommonsOrderedMap<IMutableEmailData, MailTransportError> send(@Nullable final Collection<IMutableEmailData> aAllMessages) {
    final ICommonsOrderedMap<IMutableEmailData, MailTransportError> aFailedMessages = new CommonsLinkedHashMap<>();
    if (aAllMessages != null) {
        final ICommonsList<IMutableEmailData> aRemainingMessages = new CommonsArrayList<>(aAllMessages);
        MailSendException aExceptionToBeRemembered = null;
        try (final Transport aTransport = m_aSession.getTransport(m_bSMTPS ? SMTPS_PROTOCOL : SMTP_PROTOCOL)) {
            // Add global listeners (if present)
            for (final ConnectionListener aConnectionListener : EmailGlobalSettings.getAllConnectionListeners()) aTransport.addConnectionListener(aConnectionListener);
            // Check if a detailed listener is present
            final ICommonsList<IEmailDataTransportListener> aEmailDataTransportListeners = EmailGlobalSettings.getAllEmailDataTransportListeners();
            // Connect
            aTransport.connect(m_aSMTPSettings.getHostName(), m_aSMTPSettings.getPort(), m_aSMTPSettings.getUserName(), m_aSMTPSettings.getPassword());
            // For all messages
            for (final IMutableEmailData aEmailData : aAllMessages) {
                final MimeMessage aMimeMessage = new MimeMessage(m_aSession);
                try {
                    // convert from IEmailData to MimeMessage
                    MailConverter.fillMimeMessage(aMimeMessage, aEmailData, m_aSMTPSettings.getCharsetObj());
                    // Ensure a sent date is present
                    if (aMimeMessage.getSentDate() == null)
                        aMimeMessage.setSentDate(new Date());
                    // Get an explicitly specified message ID
                    final String sMessageID = aMimeMessage.getMessageID();
                    // This creates a new message ID (besides other things)
                    aMimeMessage.saveChanges();
                    if (sMessageID != null) {
                        // Preserve explicitly specified message id...
                        aMimeMessage.setHeader(HEADER_MESSAGE_ID, sMessageID);
                    }
                    aMimeMessage.setHeader(HEADER_X_MAILER, X_MAILER);
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Delivering mail from " + Arrays.toString(aMimeMessage.getFrom()) + " to " + Arrays.toString(aMimeMessage.getAllRecipients()) + " with subject '" + aMimeMessage.getSubject() + "' and message ID '" + aMimeMessage.getMessageID() + "'");
                    // Main transmit - always throws an exception
                    aTransport.sendMessage(aMimeMessage, aMimeMessage.getAllRecipients());
                    throw new IllegalStateException("Never expected to come beyong sendMessage!");
                } catch (final SendFailedException ex) {
                    if (EmailGlobalSettings.isDebugSMTP())
                        LOGGER.error("Error send mail - SendFailedException", ex);
                    /*
             * Extract all addresses: the valid addresses to which the message
             * was sent, the valid address to which the message was not sent and
             * the invalid addresses
             */
                    final ICommonsSet<String> aValidSent = new CommonsHashSet<>(ex.getValidSentAddresses(), Address::toString);
                    final ICommonsSet<String> aValidUnsent = new CommonsHashSet<>(ex.getValidUnsentAddresses(), Address::toString);
                    final ICommonsSet<String> aInvalid = new CommonsHashSet<>(ex.getInvalidAddresses(), Address::toString);
                    final ICommonsList<MailSendDetails> aDetails = new CommonsArrayList<>();
                    Exception ex2;
                    MessagingException bex = ex;
                    while ((ex2 = bex.getNextException()) != null && ex2 instanceof MessagingException) {
                        if (ex2 instanceof SMTPAddressFailedException) {
                            final SMTPAddressFailedException ssfe = (SMTPAddressFailedException) ex2;
                            aDetails.add(new MailSendDetails(false, ssfe.getAddress().toString(), ssfe.getCommand(), ssfe.getMessage().trim(), ESMTPErrorCode.getFromIDOrDefault(ssfe.getReturnCode(), ESMTPErrorCode.FALLBACK)));
                        } else if (ex2 instanceof SMTPAddressSucceededException) {
                            final SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) ex2;
                            aDetails.add(new MailSendDetails(true, ssfe.getAddress().toString(), ssfe.getCommand(), ssfe.getMessage().trim(), ESMTPErrorCode.getFromIDOrDefault(ssfe.getReturnCode(), ESMTPErrorCode.FALLBACK)));
                        }
                        bex = (MessagingException) ex2;
                    }
                    // Map addresses to details
                    final ICommonsOrderedSet<MailSendDetails> aValidSentExt = new CommonsLinkedHashSet<>();
                    final ICommonsOrderedSet<MailSendDetails> aValidUnsentExt = new CommonsLinkedHashSet<>();
                    final ICommonsOrderedSet<MailSendDetails> aInvalidExt = new CommonsLinkedHashSet<>();
                    for (final MailSendDetails aFailure : aDetails) {
                        final String sAddress = aFailure.getAddress();
                        if (aValidSent.contains(sAddress))
                            aValidSentExt.add(aFailure);
                        else if (aValidUnsent.contains(sAddress))
                            aValidUnsentExt.add(aFailure);
                        else
                            aInvalidExt.add(aFailure);
                    }
                    final EmailDataTransportEvent aEvent = new EmailDataTransportEvent(m_aSMTPSettings, aEmailData, aMimeMessage, aValidSentExt, aValidUnsentExt, aInvalidExt);
                    if (aValidUnsent.isEmpty() && aInvalid.isEmpty() && aValidSent.isNotEmpty()) {
                        // Message delivered
                        for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners) aEmailDataTransportListener.messageDelivered(aEvent);
                        // Remove message from list of remaining
                        STATS_SEND_SUCCESS.increment();
                    } else {
                        // Message not delivered
                        for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners) aEmailDataTransportListener.messageNotDelivered(aEvent);
                        // Sending exactly this message failed
                        aFailedMessages.put(aEmailData, new MailTransportError(ex, aDetails));
                        STATS_SEND_FAILURE.increment();
                    }
                    // Remove message from list of remaining as we put it in the
                    // failed message list manually in case of error
                    aRemainingMessages.remove(aEmailData);
                } catch (final MessagingException ex) {
                    if (EmailGlobalSettings.isDebugSMTP())
                        LOGGER.error("Error send mail - MessagingException", ex);
                    final ICommonsOrderedSet<MailSendDetails> aInvalid = new CommonsLinkedHashSet<>();
                    final Consumer<IEmailAddress> aConsumer = a -> aInvalid.add(new MailSendDetails(false, a.getAddress(), "<generic error>", ex.getMessage(), ESMTPErrorCode.FALLBACK));
                    aEmailData.to().forEach(aConsumer);
                    aEmailData.cc().forEach(aConsumer);
                    aEmailData.bcc().forEach(aConsumer);
                    final EmailDataTransportEvent aEvent = new EmailDataTransportEvent(m_aSMTPSettings, aEmailData, aMimeMessage, new CommonsArrayList<>(), new CommonsArrayList<>(), aInvalid);
                    // Message not delivered
                    for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners) aEmailDataTransportListener.messageNotDelivered(aEvent);
                    // Sending exactly this message failed
                    aFailedMessages.put(aEmailData, new MailTransportError(ex));
                    // Remove message from list of remaining as we put it in the
                    // failed message list manually
                    aRemainingMessages.remove(aEmailData);
                    STATS_SEND_FAILURE.increment();
                }
            }
        // for all messages
        } catch (final AuthenticationFailedException ex) {
            // problem with the credentials
            aExceptionToBeRemembered = new MailSendException("Mail server authentication failed", ex);
        } catch (final MessagingException ex) {
            if (WebExceptionHelper.isServerNotReachableConnection(ex.getCause()))
                aExceptionToBeRemembered = new MailSendException("Failed to connect to mail server: " + ex.getCause().getMessage());
            else
                aExceptionToBeRemembered = new MailSendException("Mail server connection failed", ex);
        } catch (final Exception ex) {
            // E.g. IllegalState from SMTPTransport ("Not connected")
            aExceptionToBeRemembered = new MailSendException("Internal error sending mail", ex);
        } finally {
            // Was any message not sent
            if (aRemainingMessages.isNotEmpty()) {
                if (aExceptionToBeRemembered == null)
                    aExceptionToBeRemembered = new MailSendException("Internal error - messages are remaining but no Exception occurred!");
                for (final IMutableEmailData aRemainingMessage : aRemainingMessages) aFailedMessages.put(aRemainingMessage, new MailTransportError(aExceptionToBeRemembered));
            }
        }
    }
    return aFailedMessages;
}
Also used : ICommonsList(com.helger.commons.collection.impl.ICommonsList) AuthenticationFailedException(javax.mail.AuthenticationFailedException) EmailDataTransportEvent(com.helger.smtp.listener.EmailDataTransportEvent) IMutableEmailData(com.helger.smtp.data.IMutableEmailData) ICommonsOrderedSet(com.helger.commons.collection.impl.ICommonsOrderedSet) ConnectionListener(javax.mail.event.ConnectionListener) Consumer(java.util.function.Consumer) MimeMessage(javax.mail.internet.MimeMessage) IEmailDataTransportListener(com.helger.smtp.listener.IEmailDataTransportListener) CommonsLinkedHashMap(com.helger.commons.collection.impl.CommonsLinkedHashMap) SendFailedException(javax.mail.SendFailedException) MessagingException(javax.mail.MessagingException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) SMTPAddressSucceededException(com.sun.mail.smtp.SMTPAddressSucceededException) Date(java.util.Date) MessagingException(javax.mail.MessagingException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) SendFailedException(javax.mail.SendFailedException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) SMTPAddressSucceededException(com.sun.mail.smtp.SMTPAddressSucceededException) ICommonsSet(com.helger.commons.collection.impl.ICommonsSet) Transport(javax.mail.Transport) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) Nonnull(javax.annotation.Nonnull)

Aggregations

ICommonsSet (com.helger.commons.collection.impl.ICommonsSet)7 ICommonsList (com.helger.commons.collection.impl.ICommonsList)6 CommonsHashMap (com.helger.commons.collection.impl.CommonsHashMap)4 ISMPServiceGroupManager (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager)4 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)3 CommonsHashSet (com.helger.commons.collection.impl.CommonsHashSet)3 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)3 ISimpleURL (com.helger.commons.url.ISimpleURL)3 HCRow (com.helger.html.hc.html.tabular.HCRow)3 HCTable (com.helger.html.hc.html.tabular.HCTable)3 HCA (com.helger.html.hc.html.textlevel.HCA)3 HCNodeList (com.helger.html.hc.impl.HCNodeList)3 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)3 SMPMetaManager (com.helger.phoss.smp.domain.SMPMetaManager)3 ISMPServiceGroup (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup)3 ISMPServiceInformation (com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation)3 ISMPServiceInformationManager (com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager)3 Locale (java.util.Locale)3 Nonnull (javax.annotation.Nonnull)3 Logger (org.slf4j.Logger)3