Search in sources :

Example 11 with ISMPServiceInformationManager

use of com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager 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 12 with ISMPServiceInformationManager

use of com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager in project phoss-smp by phax.

the class BDXR1ServerAPI method getServiceRegistration.

@Nonnull
public SignedServiceMetadataType getServiceRegistration(@Nonnull final String sPathServiceGroupID, @Nonnull final String sPathDocTypeID) throws SMPServerException {
    final String sLog = LOG_PREFIX + "GET /" + sPathServiceGroupID + "/services/" + sPathDocTypeID;
    final String sAction = "getServiceRegistration";
    if (LOGGER.isInfoEnabled())
        LOGGER.info(sLog);
    STATS_COUNTER_INVOCATION.increment(sAction);
    try {
        final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
        final IParticipantIdentifier aPathServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sPathServiceGroupID);
        if (aPathServiceGroupID == null) {
            // Invalid identifier
            throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, m_aAPIDataProvider.getCurrentURI());
        }
        final ISMPServiceGroup aPathServiceGroup = SMPMetaManager.getServiceGroupMgr().getSMPServiceGroupOfID(aPathServiceGroupID);
        if (aPathServiceGroup == null) {
            throw new SMPNotFoundException("No such Service Group '" + sPathServiceGroupID + "'", m_aAPIDataProvider.getCurrentURI());
        }
        final IDocumentTypeIdentifier aPathDocTypeID = aIdentifierFactory.parseDocumentTypeIdentifier(sPathDocTypeID);
        if (aPathDocTypeID == null) {
            throw SMPBadRequestException.failedToParseDocType(sPathDocTypeID, m_aAPIDataProvider.getCurrentURI());
        }
        // First check for redirection, then for actual service
        final ISMPRedirectManager aRedirectMgr = SMPMetaManager.getRedirectMgr();
        final ISMPRedirect aRedirect = aRedirectMgr.getSMPRedirectOfServiceGroupAndDocumentType(aPathServiceGroup, aPathDocTypeID);
        final SignedServiceMetadataType aSignedServiceMetadata = new SignedServiceMetadataType();
        if (aRedirect != null) {
            aSignedServiceMetadata.setServiceMetadata(aRedirect.getAsJAXBObjectBDXR1());
        } else {
            // Get as regular service information
            final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
            final ISMPServiceInformation aServiceInfo = aServiceInfoMgr.getSMPServiceInformationOfServiceGroupAndDocumentType(aPathServiceGroup, aPathDocTypeID);
            final ServiceMetadataType aSM = aServiceInfo == null ? null : aServiceInfo.getAsJAXBObjectBDXR1();
            if (aSM != null) {
                aSignedServiceMetadata.setServiceMetadata(aSM);
            } else {
                // Neither nor is present, or no endpoint is available
                throw new SMPNotFoundException("service(" + sPathServiceGroupID + "," + sPathDocTypeID + ")", m_aAPIDataProvider.getCurrentURI());
            }
        }
        if (LOGGER.isInfoEnabled())
            LOGGER.info(sLog + " SUCCESS");
        STATS_COUNTER_SUCCESS.increment(sAction);
        return aSignedServiceMetadata;
    } catch (final SMPServerException ex) {
        if (LOGGER.isWarnEnabled())
            LOGGER.warn(sLog + " ERROR - " + ex.getMessage());
        STATS_COUNTER_ERROR.increment(sAction);
        throw ex;
    }
}
Also used : ISMPServiceInformationManager(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) SignedServiceMetadataType(com.helger.xsds.bdxr.smp1.SignedServiceMetadataType) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) ISMPRedirectManager(com.helger.phoss.smp.domain.redirect.ISMPRedirectManager) SMPNotFoundException(com.helger.phoss.smp.exception.SMPNotFoundException) ISMPRedirect(com.helger.phoss.smp.domain.redirect.ISMPRedirect) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) SignedServiceMetadataType(com.helger.xsds.bdxr.smp1.SignedServiceMetadataType) ServiceMetadataType(com.helger.xsds.bdxr.smp1.ServiceMetadataType) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) SMPServerException(com.helger.phoss.smp.exception.SMPServerException) Nonnull(javax.annotation.Nonnull)

