FieldParsers.kt 6.5 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.fields

21
import ch.memobase.exceptions.InvalidMappingException
22
import mapping.fields.LanguagePair
Jonas Waeber's avatar
Jonas Waeber committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

@Suppress("UNCHECKED_CAST")
object FieldParsers {
    private fun parsePrefixField(key: String, values: Map<String, String>): PrefixField {
        return values["field"].let { field ->
            if (field != null) {
                values["value"].let { value ->
                    if (value != null) {
                        PrefixField(key, value, field.trim())
                    } else {
                        throw InvalidMappingException("Section: $key. A 'value' subfield in prefix definition is required.")
                    }
                }
            } else {
                throw InvalidMappingException("Section: $key. A 'field' subfield in prefix definition is required.")
            }
        }
    }

    fun parseSimpleAnnotationField(key: String, item: Any): SimpleAnnotationField {
        return when (item) {
            is String -> DirectMapField(key, item.trim())
            is Map<*, *> -> {
                when {
                    item.containsKey("const") -> {
                        ConstantField(key, item["const"] as String)
                    }
                    item.containsKey("prefix") -> {
                        try {
                            parsePrefixField(key, item["prefix"] as Map<String, String>)
                        } catch (ex: ClassCastException) {
                            throw InvalidMappingException("Invalid structure for prefix field in section $key.")
                        }
                    }
                    else -> {
                        throw InvalidMappingException("Invalid key for a simple annotation field in section $key. Expected 'const' or 'prefix'.")
                    }
                }
            }
            else -> throw InvalidMappingException("Invalid value for a simple annotation field in section $key. Expected 'const' or 'prefix' or a direct map.")
        }
    }

    private fun parseFieldList(key: String, items: List<Any>): List<SimpleAnnotationField> {
        return items.map {
            parseSimpleAnnotationField(key, it)
        }
    }

    fun parseAnnotationField(entry: Map.Entry<String, Any>): AnnotationField {
        when (val value = entry.value) {
            is String -> return DirectMapField(entry.key, value)
            is Map<*, *> -> {
                return if (value.containsKey("const")) {
                    ConstantField(entry.key, value["const"] as String)
                } else if (value.containsKey("prefix")) {
                    try {
                        parsePrefixField(entry.key, value["prefix"] as Map<String, String>)
                    } catch (ex: ClassCastException) {
                        throw InvalidMappingException("Invalid structure for prefix field in section ${entry.key}.")
                    }
                } else {
85
                    val mutableList = mutableListOf<LanguagePair>()
Jonas Waeber's avatar
Jonas Waeber committed
86
87
88
89
90
91
92
93
94
95
96
97
                    for (k in value.keys) {
                        if (k is String && listOf("de", "it", "fr").contains(k)) {
                            val resultAnnotations = when (val items = value[k]) {
                                is List<*> -> {
                                    parseFieldList(entry.key, items as List<Any>)
                                }
                                is Any -> listOf(parseSimpleAnnotationField(entry.key, items))
                                else -> throw InvalidMappingException("Language map definition may not be empty.")
                            }
                            if (resultAnnotations.isEmpty()) {
                                throw InvalidMappingException("No valid definitions found under language tag $k in section ${entry.key}")
                            }
98
                            mutableList.add(LanguagePair(k, resultAnnotations))
Jonas Waeber's avatar
Jonas Waeber committed
99
100
101
102
103
104
105
106
107
108
                        }
                    }
                    if (mutableList.isNotEmpty()) {
                        LanguageField(entry.key, mutableList)
                    } else {
                        throw InvalidMappingException("Unknown key values in field mapping: $value. Use 'const' or 'de', 'fr', 'it' language tags!")
                    }
                }
            }
            is List<*> -> return ListField(
109
110
                    entry.key,
                    parseFieldList(entry.key, value as List<Any>)
Jonas Waeber's avatar
Jonas Waeber committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
            )
            else -> throw InvalidMappingException("Unknown structure for field mapping: $entry")
        }
    }

    fun parseFieldWithKeyValidation(
        parent: String,
        entry: Map.Entry<String, Any>,
        list: List<String>
    ): AnnotationField {
        if (list.contains(entry.key)) {
            return parseAnnotationField(entry)
        } else {
            throw InvalidMappingException("The section $parent does not allow the key: ${entry.key}. Use any of $list.")
        }
    }

    fun parseSubFieldProperties(
        parent: String,
        entries: Set<Map.Entry<String, Any>>,
        allowedSubFields: List<String>
    ): List<AnnotationField> {
        return entries.map { entry ->
            if (allowedSubFields.contains(entry.key)) {
                return@map parseAnnotationField(entry)
            } else {
                throw InvalidMappingException("The section $parent only allows the following subfields: $allowedSubFields.")
            }
        }
    }

    fun unpackSource(field: String, source: Map<String, Any>): String? {
        return if (field.contains('.')) {
            val fields = field.split('.')
            source[fields[0]].let {
                if (it is Map<*, *>) {
                    it[fields[1]] as String?
                } else {
                    null
                }
            }
        } else {
            source[field] as String?
        }
    }
}