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; @Component public class DeliveryRequestAugmenter { private final ConfigUtil util; private final Map configs; 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) { this.configs = deliveryRequestConfigs; this.util = util; } /** * Augments an incoming {@code request} by filling gaps with config- or default parameters. * * @param request * @return augmented request */ public DeliveryRequestType augment(DeliveryRequestType request) { var requestConfig = request.getConfig(); var fallbackProfileId = determineProfileIdFrom(requestConfig); var fallbackConfig = configs.get(fallbackProfileId); if (fallbackConfig == null) { if (util.isComplete(requestConfig)) return request; else throw moaZSException(INCOMPLETE_CONFIG_ERROR_MESSAGE); } else { var mergedConfig = (requestConfig == null) ? fallbackConfig : util.merge(requestConfig, fallbackConfig); if (util.isComplete(mergedConfig)) { return deliveryRequestTypeBuilder(request) .withConfig(mergedConfig) .build(); } else { throw moaZSException(INCOMPLETE_MERGED_CONFIG_ERROR_MESSAGE, fallbackProfileId); } } } 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); } }