YamlConfigReader.java

/*
 * Copyright 2023 Morimekta Utils Authors
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package net.morimekta.config.readers;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import net.morimekta.config.ConfigException;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.function.Consumer;

import static java.util.Objects.requireNonNull;
import static net.morimekta.config.ConfigException.asConfigException;
import static net.morimekta.file.FileUtil.readCanonicalPath;

/**
 * Read config as YAML.
 *
 * @param <ConfigType> The config type.
 */
public class YamlConfigReader<ConfigType> implements ConfigReader<ConfigType> {
    private final ObjectMapper      mapper;
    private final Class<ConfigType> configType;

    /**
     * @param configType The config type class.
     */
    public YamlConfigReader(Class<ConfigType> configType) {
        this(configType, ObjectMapper::findAndRegisterModules);
    }

    /**
     * @param configType The config type class.
     * @param init       A consumer callback to initialize the object mapper. E.g.
     *                   if extra modules needs to be loaded.
     */
    public YamlConfigReader(Class<ConfigType> configType, Consumer<ObjectMapper> init) {
        this.mapper = new ObjectMapper(new YAMLFactory());
        this.configType = configType;
        init.accept(mapper);
    }

    @Override
    public ConfigType readConfig(Path file) throws IOException, ConfigException {
        var canonical = readCanonicalPath(requireNonNull(file, "file == null"));
        if (!Files.exists(canonical)) {
            throw new FileNotFoundException("No such config file " + file);
        }
        if (!Files.isRegularFile(canonical)) {
            throw new IOException("Config path " + file + " is not a regular file.");
        }
        try (var in = Files.newInputStream(canonical, StandardOpenOption.READ);
             var reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
            try {
                return mapper.readValue(reader, configType);
            } catch (JsonMappingException | JsonParseException e) {
                throw asConfigException(e);
            }
        }
    }
}