Search in sources :

Example 6 with ISMPBusinessCardManager

use of com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager in project phoss-smp by phax.

the class ServiceGroupExport method createExportDataXMLVer10.

/**
 * Create XML export data for the provided service groups.
 *
 * @param aServiceGroups
 *        The service groups to export. May not be <code>null</code> but maybe
 *        empty.
 * @param bIncludeBusinessCards
 *        <code>true</code> to include Business Cards, <code>false</code> to
 *        skip them
 * @return The created XML document. Never <code>null</code>.
 */
@Nonnull
public static IMicroDocument createExportDataXMLVer10(@Nonnull final ICommonsList<ISMPServiceGroup> aServiceGroups, final boolean bIncludeBusinessCards) {
    ValueEnforcer.notNull(aServiceGroups, "ServiceGroups");
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Start creating Service Group export data XML v1.0 for " + aServiceGroups.size() + " entries - " + (bIncludeBusinessCards ? "incl. Business Cards" : "excl. Business Cards"));
    final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
    final ISMPRedirectManager aRedirectMgr = SMPMetaManager.getRedirectMgr();
    final IMicroDocument aDoc = new MicroDocument();
    final IMicroElement eRoot = aDoc.appendElement(CSMPExchange.ELEMENT_SMP_DATA);
    eRoot.setAttribute(CSMPExchange.ATTR_VERSION, CSMPExchange.VERSION_10);
    final ICommonsList<ISMPServiceGroup> aSortedServiceGroups = aServiceGroups.getSorted(ISMPServiceGroup.comparator());
    // Add all service groups
    for (final ISMPServiceGroup aServiceGroup : aSortedServiceGroups) {
        final IMicroElement eServiceGroup = eRoot.appendChild(MicroTypeConverter.convertToMicroElement(aServiceGroup, CSMPExchange.ELEMENT_SERVICEGROUP));
        // Add all service information
        final ICommonsList<ISMPServiceInformation> aAllServiceInfos = aServiceInfoMgr.getAllSMPServiceInformationOfServiceGroup(aServiceGroup);
        for (final ISMPServiceInformation aServiceInfo : aAllServiceInfos.getSortedInline(ISMPServiceInformation.comparator())) {
            eServiceGroup.appendChild(MicroTypeConverter.convertToMicroElement(aServiceInfo, CSMPExchange.ELEMENT_SERVICEINFO));
        }
        // Add all redirects
        final ICommonsList<ISMPRedirect> aAllRedirects = aRedirectMgr.getAllSMPRedirectsOfServiceGroup(aServiceGroup);
        for (final ISMPRedirect aServiceInfo : aAllRedirects.getSortedInline(ISMPRedirect.comparator())) {
            eServiceGroup.appendChild(MicroTypeConverter.convertToMicroElement(aServiceInfo, CSMPExchange.ELEMENT_REDIRECT));
        }
    }
    // Add Business cards only if PD integration is enabled
    if (bIncludeBusinessCards) {
        // Add all business cards
        final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
        for (final ISMPServiceGroup aServiceGroup : aSortedServiceGroups) {
            final ISMPBusinessCard aBusinessCard = aBusinessCardMgr.getSMPBusinessCardOfID(aServiceGroup.getParticipantIdentifier());
            if (aBusinessCard != null) {
                eRoot.appendChild(SMPBusinessCardMicroTypeConverter.convertToMicroElement(aBusinessCard, null, CSMPExchange.ELEMENT_BUSINESSCARD, true));
            }
        }
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Finished creating Service Group XML data");
    return aDoc;
}
Also used : ISMPServiceInformationManager(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) ISMPBusinessCard(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCard) ISMPRedirectManager(com.helger.phoss.smp.domain.redirect.ISMPRedirectManager) IMicroDocument(com.helger.xml.microdom.IMicroDocument) MicroDocument(com.helger.xml.microdom.MicroDocument) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) IMicroElement(com.helger.xml.microdom.IMicroElement) ISMPRedirect(com.helger.phoss.smp.domain.redirect.ISMPRedirect) IMicroDocument(com.helger.xml.microdom.IMicroDocument) Nonnull(javax.annotation.Nonnull)

