package at.gv.egiz.moazs.preprocess; import at.gv.egiz.moazs.scheme.Marshaller; import at.gv.zustellung.app2mzs.xsd.ConfigType; import at.gv.zustellung.app2mzs.xsd.DeliveryRequestType; import at.gv.zustellung.app2mzs.xsd.ObjectFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; import java.util.Map; import static at.gv.egiz.moazs.MoaZSException.moaZSException; import static at.gv.egiz.moazs.util.NullCoalesce.coalesce; import static at.gv.zustellung.app2mzs.xsd.DeliveryRequestType.deliveryRequestTypeBuilder; @Component public class DeliveryRequestAugmenter { private static final Logger log = LoggerFactory.getLogger(DeliveryRequestAugmenter.class); private static final ObjectFactory FACTORY = new ObjectFactory(); private final ConfigUtil util; private final Map configs; private final Marshaller mzsMarshaller; private static final String CONFIG_MISSING_ERROR_MSG = "Delivery request configuration is missing."; @Autowired public DeliveryRequestAugmenter(Map deliveryRequestConfigs, ConfigUtil util, Marshaller mzsMarshaller) { this.configs = deliveryRequestConfigs; this.util = util; this.mzsMarshaller = mzsMarshaller; } /** * 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); trace("Request config", requestConfig); trace("Fallback config", fallbackConfig); var augmentedConfig = (requestConfig != null && fallbackConfig != null) ? util.merge(requestConfig, fallbackConfig) : coalesce(requestConfig, fallbackConfig) .orElseThrow(()-> moaZSException(CONFIG_MISSING_ERROR_MSG)); trace("Augmented config", augmentedConfig); var augmentedRequest = deliveryRequestTypeBuilder(request) .withConfig(augmentedConfig) .build(); return augmentedRequest; } private String determineProfileIdFrom(@Nullable ConfigType requestConfig) { return (requestConfig == null || requestConfig.getProfileID() == null || isProfileMissing(requestConfig.getProfileID())) ? "default" : requestConfig.getProfileID(); } private boolean isProfileMissing(String id) { return !configs.containsKey(id); } private void trace(String description, ConfigType config) { if (log.isTraceEnabled()) { log.trace("{} : {}", description, mzsMarshaller.marshallXml(FACTORY.createConfig(config))); } } }