Example 13 with ISMPServiceInformationManager

use of com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager in project phoss-smp by phax.

the class SMPServerAPI method getServiceRegistration.

@Nonnull
public SignedServiceMetadataType getServiceRegistration(@Nonnull final String sPathServiceGroupID, @Nonnull final String sPathDocTypeID) throws SMPServerException {
    final String sLog = LOG_PREFIX + "GET /" + sPathServiceGroupID + "/services/" + sPathDocTypeID;
    final String sAction = "getServiceRegistration";
    if (LOGGER.isInfoEnabled())
        LOGGER.info(sLog);
    STATS_COUNTER_INVOCATION.increment(sAction);
    try {
        final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
        final IParticipantIdentifier aPathServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sPathServiceGroupID);
        if (aPathServiceGroupID == null) {
            // Invalid identifier
            throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, m_aAPIDataProvider.getCurrentURI());
        }
        final ISMPServiceGroup aPathServiceGroup = SMPMetaManager.getServiceGroupMgr().getSMPServiceGroupOfID(aPathServiceGroupID);
        if (aPathServiceGroup == null) {
            throw new SMPNotFoundException("No such Service Group '" + sPathServiceGroupID + "'", m_aAPIDataProvider.getCurrentURI());
        }
        final IDocumentTypeIdentifier aPathDocTypeID = aIdentifierFactory.parseDocumentTypeIdentifier(sPathDocTypeID);
        if (aPathDocTypeID == null) {
            throw SMPBadRequestException.failedToParseDocType(sPathDocTypeID, m_aAPIDataProvider.getCurrentURI());
        }
        // First check for redirection, then for actual service
        final ISMPRedirectManager aRedirectMgr = SMPMetaManager.getRedirectMgr();
        final ISMPRedirect aRedirect = aRedirectMgr.getSMPRedirectOfServiceGroupAndDocumentType(aPathServiceGroup, aPathDocTypeID);
        final SignedServiceMetadataType aSignedServiceMetadata = new SignedServiceMetadataType();
        if (aRedirect != null) {
            aSignedServiceMetadata.setServiceMetadata(aRedirect.getAsJAXBObjectPeppol());
        } else {
            // Get as regular service information
            final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
            final ISMPServiceInformation aServiceInfo = aServiceInfoMgr.getSMPServiceInformationOfServiceGroupAndDocumentType(aPathServiceGroup, aPathDocTypeID);
            final ServiceMetadataType aSM = aServiceInfo == null ? null : aServiceInfo.getAsJAXBObjectPeppol();
            if (aSM != null) {
                aSignedServiceMetadata.setServiceMetadata(aSM);
            } else {
                // Neither nor is present, or no endpoint is available
                throw new SMPNotFoundException("service(" + sPathServiceGroupID + "," + sPathDocTypeID + ")", m_aAPIDataProvider.getCurrentURI());
            }
        }
        if (LOGGER.isInfoEnabled())
            LOGGER.info(sLog + " SUCCESS");
        STATS_COUNTER_SUCCESS.increment(sAction);
        return aSignedServiceMetadata;
    } catch (final SMPServerException ex) {
        if (LOGGER.isWarnEnabled())
            LOGGER.warn(sLog + " ERROR - " + ex.getMessage());
        STATS_COUNTER_ERROR.increment(sAction);
        throw ex;
    }
}
Also used : ISMPServiceInformationManager(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) SignedServiceMetadataType(com.helger.xsds.peppol.smp1.SignedServiceMetadataType) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) ISMPRedirectManager(com.helger.phoss.smp.domain.redirect.ISMPRedirectManager) SMPNotFoundException(com.helger.phoss.smp.exception.SMPNotFoundException) ISMPRedirect(com.helger.phoss.smp.domain.redirect.ISMPRedirect) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) SignedServiceMetadataType(com.helger.xsds.peppol.smp1.SignedServiceMetadataType) ServiceMetadataType(com.helger.xsds.peppol.smp1.ServiceMetadataType) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) SMPServerException(com.helger.phoss.smp.exception.SMPServerException) Nonnull(javax.annotation.Nonnull)

