// SPDX-License-Identifier: BSD-3-Clause package org.islandoftex.texplate.model; import com.moandjiezana.toml.Toml; import io.vavr.control.Try; import org.islandoftex.texplate.exceptions.InvalidTemplateException; import java.nio.file.Path; import java.util.Map; /** * The configuration model. * * @version 1.0 * @since 1.0 */ public class Configuration { // template of the template private String template; // map of variables for the configuration private Map map; /** * Constructor. */ public Configuration() { } /** * Constructor. * * @param template The template. * @param map The map. */ public Configuration(String template, Map map) { this.template = template; this.map = map; } /** * Gets the template. * * @return The template. */ public String getTemplate() { return template; } /** * Sets the template. * * @param template The template. */ public void setTemplate(String template) { this.template = template; } /** * Gets the map. * * @return The map. */ public Map getMap() { return map; } /** * Sets the map. * * @param map The map. */ public void setMap(Map map) { this.map = map; } /** * Checks whether the configuration is valid. * * @return A boolean value indicating whether the configuration is valid. */ private boolean isValid() { return !(template == null || map == null); } /** * Reads the configuration from path. * * @param path The path. * @return Configuration. * @throws InvalidTemplateException The configuration is invalid. */ private static Configuration readFromPath(Path path) throws InvalidTemplateException { // the actual configuration Configuration configuration; // the default message String message = "The provided configuration file looks invalid. " + "Please make sure the configuration has a valid syntax and " + "try again. "; try { // gets the configuration configuration = new Toml().read(path.toFile()). to(Configuration.class); } catch (Exception exception) { // the configuration // seems invalid throw new InvalidTemplateException(message + "In this particular " + "scenario, there is a possibility that the configuration " + "file does not follow the TOML specification. Please " + "refer to the user manual for further details and a " + "possible fix. Also, the raised exception message can " + "give us some hints on what happened.", exception); } // checks whether the // configuration is valid if (configuration.isValid()) { // returns the configuration return configuration; } else { // the configuration // is invalid throw new InvalidTemplateException(message + "Specifically, some " + "mandatory fields are either absent or empty in the " + "configuration file. It is quite important to strictly " + "follow the configuration specification, as detailed in " + "the user manual, or the tool will not work at all."); } } /** * Gets the configuration from a path. * * @param path The path. * @return The configuration. */ public static Try of(Path path) { return Try.of(() -> readFromPath(path)); } }