KafkaTopology.kt 6.09 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 org.memobase

Jonas Waeber's avatar
Jonas Waeber committed
21
import com.beust.klaxon.Klaxon
22
import com.beust.klaxon.KlaxonException
Jonas Waeber's avatar
Jonas Waeber committed
23
import org.apache.kafka.streams.KeyValue
Jonas Waeber's avatar
Jonas Waeber committed
24
25
import org.apache.kafka.streams.StreamsBuilder
import org.apache.kafka.streams.Topology
26
27
import org.apache.kafka.streams.kstream.KStream
import org.apache.kafka.streams.kstream.Predicate
Jonas Waeber's avatar
Jonas Waeber committed
28
import org.apache.logging.log4j.LogManager
Jonas Waeber's avatar
Jonas Waeber committed
29
import org.memobase.builder.ResourceBuilder
30
import org.memobase.helpers.ReportStatus
Jonas Waeber's avatar
Jonas Waeber committed
31
import org.memobase.mapping.MappingConfig
Jonas Waeber's avatar
Jonas Waeber committed
32
33
import org.memobase.settings.SettingsLoader

34
35
class KafkaTopology(
    private val settings: SettingsLoader
Jonas Waeber's avatar
Jonas Waeber committed
36
37
) {
    private val log = LogManager.getLogger("KafkaTopology")
Jonas Waeber's avatar
Jonas Waeber committed
38
    private val config = MappingConfig(settings.appSettings.getProperty("configs"))
39
    private val reportTopic = settings.outputTopic + "-reporting"
Jonas Waeber's avatar
Jonas Waeber committed
40
41
42
43

    fun build(): Topology {
        val builder = StreamsBuilder()

Jonas Waeber's avatar
Jonas Waeber committed
44
45
        val stream = builder.stream<String, String>(settings.inputTopic)

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
        val jsonStream = stream.flatMapValues { value -> parseJsonFile(value) }
            .branch(
                Predicate { _, value -> value.containsKey("ERROR") },
                Predicate { _, _ -> true }
            )

        jsonStream[0]
            .mapValues { value -> value["ERROR"] as String }
            .to(settings.outputTopic)

        jsonStream[0]
            .mapValues { key, value ->
                Report(
                    key,
                    ReportStatus.failure,
                    "Failed to parse json input: $value."
                ).toJson()
            }
            .to(reportTopic)

        val extractedRecordIdStream = jsonStream[1]
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
            .mapValues { value -> buildResources(value) }
            .mapValues { value -> value.extractRecordId() }


        val extractedRecordTypeValueStream = extractRecordId(extractedRecordIdStream)

        val hasIdAndTypeStream = extractRecordTypeValue(extractedRecordTypeValueStream)

        val completedMappingStream = hasIdAndTypeStream
            .mapValues { value -> value.generateRecord() }
            .mapValues { value -> value.generatePhysicalObject() }
            .mapValues { value -> value.generateDigitalObject() }
            .mapValues { value -> value.addDerivedConnection() }

        val recordStream = completedMappingStream.mapValues { value -> value.writeRecord() }
Jonas Waeber's avatar
Jonas Waeber committed
82
        objectOutput(recordStream)
Jonas Waeber's avatar
Jonas Waeber committed
83
84
        return builder.build()
    }
Jonas Waeber's avatar
Jonas Waeber committed
85

86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    private fun objectOutput(stream: KStream<String, Pair<KeyValue<String, String>, Report>>) {
        stream
            .map { _, value -> value.first }
            .to(settings.outputTopic)

        stream
            .map { _, value -> KeyValue(value.first.key, value.second.toJson()) }
            .to(reportTopic)
    }

    private fun buildResources(value: Map<String, String>): ResourceBuilder {
        return ResourceBuilder(
            config.uriField,
            config.recordType,
            config.recordFieldMappers,
            config.physicalObjectFieldMappers,
            config.digitalObjectFieldMappers,
            value,
            settings.appSettings.getProperty("institutionId"),
105
106
            settings.appSettings.getProperty("recordSetId"),
            config.sponsoredByMemoriav
107
108
109
110
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
        )
    }

    private fun extractRecordId(stream: KStream<String, ResourceBuilder>): KStream<String, ResourceBuilder> {
        val hasRecordId = stream.branch(
            Predicate { _, value -> value.hasRecordId() },
            Predicate { _, _ -> true }
        )
        // early termination if there is no record id!
        val noRecordId = hasRecordId[1]

        noRecordId
            .mapValues { _ -> "ERROR: No record id specified!" }
            .to(settings.outputTopic)

        noRecordId
            .mapValues { key, value -> value.failureReport(key).toJson() }
            .to(reportTopic)

        return hasRecordId[0]
            .mapValues { value -> value.extractRecordTypeValue() }
    }

    private fun extractRecordTypeValue(stream: KStream<String, ResourceBuilder>): KStream<String, ResourceBuilder> {
        val hasRecordTypeValue = stream
            .branch(
                Predicate { _, value -> value.hasRecordType() },
                Predicate { _, _ -> true }
            )

        val noRecordTypeValue = hasRecordTypeValue[1]

        noRecordTypeValue
            .mapValues { _ -> "ERROR: No record type value specified!" }
            .to(settings.outputTopic)

        noRecordTypeValue
            .mapValues { key, value -> value.failureReport(key).toJson() }
            .to(reportTopic)

        return hasRecordTypeValue[0]
    }
Jonas Waeber's avatar
Jonas Waeber committed
149

Jonas Waeber's avatar
Jonas Waeber committed
150
    private fun parseJsonFile(message: String): List<Map<String, String>> {
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
        return if (message.contains("ERROR")) {
            listOf(mapOf(Pair("ERROR", message)))
        } else {
            try {
                Klaxon().parse<Map<String, String>>(message).let {
                    return if (it != null) {
                        listOf(it)
                    } else {
                        listOf(mapOf(Pair("ERROR", "ERROR: Could not parse message: $message.")))
                    }
                }
            } catch (ex: KlaxonException) {
                listOf(
                    mapOf(
                        Pair(
                            "ERROR",
                            "ERROR: Could not parse message: $message. Because of ${ex.localizedMessage}."
                        )
                    )
                )
Jonas Waeber's avatar
Jonas Waeber committed
171
172
173
            }
        }
    }
Jonas Waeber's avatar
Jonas Waeber committed
174
}