Example 14 with ISMPServiceInformationManager

use of com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager in project phoss-smp by phax.

the class SMPServerAPI method getCompleteServiceGroup.

@Nonnull
public CompleteServiceGroupType getCompleteServiceGroup(final String sPathServiceGroupID) throws SMPServerException {
    final String sLog = LOG_PREFIX + "GET /complete/" + sPathServiceGroupID;
    final String sAction = "getCompleteServiceGroup";
    if (LOGGER.isInfoEnabled())
        LOGGER.info(sLog);
    STATS_COUNTER_INVOCATION.increment(sAction);
    try {
        final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
        final IParticipantIdentifier aPathServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sPathServiceGroupID);
        if (aPathServiceGroupID == null) {
            // Invalid identifier
            throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, m_aAPIDataProvider.getCurrentURI());
        }
        final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
        final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
        final ISMPServiceGroup aServiceGroup = aServiceGroupMgr.getSMPServiceGroupOfID(aPathServiceGroupID);
        if (aServiceGroup == null) {
            // No such service group
            throw new SMPNotFoundException("Unknown Service Group ID '" + sPathServiceGroupID + "'", m_aAPIDataProvider.getCurrentURI());
        }
        // Then add the service metadata references
        final ServiceMetadataReferenceCollectionType aRefCollection = new ServiceMetadataReferenceCollectionType();
        for (final IDocumentTypeIdentifier aDocTypeID : aServiceInfoMgr.getAllSMPDocumentTypesOfServiceGroup(aServiceGroup)) {
            // Ignore all service information without endpoints
            final ISMPServiceInformation aServiceInfo = aServiceInfoMgr.getSMPServiceInformationOfServiceGroupAndDocumentType(aServiceGroup, aDocTypeID);
            if (aServiceInfo != null && aServiceInfo.getTotalEndpointCount() > 0) {
                final ServiceMetadataReferenceType aMetadataReference = new ServiceMetadataReferenceType();
                aMetadataReference.setHref(m_aAPIDataProvider.getServiceMetadataReferenceHref(aPathServiceGroupID, aDocTypeID));
                aRefCollection.addServiceMetadataReference(aMetadataReference);
            }
        }
        final ServiceGroupType aSG = aServiceGroup.getAsJAXBObjectPeppol();
        aSG.setServiceMetadataReferenceCollection(aRefCollection);
        // a CompleteSG may be empty
        final CompleteServiceGroupType aCompleteServiceGroup = new CompleteServiceGroupType();
        aCompleteServiceGroup.setServiceGroup(aSG);
        for (final ISMPServiceInformation aServiceInfo : aServiceInfoMgr.getAllSMPServiceInformationOfServiceGroup(aServiceGroup)) {
            final ServiceMetadataType aSM = aServiceInfo.getAsJAXBObjectPeppol();
            if (aSM != null)
                aCompleteServiceGroup.addServiceMetadata(aSM);
        }
        if (LOGGER.isInfoEnabled())
            LOGGER.info(sLog + " SUCCESS");
        STATS_COUNTER_SUCCESS.increment(sAction);
        return aCompleteServiceGroup;
    } catch (final SMPServerException ex) {
        if (LOGGER.isWarnEnabled())
            LOGGER.warn(sLog + " ERROR - " + ex.getMessage());
        STATS_COUNTER_ERROR.increment(sAction);
        throw ex;
    }
}
Also used : CompleteServiceGroupType(com.helger.xsds.peppol.smp1.CompleteServiceGroupType) ISMPServiceGroupManager(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager) ISMPServiceInformationManager(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager) ServiceMetadataReferenceCollectionType(com.helger.xsds.peppol.smp1.ServiceMetadataReferenceCollectionType) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) SMPNotFoundException(com.helger.phoss.smp.exception.SMPNotFoundException) ServiceMetadataReferenceType(com.helger.xsds.peppol.smp1.ServiceMetadataReferenceType) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) ServiceGroupType(com.helger.xsds.peppol.smp1.ServiceGroupType) CompleteServiceGroupType(com.helger.xsds.peppol.smp1.CompleteServiceGroupType) SignedServiceMetadataType(com.helger.xsds.peppol.smp1.SignedServiceMetadataType) ServiceMetadataType(com.helger.xsds.peppol.smp1.ServiceMetadataType) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) SMPServerException(com.helger.phoss.smp.exception.SMPServerException) Nonnull(javax.annotation.Nonnull)

