KafkaTopology.kt 4.9 KB
Newer Older
Jonas Waeber's avatar
Jonas Waeber committed
1
/*
2
 * XML Data Import 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
22
import ch.memobase.kafka.utils.ConfigJoiner
import ch.memobase.kafka.utils.models.ImportService
Jonas Waeber's avatar
Jonas Waeber committed
23
import com.beust.klaxon.Klaxon
Jonas Waeber's avatar
Jonas Waeber committed
24
import org.apache.kafka.common.serialization.Serdes
Jonas Waeber's avatar
Jonas Waeber committed
25
26
27
28
import org.apache.kafka.streams.KeyValue
import org.apache.kafka.streams.StreamsBuilder
import org.apache.kafka.streams.Topology
import org.apache.kafka.streams.kstream.KStream
Jonas Waeber's avatar
Jonas Waeber committed
29
30
import org.apache.logging.log4j.LogManager
import org.memobase.models.*
Jonas Waeber's avatar
Jonas Waeber committed
31
32
import org.memobase.settings.SettingsLoader
import org.memobase.sftp.SftpClient
Jonas Waeber's avatar
Jonas Waeber committed
33
34
35
36
37
import org.memobase.utils.MissingIdentifierException
import org.memobase.utils.SerdeMessage
import org.memobase.utils.XsltException
import org.memobase.xml.XMLTransformer
import settings.HeaderExtractionTransformSupplier
Jonas Waeber's avatar
Jonas Waeber committed
38
39
40
41
42
import java.io.File
import java.io.StringReader


class KafkaTopology(private val settings: SettingsLoader) {
Jonas Waeber's avatar
Jonas Waeber committed
43
    private val log = LogManager.getLogger("XMLDataImport")
Jonas Waeber's avatar
Jonas Waeber committed
44
    private val sftpClient: SftpClient = SftpClient(settings.sftpSettings)
Jonas Waeber's avatar
Jonas Waeber committed
45
46
47
48
49
50
51
52
    private val xmlTransformer = XMLTransformer()
    private val configJoiner = ConfigJoiner<Message, ByteArray>(
        ImportService.Transform,
        SerdeMessage(),
        Serdes.ByteArray(),
        xmlTransformer::xsltFunction
    )
    private val reportingTopic = settings.processReportTopic
Jonas Waeber's avatar
Jonas Waeber committed
53
54
55
56

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

Jonas Waeber's avatar
Jonas Waeber committed
57
58
59
60
        val configStream = builder.stream<ByteArray, ByteArray>("import-process-config")


        val dataStream = builder
Jonas Waeber's avatar
Jonas Waeber committed
61
62
            .stream<String, String>(settings.inputTopic)
            .flatMapValues { _, value -> parseMessage(value) }
63
            .filter { _, value -> value.format != Formats.xml }
Jonas Waeber's avatar
Jonas Waeber committed
64
65
66
67
68
69
70
71
72
73
74
75
76

        val joinedStream = configJoiner.join(dataStream, configStream)

        val saxHandlerStream = joinedStream
            .mapValues { value -> Input(value.left, value.right) }
            .transformValues(HeaderExtractionTransformSupplier<Input>())
            .mapValues { value ->
                Content(
                    value.first.message,
                    value.second,
                    value.first.xsltData,
                    sftpClient.open(File(value.first.message.path))
                )
Jonas Waeber's avatar
Jonas Waeber committed
77
            }
Jonas Waeber's avatar
Jonas Waeber committed
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
            .map { key, value ->
                value.inputStream.use {
                    try {
                        val output =
                            xmlTransformer.applyXSLT(key, value.headerMetadata, value.inputStream, value.xsltData)
                        KeyValue(
                            output.first,
                            Pair(output.second.output.toString(), output.second.getReport())
                        )
                    } catch (ex: XsltException) {
                        log.error(ex.message)
                        KeyValue(
                            key, Pair(
                                null, Report(
                                    key,
                                    ReportStatus.failure,
                                    ex.localizedMessage
                                )
                            )
                        )
Jonas Waeber's avatar
Jonas Waeber committed
98

Jonas Waeber's avatar
Jonas Waeber committed
99
100
101
102
103
104
105
106
107
108
109
                    } catch (ex: MissingIdentifierException) {
                        log.error(ex.message)
                        KeyValue(
                            key, Pair(
                                null, Report(
                                    key,
                                    ReportStatus.failure,
                                    ex.localizedMessage
                                )
                            )
                        )
Jonas Waeber's avatar
Jonas Waeber committed
110

Jonas Waeber's avatar
Jonas Waeber committed
111
112
113
114
                    }
                }
            }
        streamOutput(saxHandlerStream)
Jonas Waeber's avatar
Jonas Waeber committed
115
116
117
        return builder.build()
    }

Jonas Waeber's avatar
Jonas Waeber committed
118
    private fun streamOutput(stream: KStream<String, Pair<String?, Report>>) {
Jonas Waeber's avatar
Jonas Waeber committed
119
        stream
Jonas Waeber's avatar
Jonas Waeber committed
120
121
            .filter { _, value -> value != null }
            .mapValues { value -> value.first }
Jonas Waeber's avatar
Jonas Waeber committed
122
123
124
            .to(settings.outputTopic)

        stream
Jonas Waeber's avatar
Jonas Waeber committed
125
            .mapValues { value -> value.second.toJson() }
Jonas Waeber's avatar
Jonas Waeber committed
126
127
128
129
130
131
132
133
134
135
            .to(reportingTopic)
    }

    private fun parseMessage(value: String): List<Message> {
        return Klaxon().parse<Message>(StringReader(value)).let {
            if (it == null) emptyList()
            else listOf(it)
        }
    }
}