Example 7 with ISMPBusinessCardManager

use of com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager 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 8 with ISMPBusinessCardManager

use of com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager in project phoss-smp by phax.

the class BusinessCardServerAPI method createBusinessCard.

@Nonnull
public ESuccess createBusinessCard(@Nonnull final String sServiceGroupID, @Nonnull final PDBusinessCard aBusinessCard, @Nonnull final BasicAuthClientCredentials aCredentials) throws SMPServerException {
    final String sLog = LOG_PREFIX + "PUT /businesscard/" + sServiceGroupID;
    final String sAction = "createBusinessCard";
    if (LOGGER.isInfoEnabled())
        LOGGER.info(sLog + " ==> " + aBusinessCard);
    STATS_COUNTER_INVOCATION.increment(sAction);
    try {
        // Parse and validate identifier
        final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
        final IParticipantIdentifier aServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sServiceGroupID);
        if (aServiceGroupID == null) {
            // Invalid identifier
            throw SMPBadRequestException.failedToParseSG(sServiceGroupID, m_aAPIProvider.getCurrentURI());
        }
        final IParticipantIdentifier aPayloadServiceGroupID = aIdentifierFactory.createParticipantIdentifier(aBusinessCard.getParticipantIdentifier().getScheme(), aBusinessCard.getParticipantIdentifier().getValue());
        if (!aServiceGroupID.hasSameContent(aPayloadServiceGroupID)) {
            // Business identifiers must be equal
            throw new SMPBadRequestException("Participant Inconsistency. The URL points to '" + aServiceGroupID.getURIEncoded() + "' whereas the BusinessCard contains '" + aPayloadServiceGroupID.getURIEncoded() + "'", m_aAPIProvider.getCurrentURI());
        }
        // Retrieve the service group
        final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
        final ISMPServiceGroup aServiceGroup = aServiceGroupMgr.getSMPServiceGroupOfID(aServiceGroupID);
        if (aServiceGroup == null) {
            // No such service group (on this server)
            throw new SMPNotFoundException("Unknown serviceGroup '" + sServiceGroupID + "'", m_aAPIProvider.getCurrentURI());
        }
        // Check credentials and verify service group is owned by provided user
        final IUser aSMPUser = SMPUserManagerPhoton.validateUserCredentials(aCredentials);
        SMPUserManagerPhoton.verifyOwnership(aServiceGroupID, aSMPUser);
        final ISMPBusinessCardManager aBusinessCardMgr = SMPMetaManager.getBusinessCardMgr();
        if (aBusinessCardMgr == null) {
            throw new SMPBadRequestException("This SMP server does not support the BusinessCard API", m_aAPIProvider.getCurrentURI());
        }
        final ICommonsList<SMPBusinessCardEntity> aEntities = new CommonsArrayList<>();
        for (final PDBusinessEntity aEntity : aBusinessCard.businessEntities()) aEntities.add(SMPBusinessCardEntity.createFromGenericObject(aEntity));
        if (aBusinessCardMgr.createOrUpdateSMPBusinessCard(aServiceGroup.getParticipantIdentifier(), aEntities) == null) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn(sLog + " ERROR");
            STATS_COUNTER_ERROR.increment(sAction);
            return ESuccess.FAILURE;
        }
        if (LOGGER.isInfoEnabled())
            LOGGER.info(sLog + " SUCCESS");
        STATS_COUNTER_SUCCESS.increment(sAction);
        return ESuccess.SUCCESS;
    } 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) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) SMPBusinessCardEntity(com.helger.phoss.smp.domain.businesscard.SMPBusinessCardEntity) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) SMPNotFoundException(com.helger.phoss.smp.exception.SMPNotFoundException) IUser(com.helger.photon.security.user.IUser) PDBusinessEntity(com.helger.pd.businesscard.generic.PDBusinessEntity) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) SMPServerException(com.helger.phoss.smp.exception.SMPServerException) Nonnull(javax.annotation.Nonnull)

Example 9 with ISMPBusinessCardManager

use of com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager in project phoss-smp by phax.

the class BusinessCardInterfaceTest method testGetCreateV1GetDeleteGet.

