KafkaTopology.kt 5.9 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
/*
 * Media Linker
 * 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 java.io.ByteArrayInputStream
import java.io.StringWriter
import kotlin.system.exitProcess
import org.apache.jena.rdf.model.Model
import org.apache.jena.rdf.model.ModelFactory
import org.apache.jena.rdf.model.Resource
import org.apache.jena.rdf.model.impl.StatementImpl
import org.apache.kafka.streams.StreamsBuilder
import org.apache.kafka.streams.Topology
import org.apache.kafka.streams.kstream.Predicate
import org.apache.logging.log4j.LogManager
import org.memobase.rdf.EBUCORE
import org.memobase.rdf.RDF
import org.memobase.rdf.RICO
import org.memobase.reports.ReportMessages
import org.memobase.reports.ReportStatus
import org.memobase.settings.SettingsLoader
import org.memobase.sftp.SftpClient

class KafkaTopology(private val settings: SettingsLoader) {
    private val log = LogManager.getLogger("MediaLinker")

    private val sftpClient = SftpClient(settings.sftpSettings)

    private val files = createMediaFileList(settings.appSettings.getProperty("recordSetId"))

    private fun createMediaFileList(setting: String): List<String> {
        return try {
            sftpClient.listFiles("/$setting/media")
        } catch (ex: Exception) {
            ex.printStackTrace()
            log.error(ex.localizedMessage + ": /$setting/media")
            exitProcess(1)
        }
    }

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

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

        val stream = builder.stream<String, ByteArray>(settings.inputTopic)

        val instantiationBranch = stream
            .mapValues { value -> createModel(value) }
            .mapValues { value -> extractSubjects(value) }
            .branch(
                Predicate { _, value -> isDigitalObjectWithoutLocator(value.second) },
                Predicate { _, _ -> true }
            )

        val updateDigitalObjects = instantiationBranch[0]
            .mapValues { value -> enrichSftpLocator(value) }
            .mapValues { value ->
                val out = StringWriter()
                value.first.write(out)
                out.toString()
            }

        updateDigitalObjects
            .to(settings.outputTopic)

        updateDigitalObjects
            .mapValues { readOnlyKey, _ ->
                Klaxon().toJsonString(
                    Report(
                        readOnlyKey,
                        ReportStatus.success,
                        "Added sftp locator link to digital resource."
                    )
                )
            }
            .to(reportingTopic)

        val unchangedWrittenResources = instantiationBranch[1]
            .mapValues { value ->
                val out = StringWriter()
                value.first.write(out)
                out.toString()
            }

        unchangedWrittenResources
            .to(settings.outputTopic)

        unchangedWrittenResources
            .mapValues { key, _ -> Klaxon().toJsonString(Report(key, ReportStatus.success, "No changes made.")) }
            .to(reportingTopic)

        return builder.build()
    }

    private fun extractSubjects(model: Model): Pair<Model, Resource> {
        return Pair(model, model.listSubjectsWithProperty(RDF.type, RICO.Instantiation).next())
    }

    private fun isDigitalObjectWithoutLocator(res: Resource): Boolean {
        return res.hasProperty(RICO.type, "digitalObject") && !res.hasProperty(EBUCORE.locator)
    }

    private fun createModel(data: ByteArray): Model {
        val model = ModelFactory.createDefaultModel()
        model.read(ByteArrayInputStream(data), "", "NTRIPLES")
        return model
    }

    private fun enrichSftpLocator(data: Pair<Model, Resource>): Pair<Model, Report> {
        var isEnriched = false
        var link = ""
        for (stmt in data.second.listProperties(RICO.identifiedBy)) {
            if (stmt != null) {
                if (stmt.`object`.isResource) {
                    val resource = stmt.`object`.asResource()
                    if (resource.hasLiteral(RICO.type, "original")) {
                        val value = resource.getProperty(RICO.identifier).literal
                        for (file in files) {
                            if (file.contains(value.string)) {
                                link = "sftp://$file"
                                val literal = data.first.createLiteral(link)
                                data.first.add(StatementImpl(data.second, EBUCORE.locator, literal))
                                isEnriched = true
                            }
                        }
                    }
                }
            }
        }
        if (isEnriched) {
            return Pair(
                data.first,
                Report(
                    data.second.id.labelString,
                    ReportStatus.success,
                    ReportMessages.reportSuccess(data.second.id.labelString, link)
                )
            )
        } else {
            return Pair(
                data.first,
                Report(
                    data.second.id.labelString,
                    ReportStatus.failure,
                    ReportMessages.reportFailure(data.second.id.labelString)
                )
            )
        }
    }
}