InstitutionSearchDocBuilder.kt 6.42 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * search-doc-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 org.memobase

21
import com.beust.klaxon.JsonArray
22
import com.beust.klaxon.JsonObject
23
import java.util.Properties
24
import org.apache.logging.log4j.LogManager
25
import org.memobase.helpers.Date
26
import org.memobase.helpers.ElasticSearchWrapper
27
28
29
import org.memobase.helpers.Extract
import org.memobase.helpers.InstitutionTypeMapper
import org.memobase.helpers.KEYS
Jonas Waeber's avatar
Jonas Waeber committed
30
import org.memobase.model.FacetContainer
31
32
33
import org.memobase.model.InstitutionSearchDoc
import org.memobase.model.LanguageContainer
import org.memobase.model.Schema
34
import org.memobase.rdf.NS
35

36
class InstitutionSearchDocBuilder(path: String, appSettings: Properties) {
37
    private val log = LogManager.getLogger("InstitutionSearchDocBuilder")
38
    private val institutionTypeMapper = InstitutionTypeMapper(path)
39
    private val elasticSearchWrapper = ElasticSearchWrapper(appSettings)
40

41
    fun transform(key: String, input: Map<String, JsonObject>): Schema {
42
        val institution =
43
                input["institution"] ?: throw InvalidInputException("No institution entity found in message $key.")
44
        val identifiers = mutableListOf<JsonObject>()
Jonas Waeber's avatar
Jonas Waeber committed
45
        val cantons = mutableListOf<FacetContainer>()
46
47
48
        val municipalities = mutableListOf<LanguageContainer>()
        val addresses = mutableListOf<String>()
        val postalCodes = mutableListOf<String>()
49

50
        input.values.forEach {
51
52
            when {
                it[KEYS.ricoType] == KEYS.LocationType.canton -> {
Jonas Waeber's avatar
Jonas Waeber committed
53
                    cantons.add(FacetContainer(extractAdminUnit(it, "canton", "NoCantonFound"), null, emptyList()))
54
55
56
57
58
59
60
                }
                it[KEYS.ricoType] == KEYS.LocationType.municipality -> {
                    municipalities.add(extractAdminUnit(it, "municipality", "NoCityFound"))
                }
                it[KEYS.ricoType] == KEYS.IdentifierType.main -> {
                    identifiers.add(it)
                }
61
                it[KEYS.atType] == NS.rico + KEYS.Place -> {
62
63
64
                    addresses.addAll(Extract.listOfStrings(it[KEYS.wikidataAddresses]))
                    postalCodes.addAll(Extract.listOfStrings(it[KEYS.wikidataPostalCodes]))
                }
65
66
            }
        }
67

68
        val type = institution[KEYS.wikidataInstance].let {
69
            when (it) {
70
71
72
73
74
75
76
77
78
                is String -> listOf(institutionTypeMapper.getValue(it))
                is JsonArray<*> -> it.map { any -> institutionTypeMapper.getValue(any as String) }
                else -> {
                    log.error("Found no institution types on institution $key")
                    emptyList()
                }
            }
        }

79
80
        val name = extractLanguageContainer(institution[KEYS.name], "NoNameFound")
        val description = extractLanguageContainer(institution[KEYS.descriptiveNote], "NoDescriptionFound")
Jonas Waeber's avatar
Jonas Waeber committed
81
        val id = Extract.extractIdValue(identifiers, KEYS.IdentifierType.main) ?: "NoIdentifierFound"
82
83
        val recordSetIds = Extract.listOfStrings(institution[KEYS.isHolderOf])

84
        return InstitutionSearchDoc(
85
86
87
88
89
90
91
92
                institutionId = id,
                published = institution[KEYS.isPublished].let {
                    when (it) {
                        is String -> it.toBoolean()
                        else -> {
                            log.error("Found no isPublished property on institution $key. Set to false.")
                            false
                        }
93
                    }
94
95
96
97
98
99
100
101
102
103
104
105
106
                },
                type = type,
                name = name,
                description = description,
                documentType = listOf(FacetContainer.placeholder("PLACEHOLDER")),
                keyVisualLink = institution[KEYS.wikidataImage].let { if (it != null) it as String else "NoKeyVisualLinkDefined" },
                canton = cantons,
                city = municipalities,
                address = addresses,
                postalCodes = postalCodes,
                numberOfRecordSets = recordSetIds.count(),
                numberOfDocuments = recordSetIds
                        .map { value -> elasticSearchWrapper.countNumberOfDocuments(value) }
Jonas Waeber's avatar
Jonas Waeber committed
107
                        .sum(),
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
                teaserColor = institution[KEYS.teaserColor].let {
                    if (it == null) {
                        log.error("No teaser colour found for institution $id.")
                        ""
                    } else
                        it as String
                },
                teaserColorComputed = institution[KEYS.teaserColorComputed].let {
                    if (it == null) {
                        log.error("No computed teaser colour found for institution $id.")
                        ""
                    } else
                        it as String
                },
                lastUpdatedDate = Date.now
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

    private fun extractLanguageContainer(value: Any?, placeholder: String): LanguageContainer {
        return Extract.languageContainer("institution", value).let { items ->
            when {
                items.isEmpty() -> {
                    LanguageContainer.placeholder(placeholder)
                }
                items.size == 1 -> {
                    items[0]
                }
                else -> {
                    items.reduce { acc, languageContainer -> acc.merge(languageContainer) }
                }
            }
        }
    }

    private fun extractAdminUnit(item: JsonObject, parent: String, placeholder: String): LanguageContainer {
        return item[KEYS.name].let { name ->
            Extract.languageContainer(parent, name).let {
                when {
                    it.isEmpty() -> LanguageContainer.placeholder(placeholder)
                    else -> it.reduce { acc, languageContainer -> acc.merge(languageContainer) }
                }
            }
        }
    }
152
}