@Test
public void testGetCreateV1GetDeleteGet() {
    final ISMPServiceGroupManager aSGMgr = SMPMetaManager.getServiceGroupMgr();
    assertNotNull(aSGMgr);
    final ISMPBusinessCardManager aBCMgr = SMPMetaManager.getBusinessCardMgr();
    assertNotNull(aBCMgr);
    final IParticipantIdentifier aPI = PeppolIdentifierFactory.INSTANCE.createParticipantIdentifierWithDefaultScheme("9999:tester");
    final String sPI = aPI.getURIEncoded();
    final ServiceGroupType aSG = new ServiceGroupType();
    aSG.setParticipantIdentifier(new SimpleParticipantIdentifier(aPI));
    aSG.setServiceMetadataReferenceCollection(new ServiceMetadataReferenceCollectionType());
    final WebTarget aTarget = ClientBuilder.newClient().target(m_aRule.getFullURL());
    Response aResponseMsg;
    try {
        // Create SG
        aResponseMsg = _addCredentials(aTarget.path(sPI).request()).put(Entity.xml(m_aObjFactory.createServiceGroup(aSG)));
        _testResponseJerseyClient(aResponseMsg, 200);
        // Get SG - must work
        assertNotNull(aTarget.path(sPI).request().get(ServiceGroupType.class));
        assertTrue(aSGMgr.containsSMPServiceGroupWithID(aPI));
        // Get BC - not existing
        aResponseMsg = aTarget.path("businesscard").path(sPI).request().get();
        _testResponseJerseyClient(aResponseMsg, 404);
        // Create BC with some entities
        final PD1BusinessCardType aBC = new PD1BusinessCardType();
        aBC.setParticipantIdentifier(PD1APIHelper.createIdentifier(aPI.getScheme(), aPI.getValue()));
        PD1BusinessEntityType aBE = new PD1BusinessEntityType();
        aBE.setName("BusinessEntity1");
        aBE.setCountryCode("AT");
        aBE.setGeographicalInformation("Vienna");
        aBC.addBusinessEntity(aBE);
        aBE = new PD1BusinessEntityType();
        aBE.setName("BusinessEntity2");
        aBE.setCountryCode("DE");
        aBE.setGeographicalInformation("Berlin");
        aBC.addBusinessEntity(aBE);
        aResponseMsg = _addCredentials(aTarget.path("businesscard").path(sPI).request()).put(Entity.xml(m_aBC1ObjFactory.createBusinessCard(aBC)));
        _testResponseJerseyClient(aResponseMsg, 200);
        // Get BC - must work (always V3)
        PD3BusinessCardType aReadBC = aTarget.path("businesscard").path(sPI).request().get(PD3BusinessCardType.class);
        assertNotNull(aReadBC);
        assertEquals(2, aReadBC.getBusinessEntityCount());
        ISMPBusinessCard aGetBC = aBCMgr.getSMPBusinessCardOfID(aPI);
        assertNotNull(aGetBC);
        // Update BC - add entity
        aBE = new PD1BusinessEntityType();
        aBE.setName("BusinessEntity3");
        aBE.setCountryCode("SE");
        aBE.setGeographicalInformation("Stockholm");
        aBC.addBusinessEntity(aBE);
        aResponseMsg = _addCredentials(aTarget.path("businesscard").path(sPI).request()).put(Entity.xml(m_aBC1ObjFactory.createBusinessCard(aBC)));
        _testResponseJerseyClient(aResponseMsg, 200);
        // Get BC - must work (always V3)
        aReadBC = aTarget.path("businesscard").path(sPI).request().get(PD3BusinessCardType.class);
        assertNotNull(aReadBC);
        assertEquals(3, aReadBC.getBusinessEntityCount());
        aGetBC = aBCMgr.getSMPBusinessCardOfID(aPI);
        assertNotNull(aGetBC);
    } finally {
        // Delete Business Card
        aResponseMsg = _addCredentials(aTarget.path("businesscard").path(sPI).request()).delete();
        _testResponseJerseyClient(aResponseMsg, 200, 404);
        // must be deleted
        _testResponseJerseyClient(aTarget.path("businesscard").path(sPI).request().get(), 404);
        assertNull(aBCMgr.getSMPBusinessCardOfID(aPI));
        // Delete service Group
        aResponseMsg = _addCredentials(aTarget.path(sPI).request()).delete();
        _testResponseJerseyClient(aResponseMsg, 200, 404);
        // must be deleted
        _testResponseJerseyClient(aTarget.path(sPI).request().get(), 404);
        assertFalse(aSGMgr.containsSMPServiceGroupWithID(aPI));
    }
}
Also used : ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) ServiceMetadataReferenceCollectionType(com.helger.xsds.peppol.smp1.ServiceMetadataReferenceCollectionType) PD1BusinessEntityType(com.helger.pd.businesscard.v1.PD1BusinessEntityType) PD1BusinessCardType(com.helger.pd.businesscard.v1.PD1BusinessCardType) SimpleParticipantIdentifier(com.helger.peppolid.simple.participant.SimpleParticipantIdentifier) Response(javax.ws.rs.core.Response) ISMPBusinessCard(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCard) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) PD3BusinessCardType(com.helger.pd.businesscard.v3.PD3BusinessCardType) WebTarget(javax.ws.rs.client.WebTarget) ServiceGroupType(com.helger.xsds.peppol.smp1.ServiceGroupType) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) Test(org.junit.Test)