Example 15 with ISMPServiceInformationManager

use of com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager in project phoss-smp by phax.

the class SMPServerAPI method saveServiceRegistration.

@Nonnull
public ESuccess saveServiceRegistration(@Nonnull final String sPathServiceGroupID, @Nonnull final String sPathDocumentTypeID, @Nonnull final ServiceMetadataType aServiceMetadata, @Nonnull final BasicAuthClientCredentials aCredentials) throws SMPServerException {
    final String sLog = LOG_PREFIX + "PUT /" + sPathServiceGroupID + "/services/" + sPathDocumentTypeID;
    final String sAction = "saveServiceRegistration";
    if (LOGGER.isInfoEnabled())
        LOGGER.info(sLog + " ==> " + aServiceMetadata);
    STATS_COUNTER_INVOCATION.increment(sAction);
    try {
        // Parse provided identifiers
        final IIdentifierFactory aIdentifierFactory = SMPMetaManager.getIdentifierFactory();
        final IParticipantIdentifier aPathServiceGroupID = aIdentifierFactory.parseParticipantIdentifier(sPathServiceGroupID);
        if (aPathServiceGroupID == null) {
            // Invalid identifier
            throw SMPBadRequestException.failedToParseSG(sPathServiceGroupID, m_aAPIDataProvider.getCurrentURI());
        }
        final IDocumentTypeIdentifier aPathDocTypeID = aIdentifierFactory.parseDocumentTypeIdentifier(sPathDocumentTypeID);
        if (aPathDocTypeID == null) {
            // Invalid identifier
            throw SMPBadRequestException.failedToParseDocType(sPathDocumentTypeID, m_aAPIDataProvider.getCurrentURI());
        }
        // May be null for a Redirect!
        final ServiceInformationType aServiceInformation = aServiceMetadata.getServiceInformation();
        if (aServiceInformation != null) {
            // metadata (body) must equal path
            if (aServiceInformation.getParticipantIdentifier() == null) {
                throw new SMPBadRequestException("Save Service Metadata has inconsistent values.\n" + "Service Information Participant ID: <none>\n" + "URL Parameter value: '" + aPathServiceGroupID.getURIEncoded() + "'", m_aAPIDataProvider.getCurrentURI());
            }
            final IParticipantIdentifier aPayloadServiceGroupID;
            if (aServiceInformation.getParticipantIdentifier() == null) {
                // Can happen when tampering with the input data
                aPayloadServiceGroupID = null;
            } else {
                aPayloadServiceGroupID = aIdentifierFactory.createParticipantIdentifier(aServiceInformation.getParticipantIdentifier().getScheme(), aServiceInformation.getParticipantIdentifier().getValue());
            }
            if (!aPathServiceGroupID.hasSameContent(aPayloadServiceGroupID)) {
                // Participant ID in URL must match the one in XML structure
                throw new SMPBadRequestException("Save Service Metadata was called with inconsistent values.\n" + "Service Infoformation Participant ID: " + (aPayloadServiceGroupID == null ? "<none>" : "'" + aPayloadServiceGroupID.getURIEncoded() + "'") + "\n" + "URL parameter value: '" + aPathServiceGroupID.getURIEncoded() + "'", m_aAPIDataProvider.getCurrentURI());
            }
            if (aServiceInformation.getDocumentIdentifier() == null) {
                throw new SMPBadRequestException("Save Service Metadata was called with inconsistent values.\n" + "Service Information Document Type ID: <none>\n" + "URL parameter value: '" + aPathDocTypeID.getURIEncoded() + "'", m_aAPIDataProvider.getCurrentURI());
            }
            final IDocumentTypeIdentifier aPayloadDocTypeID = aIdentifierFactory.createDocumentTypeIdentifier(aServiceInformation.getDocumentIdentifier().getScheme(), aServiceInformation.getDocumentIdentifier().getValue());
            if (!aPathDocTypeID.hasSameContent(aPayloadDocTypeID)) {
                // Document type ID in URL must match the one in XML structure
                throw new SMPBadRequestException("Save Service Metadata was called with inconsistent values.\n" + "Service Information Document Type ID: '" + aPayloadDocTypeID.getURIEncoded() + "'\n" + "URL parameter value: '" + aPathDocTypeID.getURIEncoded() + "'", m_aAPIDataProvider.getCurrentURI());
            }
        }
        // Main save
        final IUser aDataUser = SMPUserManagerPhoton.validateUserCredentials(aCredentials);
        SMPUserManagerPhoton.verifyOwnership(aPathServiceGroupID, aDataUser);
        final ISMPServiceGroupManager aServiceGroupMgr = SMPMetaManager.getServiceGroupMgr();
        final ISMPServiceGroup aPathServiceGroup = aServiceGroupMgr.getSMPServiceGroupOfID(aPathServiceGroupID);
        if (aPathServiceGroup == null) {
            // Service group not found
            throw new SMPNotFoundException("Service Group '" + sPathServiceGroupID + "' is not on this SMP", m_aAPIDataProvider.getCurrentURI());
        }
        if (aServiceMetadata.getRedirect() != null) {
            // Handle redirect
            final ISMPRedirectManager aRedirectMgr = SMPMetaManager.getRedirectMgr();
            // not available in Peppol mode
            final X509Certificate aCertificate = null;
            if (aRedirectMgr.createOrUpdateSMPRedirect(aPathServiceGroup, aPathDocTypeID, aServiceMetadata.getRedirect().getHref(), aServiceMetadata.getRedirect().getCertificateUID(), aCertificate, SMPExtensionConverter.convertToString(aServiceMetadata.getRedirect().getExtension())) == null) {
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(sLog + " - ERROR - Redirect");
                STATS_COUNTER_ERROR.increment(sAction);
                return ESuccess.FAILURE;
            }
            if (LOGGER.isInfoEnabled())
                LOGGER.info(sLog + " SUCCESS - Redirect");
        } else if (aServiceInformation != null) {
            // Handle service information
            final ProcessListType aJAXBProcesses = aServiceInformation.getProcessList();
            final ICommonsList<SMPProcess> aProcesses = new CommonsArrayList<>();
            for (final ProcessType aJAXBProcess : aJAXBProcesses.getProcess()) {
                final ICommonsList<SMPEndpoint> aEndpoints = new CommonsArrayList<>();
                for (final EndpointType aJAXBEndpoint : aJAXBProcess.getServiceEndpointList().getEndpoint()) {
                    final SMPEndpoint aEndpoint = new SMPEndpoint(aJAXBEndpoint.getTransportProfile(), W3CEndpointReferenceHelper.getAddress(aJAXBEndpoint.getEndpointReference()), aJAXBEndpoint.isRequireBusinessLevelSignature(), aJAXBEndpoint.getMinimumAuthenticationLevel(), aJAXBEndpoint.getServiceActivationDate(), aJAXBEndpoint.getServiceExpirationDate(), aJAXBEndpoint.getCertificate(), aJAXBEndpoint.getServiceDescription(), aJAXBEndpoint.getTechnicalContactUrl(), aJAXBEndpoint.getTechnicalInformationUrl(), SMPExtensionConverter.convertToString(aJAXBEndpoint.getExtension()));
                    aEndpoints.add(aEndpoint);
                }
                final SMPProcess aProcess = new SMPProcess(SimpleProcessIdentifier.wrap(aJAXBProcess.getProcessIdentifier()), aEndpoints, SMPExtensionConverter.convertToString(aJAXBProcess.getExtension()));
                aProcesses.add(aProcess);
            }
            final ISMPServiceInformationManager aServiceInfoMgr = SMPMetaManager.getServiceInformationMgr();
            final String sExtensionXML = SMPExtensionConverter.convertToString(aServiceInformation.getExtension());
            if (aServiceInfoMgr.mergeSMPServiceInformation(new SMPServiceInformation(aPathServiceGroup, aPathDocTypeID, aProcesses, sExtensionXML)).isFailure()) {
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(sLog + " - ERROR - ServiceInformation");
                STATS_COUNTER_ERROR.increment(sAction);
                return ESuccess.FAILURE;
            }
            if (LOGGER.isInfoEnabled())
                LOGGER.info(sLog + " SUCCESS - ServiceInformation");
        } else {
            throw new SMPBadRequestException("Save Service Metadata was called with neither a Redirect nor a ServiceInformation", m_aAPIDataProvider.getCurrentURI());
        }
        if (false)
            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) ICommonsList(com.helger.commons.collection.impl.ICommonsList) SMPBadRequestException(com.helger.phoss.smp.exception.SMPBadRequestException) ISMPServiceInformationManager(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager) ISMPServiceGroup(com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup) SMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.SMPServiceInformation) ISMPServiceInformation(com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation) IDocumentTypeIdentifier(com.helger.peppolid.IDocumentTypeIdentifier) SMPEndpoint(com.helger.phoss.smp.domain.serviceinfo.SMPEndpoint) ServiceInformationType(com.helger.xsds.peppol.smp1.ServiceInformationType) X509Certificate(java.security.cert.X509Certificate) ISMPRedirectManager(com.helger.phoss.smp.domain.redirect.ISMPRedirectManager) SMPProcess(com.helger.phoss.smp.domain.serviceinfo.SMPProcess) SMPNotFoundException(com.helger.phoss.smp.exception.SMPNotFoundException) ProcessType(com.helger.xsds.peppol.smp1.ProcessType) EndpointType(com.helger.xsds.peppol.smp1.EndpointType) IUser(com.helger.photon.security.user.IUser) ProcessListType(com.helger.xsds.peppol.smp1.ProcessListType) IIdentifierFactory(com.helger.peppolid.factory.IIdentifierFactory) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier) SMPServerException(com.helger.phoss.smp.exception.SMPServerException) Nonnull(javax.annotation.Nonnull)

