diff options
Diffstat (limited to 'support/texplate/source/main/java/org/islandoftex/texplate/util/ValidatorUtils.java')
-rw-r--r-- | support/texplate/source/main/java/org/islandoftex/texplate/util/ValidatorUtils.java | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/support/texplate/source/main/java/org/islandoftex/texplate/util/ValidatorUtils.java b/support/texplate/source/main/java/org/islandoftex/texplate/util/ValidatorUtils.java new file mode 100644 index 0000000000..b400731242 --- /dev/null +++ b/support/texplate/source/main/java/org/islandoftex/texplate/util/ValidatorUtils.java @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: BSD-3-Clause +package org.islandoftex.texplate.util; + +import io.vavr.control.Try; +import org.islandoftex.texplate.exceptions.InvalidKeySetException; +import org.islandoftex.texplate.model.Template; + +import java.util.Map; + +/** + * Helper methods for validation. + * + * @version 1.0 + * @since 1.0 + */ +public class ValidatorUtils { + + /** + * Validates the data map based on the template requirements. + * + * @param template The template. + * @param map The data map. + * @return A boolean value indicating whether the data map is valid. + */ + private static boolean validateRequirements(Template template, + Map<String, String> map) { + return template.getRequirements().isEmpty() || + template.getRequirements().containsAll(map.keySet()); + } + + /** + * Validates the template pattern and the data map and throws an exception + * in case of failure. + * + * @param template The template. + * @param map The data map. + * @return The data map. + * @throws InvalidKeySetException There are invalid keys in the map. + */ + private static Map<String, String> checkValidation(Template template, + Map<String, String> map) + throws InvalidKeySetException { + + // for starters, we try to validate + // the template requirements + if (validateRequirements(template, map)) { + + // everything is validated, so + // we simply return the map + return map; + + } else { + + // the requirements were missing, + // so an exception is thrown + throw new InvalidKeySetException("The provided map does not " + + "contain all the keys required by the chosen " + + "template. Make sure to define such keys and try " + + "again. Check the user manual for further details."); + } + } + + /** + * Validates the template pattern and the data map. + * + * @param template The template. + * @param map The data map. + * @return The data map, enclosed in a Try object. + */ + public static Try<Map<String, String>> validate(Template template, + Map<String, String> map) { + return Try.of(() -> checkValidation(template, map)); + } + +} |