KafkaTopology.kt 2.06 KB
Newer Older
Jonas Waeber's avatar
Jonas Waeber committed
1
/*
Jonas Waeber's avatar
Jonas Waeber committed
2
 * Drupal Sync Service
Jonas Waeber's avatar
Jonas Waeber committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 * 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 org.apache.jena.rdf.model.Model
Jonas Waeber's avatar
Jonas Waeber committed
22
23
24
import org.apache.kafka.streams.StreamsBuilder
import org.apache.kafka.streams.Topology
import org.apache.logging.log4j.LogManager
25
26
27
import org.memobase.model.Input
import org.memobase.model.Institution
import org.memobase.model.RecordSet
Jonas Waeber's avatar
Jonas Waeber committed
28
29
30
import org.memobase.settings.SettingsLoader

class KafkaTopology(private val settings: SettingsLoader) {
31
    private val log = LogManager.getLogger("DrupalSyncProcessor")
32
    private val transformer = RdfTransformer(settings.appSettings)
Jonas Waeber's avatar
Jonas Waeber committed
33
34
35
36
    fun build(): Topology {
        val builder = StreamsBuilder()
        val stream = builder.stream<String, String>(settings.inputTopic)
        stream
37
38
39
            .flatMapValues { value -> JSON.parseJson(value) }
            .flatMapValues { value -> mapJson(value) }
            .map { _, value -> Util.writeModel(value.first, value.second) }
Jonas Waeber's avatar
Jonas Waeber committed
40
41
42
43
44
            .to(settings.outputTopic)

        return builder.build()
    }

45
    private fun mapJson(input: Input): List<Pair<String, Model>> {
Jonas Waeber's avatar
Jonas Waeber committed
46
        return when (input) {
47
48
49
50
51
52
            is Institution -> listOf(transformer.createInstitution(input))
            is RecordSet -> listOf(transformer.createRecordSet(input))
            else -> {
                log.error("Could not cast input to institution or record set: $input.")
                return emptyList()
            }
Jonas Waeber's avatar
Jonas Waeber committed
53
        }
Jonas Waeber's avatar
Jonas Waeber committed
54
55
    }
}