Example 10 with ISMPBusinessCardManager

use of com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager in project phoss-smp by phax.

the class BusinessCardInterfaceTest method testGetCreateV3GetDeleteGet.

@Test
public void testGetCreateV3GetDeleteGet() {
    final ISMPServiceGroupManager aSGMgr = SMPMetaManager.getServiceGroupMgr();
    assertNotNull(aSGMgr);
    final ISMPBusinessCardManager aBCMgr = SMPMetaManager.getBusinessCardMgr();
    assertNotNull(aBCMgr);
    final IParticipantIdentifier aPI = PeppolIdentifierFactory.INSTANCE.createParticipantIdentifierWithDefaultScheme("9999:tester");
    final String sPI = aPI.getURIEncoded();
    final ServiceGroupType aSG = new ServiceGroupType();
    aSG.setParticipantIdentifier(new SimpleParticipantIdentifier(aPI));
    aSG.setServiceMetadataReferenceCollection(new ServiceMetadataReferenceCollectionType());
    final WebTarget aTarget = ClientBuilder.newClient().target(m_aRule.getFullURL());
    Response aResponseMsg;
    try {
        // Create SG
        aResponseMsg = _addCredentials(aTarget.path(sPI).request()).put(Entity.xml(m_aObjFactory.createServiceGroup(aSG)));
        _testResponseJerseyClient(aResponseMsg, 200);
        // Get SG - must work
        assertNotNull(aTarget.path(sPI).request().get(ServiceGroupType.class));
        assertTrue(aSGMgr.containsSMPServiceGroupWithID(aPI));
        // Get BC - not existing
        aResponseMsg = aTarget.path("businesscard").path(sPI).request().get();
        _testResponseJerseyClient(aResponseMsg, 404);
        // Create BC with some entities
        final PD3BusinessCardType aBC = new PD3BusinessCardType();
        aBC.setParticipantIdentifier(PD3APIHelper.createIdentifier(aPI.getScheme(), aPI.getValue()));
        PD3BusinessEntityType aBE = new PD3BusinessEntityType();
        aBE.addName(PD3APIHelper.createName("BusinessEntity1", null));
        aBE.setCountryCode("AT");
        aBE.setGeographicalInformation("Vienna");
        aBC.addBusinessEntity(aBE);
        aBE = new PD3BusinessEntityType();
        aBE.addName(PD3APIHelper.createName("BusinessEntity2", null));
        aBE.setCountryCode("DE");
        aBE.setGeographicalInformation("Berlin");
        aBC.addBusinessEntity(aBE);
        aResponseMsg = _addCredentials(aTarget.path("businesscard").path(sPI).request()).put(Entity.xml(m_aBC3ObjFactory.createBusinessCard(aBC)));
        _testResponseJerseyClient(aResponseMsg, 200);
        // Get BC - must work (always V3)
        PD3BusinessCardType aReadBC = aTarget.path("businesscard").path(sPI).request().get(PD3BusinessCardType.class);
        assertNotNull(aReadBC);
        assertEquals(2, aReadBC.getBusinessEntityCount());
        ISMPBusinessCard aGetBC = aBCMgr.getSMPBusinessCardOfID(aPI);
        assertNotNull(aGetBC);
        // Update BC - add entity
        aBE = new PD3BusinessEntityType();
        aBE.addName(PD3APIHelper.createName("BusinessEntity3", null));
        aBE.setCountryCode("SE");
        aBE.setGeographicalInformation("Stockholm");
        aBC.addBusinessEntity(aBE);
        aResponseMsg = _addCredentials(aTarget.path("businesscard").path(sPI).request()).put(Entity.xml(m_aBC3ObjFactory.createBusinessCard(aBC)));
        _testResponseJerseyClient(aResponseMsg, 200);
        // Get BC - must work (always V3)
        aReadBC = aTarget.path("businesscard").path(sPI).request().get(PD3BusinessCardType.class);
        assertNotNull(aReadBC);
        assertEquals(3, aReadBC.getBusinessEntityCount());
        aGetBC = aBCMgr.getSMPBusinessCardOfID(aPI);
        assertNotNull(aGetBC);
    } finally {
        // Delete Business Card
        aResponseMsg = _addCredentials(aTarget.path("businesscard").path(sPI).request()).delete();
        _testResponseJerseyClient(aResponseMsg, 200, 404);
        // must be deleted
        _testResponseJerseyClient(aTarget.path("businesscard").path(sPI).request().get(), 404);
        assertNull(aBCMgr.getSMPBusinessCardOfID(aPI));
        // Delete service Group
        aResponseMsg = _addCredentials(aTarget.path(sPI).request()).delete();
        _testResponseJerseyClient(aResponseMsg, 200, 404);
        // must be deleted
        _testResponseJerseyClient(aTarget.path(sPI).request().get(), 404);
        assertFalse(aSGMgr.containsSMPServiceGroupWithID(aPI));
    }
}
Also used : Response(javax.ws.rs.core.Response) ISMPBusinessCard(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCard) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) ISMPBusinessCardManager(com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager) ServiceMetadataReferenceCollectionType(com.helger.xsds.peppol.smp1.ServiceMetadataReferenceCollectionType) PD3BusinessCardType(com.helger.pd.businesscard.v3.PD3BusinessCardType) PD3BusinessEntityType(com.helger.pd.businesscard.v3.PD3BusinessEntityType) WebTarget(javax.ws.rs.client.WebTarget) ServiceGroupType(com.helger.xsds.peppol.smp1.ServiceGroupType) SimpleParticipantIdentifier(com.helger.peppolid.simple.participant.SimpleParticipantIdentifier) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) Test(org.junit.Test)

