YamlLoader.kt 2.12 KB
Newer Older
Jonas Waeber's avatar
Jonas Waeber committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * mapper-service
 * Copyright (C) 2020 Memoriav
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package ch.memobase.mapping

21
import ch.memobase.exceptions.InvalidMappingException
22
23
import ch.memobase.settings.CustomEnvConfig
import ch.memobase.settings.MissingSettingException
24
import java.io.ByteArrayInputStream
Jonas Waeber's avatar
Jonas Waeber committed
25
26
27
28
29
30
import java.util.Optional
import org.snakeyaml.engine.v2.api.Load
import org.snakeyaml.engine.v2.api.LoadSettings
import org.snakeyaml.engine.v2.exceptions.DuplicateKeyException
import org.snakeyaml.engine.v2.exceptions.MissingEnvironmentVariableException

31
class YamlLoader(private val data: ByteArray) {
Jonas Waeber's avatar
Jonas Waeber committed
32
33
34
35
36
37
38
39
40

    fun load(): Iterable<Any> {
        val settings =
            LoadSettings.builder().setEnvConfig(Optional.of(CustomEnvConfig())).build()
        val load = Load(settings)
        return try {
            if (data.isEmpty()) {
                throw InvalidMappingException("The mapping file may not be empty!")
            }
41
            load.loadAllFromInputStream(ByteArrayInputStream(data)) as Iterable<Any>
Jonas Waeber's avatar
Jonas Waeber committed
42
43
44
45
46
47
48
49
50
51
        } catch (ex: MissingEnvironmentVariableException) {
            throw MissingSettingException("env", ex.localizedMessage)
        } catch (ex: ClassCastException) {
            throw InvalidMappingException("Top level structure of the mapping file must be a map!")
        } catch (ex: DuplicateKeyException) {
            // TODO: Figure out why this exception is not properly caught...
            throw InvalidMappingException("Duplicate Key Detected: ${ex.localizedMessage}.")
        }
    }
}