KafkaTopology.kt 4.97 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
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
/*
 * Table Data Import 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

import com.beust.klaxon.Klaxon
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
import org.apache.kafka.streams.kstream.Predicate
import org.apache.logging.log4j.LogManager
import org.memobase.settings.SettingsLoader
import org.memobase.sftp.SftpClient
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.io.StringReader
import javax.xml.transform.TransformerFactory
import javax.xml.transform.sax.SAXResult
import javax.xml.transform.stream.StreamSource
import kotlin.system.exitProcess


class KafkaTopology(private val settings: SettingsLoader) {
    private val log = LogManager.getLogger("KafkaTopologySetup")
    private val sftpClient: SftpClient = SftpClient(settings.sftpSettings)
    private val xlstFilePath = settings.appSettings.getProperty("xsltFilePath")
    private val identifierFieldName = settings.appSettings.getProperty("identifierFieldName")
    private val recordTag = settings.appSettings.getProperty("recordTag")

    init {
        if (identifierFieldName == "placeholderValue") {
            log.error("Requires a value for identifier field name, but found default value.")
            exitProcess(1)
        }
    }

    private val factory = TransformerFactory.newInstance()
    private val xslt = StreamSource(FileInputStream(File(xlstFilePath)))
    private val transformer = factory.newTransformer(xslt)

    private val reportingTopic = settings.outputTopic + "-reporting"

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

        val errorFilter = builder
            .stream<String, String>(settings.inputTopic)
            .flatMapValues { _, value -> parseMessage(value) }
            .branch(
                Predicate { _, value -> value.format == Formats.error },
                Predicate { _, _ -> true }
            )

        // report filtered error message from previous job.
        errorFilter[0]
            .mapValues { key, _ ->
                Klaxon().toJsonString(
                    Report(
                        key,
                        ReportStatus.failure,
                        ReportMessages.processFailure(key, "The input file is invalid.")
                    )
                )
            }
            .to("${settings.outputTopic}-reporting")

        // filtered result simply sends ERROR along!
        errorFilter[0]
            .mapValues { _ -> "ERROR" }
            .to(settings.outputTopic)

        // report full process as failure
        errorFilter[0]
            .mapValues { key, _ ->
                Klaxon().toJsonString(
                    Report(
                        "xml-data-transform",
                        ReportStatus.failure,
                        ReportMessages.processFailure(key, "The input file is invalid.")
                    )
                )
            }
            .to(settings.processReportTopic)

        // TODO: Implement multi record xml documents splitter!
        val transformedValue = errorFilter[1]
            .mapValues { value -> sftpClient.open(File(value.path)) }
            .map { key, value -> transformXml(key, value) }

        streamOutput(transformedValue)

        return builder.build()
    }

    private fun streamOutput(stream: KStream<String, SAXContentHandler>) {
        stream
            .mapValues { value -> value.output.toString() }
            .to(settings.outputTopic)

        stream
            .mapValues { value -> value.report!!.toJson() }
            .to(reportingTopic)

        stream
            .mapValues { value -> value.report!!.toJson() }
            .to(settings.processReportTopic)
    }

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

    private fun transformXml(key: String, data: InputStream): KeyValue<String, SAXContentHandler> {
        val contentHandler = SAXContentHandler(key, identifierFieldName, recordTag)
        data.use {
            transformer.transform(StreamSource(it), SAXResult(contentHandler))
        }
        return KeyValue(contentHandler.identifier, contentHandler)
    }




}