Aggregations

ISMPServiceGroup (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroup)28 ISMPServiceInformationManager (com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformationManager)28 ISMPServiceGroupManager (com.helger.phoss.smp.domain.servicegroup.ISMPServiceGroupManager)21 ISMPServiceInformation (com.helger.phoss.smp.domain.serviceinfo.ISMPServiceInformation)21 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)20 IIdentifierFactory (com.helger.peppolid.factory.IIdentifierFactory)17 IDocumentTypeIdentifier (com.helger.peppolid.IDocumentTypeIdentifier)16 ISMPRedirectManager (com.helger.phoss.smp.domain.redirect.ISMPRedirectManager)14 SMPNotFoundException (com.helger.phoss.smp.exception.SMPNotFoundException)14 SMPServerException (com.helger.phoss.smp.exception.SMPServerException)13 Nonnull (javax.annotation.Nonnull)12 ICommonsList (com.helger.commons.collection.impl.ICommonsList)7 ISMPRedirect (com.helger.phoss.smp.domain.redirect.ISMPRedirect)7 ISMPProcess (com.helger.phoss.smp.domain.serviceinfo.ISMPProcess)7 IUser (com.helger.photon.security.user.IUser)7 HCNodeList (com.helger.html.hc.impl.HCNodeList)6 ISMPEndpoint (com.helger.phoss.smp.domain.serviceinfo.ISMPEndpoint)6 SMPEndpoint (com.helger.phoss.smp.domain.serviceinfo.SMPEndpoint)6 Locale (java.util.Locale)6 EChange (com.helger.commons.state.EChange)4