Aggregations

ISMPBusinessCardManager (com.helger.phoss.smp.domain.businesscard.ISMPBusinessCardManager)17 ISMPBusinessCard (com.helger.phoss.smp.domain.businesscard.ISMPBusinessCard)13 ISMPServiceGroupManager (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager)11 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)9 Nonnull (javax.annotation.Nonnull)8 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)7 ISMPServiceGroup (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup)7 ISMPSettings (com.helger.phoss.smp.settings.ISMPSettings)7 HCNodeList (com.helger.html.hc.impl.HCNodeList)6 IIdentifierFactory (com.helger.peppolid.factory.IIdentifierFactory)6 SMPBusinessCardEntity (com.helger.phoss.smp.domain.businesscard.SMPBusinessCardEntity)6 SMPMetaManager (com.helger.phoss.smp.domain.SMPMetaManager)5 BootstrapButtonToolbar (com.helger.photon.bootstrap4.buttongroup.BootstrapButtonToolbar)5 IUser (com.helger.photon.security.user.IUser)5 ICommonsList (com.helger.commons.collection.impl.ICommonsList)4 ICommonsMap (com.helger.commons.collection.impl.ICommonsMap)4 ISimpleURL (com.helger.commons.url.ISimpleURL)4 HCRow (com.helger.html.hc.html.tabular.HCRow)4 HCTable (com.helger.html.hc.html.tabular.HCTable)4 HCA (com.helger.html.hc.html.textlevel.HCA)4