package at.gv.egiz.moazs.preprocess; import at.gv.zustellung.app2mzs.xsd.ConfigType; import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Map; import static at.gv.egiz.moazs.MoaZSException.moaZSException; import static at.gv.zustellung.app2mzs.xsd.DeliveryRequestType.deliveryRequestTypeBuilder; import static java.lang.String.format; @Component public class DeliveryRequestAugmenter { private final ConfigUtil util; private final Map configs; private final MzsDeliveryRequestValidator validator; private static final String INCOMPLETE_TNVZ_ERROR_MESSAGE = "mzs:DeliveryRequest is incomplete because mandatory " + "fields for sending a tnvz:QueryPersonRequest are missing."; private static final String INCOMPLETE_CONFIG_ERROR_MESSAGE = "Could not find a profile for " + "the delivery request configuration, and the configuration attached to mzs:DeliveryRequest is incomplete."; private static final String INCOMPLETE_MERGED_CONFIG_ERROR_MESSAGE = "I merged parameters from " + "mzs:DeliveryRequest/Config with parameters from config profile with ProfileId='%s', but the " + "configuration is incomplete."; @Autowired public DeliveryRequestAugmenter(Map deliveryRequestConfigs, ConfigUtil util, MzsDeliveryRequestValidator validator) { this.configs = deliveryRequestConfigs; this.util = util; this.validator = validator; } /** * Augments an incoming {@code request} by filling gaps with config- or default parameters. * * @param request * @throws at.gv.egiz.moazs.MoaZSException * @return augmented request and validated */ public DeliveryRequestType augment(DeliveryRequestType request) { var requestConfig = request.getConfig(); var fallbackProfileId = determineProfileIdFrom(requestConfig); var fallbackConfig = configs.get(fallbackProfileId); if (fallbackConfig == null) { if (!validator.isConfigProfileComplete(request.getConfig())) { throw moaZSException(INCOMPLETE_CONFIG_ERROR_MESSAGE); } else if (!validator.isTnvzComplete(request)) { throw moaZSException(INCOMPLETE_TNVZ_ERROR_MESSAGE); } else { return request; } } else { var mergedConfig = (requestConfig == null) ? fallbackConfig : util.merge(requestConfig, fallbackConfig); if (!validator.isConfigProfileComplete(mergedConfig)) { var message = format(INCOMPLETE_MERGED_CONFIG_ERROR_MESSAGE, fallbackProfileId); throw moaZSException(message); } var mergedRequest = deliveryRequestTypeBuilder(request) .withConfig(mergedConfig) .build(); if (!validator.isTnvzComplete(mergedRequest)) { throw moaZSException(INCOMPLETE_TNVZ_ERROR_MESSAGE); } return mergedRequest; } } private String determineProfileIdFrom(ConfigType requestConfig) { return (requestConfig == null || requestConfig.getProfileID() == null || isProfileMissing(requestConfig.getProfileID())) ? "default" : requestConfig.getProfileID(); } private boolean isProfileMissing(String id) { return !configs.containsKey(id); } }