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

36

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

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

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

69
        val type = institution[KEYS.wikidataInstance].let {
70
            when (it) {
71
72
73
74
75
76
77
78
79
                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()
                }
            }
        }

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

85
        return InstitutionSearchDoc(
86
87
88
89
90
91
92
93
                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
                        }
94
                    }
95
96
97
98
99
100
101
102
103
104
105
106
107
                },
                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
108
                        .sum(),
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
                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
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

    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) }
                }
            }
        }
    }
153
}