KafkaTopology.kt 7.17 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
/*
 * fedora-metadata-extractor
 * 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.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import org.apache.jena.rdf.model.Model
import org.apache.jena.rdf.model.ModelFactory
import org.apache.jena.rdf.model.Property
import org.apache.jena.rdf.model.Resource
Jonas Waeber's avatar
Jonas Waeber committed
27
28
import org.apache.jena.rdf.model.impl.SelectorImpl
import org.apache.jena.rdf.model.impl.StatementImpl
Jonas Waeber's avatar
Jonas Waeber committed
29
30
31
32
33
34
35
36
import org.apache.jena.riot.Lang
import org.apache.jena.riot.RDFDataMgr
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.fedora.FedoraClientImpl
import org.memobase.model.EventMessage
Jonas Waeber's avatar
Jonas Waeber committed
37
import org.memobase.rdf.*
Jonas Waeber's avatar
Jonas Waeber committed
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
import org.memobase.settings.SettingsLoader
import java.io.StringWriter
import java.net.URI
import java.nio.charset.StandardCharsets

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

    private val objectMapper = ObjectMapper().registerKotlinModule()
    private val fedora = FedoraClientImpl.builder()
        .urls(
            settings.appSettings.getProperty("fedora.internalDomain"),
            settings.appSettings.getProperty("fedora.externalDomain")
        )
        .credentials(
            settings.appSettings.getProperty("fedora.user"),
            settings.appSettings.getProperty("fedora.password")
        )
        .build()

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

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

        val objectBranches = stream
            .mapValues { value -> parseMessage(value) }
            .branch(
                // TODO: Add actual values.
                Predicate { _, value -> value.objectTypes == "rico:Record" },
                Predicate { _, value ->
Jonas Waeber's avatar
Jonas Waeber committed
71
72
                    value.objectTypes == "rico:CorporateBody" || value.objectTypes == "rico:RecordSet"
                }
Jonas Waeber's avatar
Jonas Waeber committed
73
74
75
76
77
78
79
            )

        objectBranches[0]
            .mapValues { value -> requestPrimaryResource(value) }
            .mapValues { value -> parseModel(value) }
            .mapValues { value -> addStatus(value) }
            .mapValues { value -> requestAdditionalRecordResources(value) }
Jonas Waeber's avatar
Jonas Waeber committed
80
            .mapValues { value -> filterFedoraProperties(value) }
Jonas Waeber's avatar
Jonas Waeber committed
81
82
83
84
85
86
87
            .mapValues { value -> writeModel(value) }
            .to(settings.outputTopic)

        objectBranches[1]
            .mapValues { value -> requestPrimaryResource(value) }
            .mapValues { value -> parseModel(value) }
            .mapValues { value -> addStatus(value) }
Jonas Waeber's avatar
Jonas Waeber committed
88
            .mapValues { value -> filterFedoraProperties(value) }
Jonas Waeber's avatar
Jonas Waeber committed
89
90
91
92
93
94
95
96
97
98
99
100
            .mapValues { value -> writeModel(value) }
            .to(settings.outputTopic)

        return builder.build()
    }

    private fun parseMessage(data: String): EventMessage {
        // can we assume that this is always correct? or should we handle parse errors?
        return objectMapper.readValue(data, EventMessage::class.java)
    }

    private fun requestPrimaryResource(message: EventMessage): Pair<EventMessage, String> {
Jonas Waeber's avatar
Jonas Waeber committed
101
        return Pair(message, fedora.fetchRdfResourceIntoString(URI.create(message.objectPath), "text/plain"))
Jonas Waeber's avatar
Jonas Waeber committed
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
    }

    private fun parseModel(input: Pair<EventMessage, String>): Pair<EventMessage, Model> {
        val model = ModelFactory.createDefaultModel()
        // TODO: Add exception handling
        RDFDataMgr.read(model, input.second.byteInputStream(StandardCharsets.UTF_8), Lang.NT)
        return Pair(input.first, model)
    }

    /**
     *  Adds the status of the event message to the core resources.
     *  Core resources are rico:Record, rico:CorporateBody (for institutions) and rico:RecordSet.
     *  Downstream services should remove this property before publishing the data to the outside world!
     */
    private fun addStatus(input: Pair<EventMessage, Model>): Model {
        listOf(RICO.Record, RICO.CorporateBody, RICO.RecordSet).forEach {
            val record = input.second.listSubjectsWithProperty(RDF.type, it).toList()
            if (record.isNotEmpty()) {
                record[0].addProperty(NS.hasStatus, input.first.eventType)
            }
        }
        return input.second
    }

    private fun requestAdditionalRecordResources(model: Model): Model {
        val subjects = model.listSubjectsWithProperty(RDF.type, RICO.Record).toList()
        if (subjects.isEmpty()) {
            // TODO: Improve exception handling
            throw Exception("The requested resource is not a record...")
        } else {
            val subject = subjects[0]!!
            requestAdditionalResources(subject, model, RICO.heldBy)
            requestAdditionalResources(subject, model, RICO.isPartOf)
            requestAdditionalResources(subject, model, RICO.hasInstantiation)
        }
        return model
    }

    private fun requestAdditionalResources(subject: Resource, model: Model, property: Property) {
        if (subject.hasProperty(property)) {
            subject.listProperties(property).forEach {
                if (it.`object`.isResource) {
                    val uri = it.`object`.asResource().uri
Jonas Waeber's avatar
Jonas Waeber committed
145
                    val data = fedora.fetchRdfResourceIntoString(URI(uri), "text/plain")
Jonas Waeber's avatar
Jonas Waeber committed
146
147
148
149
150
151
                    RDFDataMgr.read(model, data.byteInputStream(StandardCharsets.UTF_8), Lang.NT)
                }
            }
        }
    }

Jonas Waeber's avatar
Jonas Waeber committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
    private fun filterFedoraProperties(model: Model): Model {
        // This value is required for the compiler to be able to use the SelectorImpl constructor
        val typedValue: String? = null

        listOf(
            FEDORA.created,
            FEDORA.createdBy,
            FEDORA.lastModified,
            FEDORA.lastModifiedBy
        ).forEach {
            val createdStatements = model.listStatements(
                SelectorImpl(null, it, typedValue)
            )
            model.remove(createdStatements)
        }

        listOf(
            LDP.Container,
            LDP.BasicContainer,
            LDP.RDFSource,
            FEDORA.Container,
            FEDORA.Resource
        ).forEach {
            val createdStatements = model.listStatements(
                SelectorImpl(null, RDF.type, it)
            )
            model.remove(createdStatements)
        }
        return model
    }

Jonas Waeber's avatar
Jonas Waeber committed
183
184
    private fun writeModel(model: Model): String {
        val writer = StringWriter()
Jonas Waeber's avatar
Jonas Waeber committed
185
186
        RDFDataMgr.write(writer, model, Lang.NT)
        return writer.toString().trim()
Jonas Waeber's avatar
Jonas Waeber committed
187
188
    }
}