SAXContentHandler.kt 6.31 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
/*
 * xml-data-transform
 * 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/>.
 */

Jonas Waeber's avatar
Jonas Waeber committed
19
package org.memobase.xml
Jonas Waeber's avatar
Jonas Waeber committed
20

Jonas Waeber's avatar
Jonas Waeber committed
21
22
import ch.memobase.reporting.Report
import ch.memobase.reporting.ReportStatus
Jonas Waeber's avatar
Jonas Waeber committed
23
import com.beust.klaxon.JsonObject
Jonas Waeber's avatar
Jonas Waeber committed
24
import java.io.StringWriter
25
import org.apache.logging.log4j.LogManager
Jonas Waeber's avatar
Jonas Waeber committed
26
import org.memobase.Service
Jonas Waeber's avatar
Jonas Waeber committed
27
28
29
30
import org.xml.sax.Attributes
import org.xml.sax.ContentHandler
import org.xml.sax.Locator

Jonas Waeber's avatar
Jonas Waeber committed
31
32
33
34
35
36
37
38
39
40
/**
 * Class to transform a xml stream into a json representation. Expects a flat xml preprocessed with
 * a xslt if necessary.
 *
 * Can only handle elements up to one level deep and ignores attributes.
 *
 * @param key The key of the kafka message.
 * @param identifierFieldName The field name of the unique identifier of this record.
 * @param recordTag The root tag of the xml structure.
 */
Jonas Waeber's avatar
Jonas Waeber committed
41
42
43
44
45
class SAXContentHandler(
    private val key: String,
    private val identifierFieldName: String,
    private val recordTag: String
) :
Jonas Waeber's avatar
Jonas Waeber committed
46
    ContentHandler {
47
48
    private val log = LogManager.getLogger("SAXHandler")

Jonas Waeber's avatar
Jonas Waeber committed
49
50
51
    /**
     * The json representation of the xml stream after processing.
     */
Jonas Waeber's avatar
Jonas Waeber committed
52
    val output = StringWriter()
Jonas Waeber's avatar
Jonas Waeber committed
53
54
55
56

    /**
     * The identifier is used as a message key for the outgoing message.
     */
Jonas Waeber's avatar
Jonas Waeber committed
57
    var identifier: String? = null
Jonas Waeber's avatar
Jonas Waeber committed
58
    private var report: Report? = null
Jonas Waeber's avatar
Jonas Waeber committed
59
60
    private val jsonResult = JsonObject()

Jonas Waeber's avatar
Jonas Waeber committed
61
62
63
    /**
     * @return A report on the status of the transformation.
     */
Jonas Waeber's avatar
Jonas Waeber committed
64
65
66
67
    fun getReport(): Report {
        return report.let {
            it
                ?: Report(
Jonas Waeber's avatar
Jonas Waeber committed
68
                    identifier ?: key,
Jonas Waeber's avatar
Jonas Waeber committed
69
70
71
                    ReportStatus.fatal,
                    "Unknown Failure: No report found.",
                    Service.name
Jonas Waeber's avatar
Jonas Waeber committed
72
73
74
75
                )
        }
    }

Jonas Waeber's avatar
Jonas Waeber committed
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
    private var currentElementTag: String = ""
    private var currentInnerElementTag: String = ""
    private var currentElementContent: String = ""
    private var currentInnerElementContent: String = ""
    private val innerElements = mutableListOf<Pair<String, String>>()

    private val invalidPropertyNameCharacters = Regex("[.+,\\\\]")

    private var reportText = ""

    override fun setDocumentLocator(p0: Locator?) {
        // NOT NEEDED...
    }

    override fun startDocument() {
        // Do nothing...
    }

    override fun processingInstruction(p0: String?, p1: String?) {
        // NOT NEEDED
    }

    override fun skippedEntity(p0: String?) {
        // NOT NEEDED
    }

    override fun ignorableWhitespace(p0: CharArray?, p1: Int, p2: Int) {
        // Do Nothing
    }

    override fun startPrefixMapping(p0: String?, p1: String?) {
        // NOT NEEDED
    }

    override fun endPrefixMapping(p0: String?) {
        // NOT NEEDED.
    }

    override fun characters(characters: CharArray?, start: Int, size: Int) {
        if (characters != null) {
116
117
118
119
120
121
122
123
124
125
            val line = characters.joinToString("").trim()
            if (line.isNotEmpty()) {
                when {
                    currentInnerElementTag != "" -> {
                        currentInnerElementContent += line
                    }
                    currentElementTag != "" -> {
                        currentElementContent += line
                    }
                    else -> {
Jonas Waeber's avatar
Jonas Waeber committed
126
                        log.warn("Content without Tags: $line.")
127
128
                    }
                }
Jonas Waeber's avatar
Jonas Waeber committed
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
            }
        }
    }

    override fun startElement(uri: String?, localName: String?, qName: String?, attributes: Attributes?) {
        if (attributes != null && attributes.length > 0)
            reportText += "Found an attribute. There should be non left...\n"
        if (localName == null) {
            reportText += "Found no local name in element $uri.\n"
            return
        }
        if (localName.contains(invalidPropertyNameCharacters)) {
            reportText += "Contains invalid characters in property '$localName': $invalidPropertyNameCharacters."
            return
        }
        if (recordTag == localName)
            return

        if (currentElementTag == "") {
            currentElementTag = localName

        } else {
            currentInnerElementTag = localName
        }
    }

    override fun endElement(uri: String?, localName: String?, qName: String?) {
        if (recordTag == localName)
            return

159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
        when {
            currentElementTag == localName -> {
                if (currentElementTag == identifierFieldName) {
                    identifier = currentElementContent
                }
                if (innerElements.isEmpty()) {
                    if (currentElementContent.isNotEmpty()) {
                        jsonResult[currentElementTag] = currentElementContent
                    }
                } else {
                    jsonResult[currentElementTag] = innerElements.toMap()
                    innerElements.clear()
                }
                currentElementTag = ""
                currentElementContent = ""
Jonas Waeber's avatar
Jonas Waeber committed
174
            }
175
176
177
            currentInnerElementTag == localName -> {
                if (currentInnerElementContent.isNotEmpty()) {
                    innerElements.add(Pair(currentInnerElementTag, currentInnerElementContent))
178
                }
179
180
                currentInnerElementTag = ""
                currentInnerElementContent = ""
Jonas Waeber's avatar
Jonas Waeber committed
181
            }
182
183
            else -> {
                reportText += "Unmatched end element: $localName.\n"
184
            }
Jonas Waeber's avatar
Jonas Waeber committed
185
186
187
188
189
190
        }
    }

    override fun endDocument() {
        output.write(jsonResult.toJsonString())
        report = Report(
Jonas Waeber's avatar
Jonas Waeber committed
191
            id = identifier ?: key,
Jonas Waeber's avatar
Jonas Waeber committed
192
193
194
            status = if (reportText.isEmpty()) ReportStatus.success else ReportStatus.fatal,
            message = if (reportText.isEmpty()) "Successfully transformed xml to json!" else reportText.trim(),
            step = Service.name
Jonas Waeber's avatar
Jonas Waeber committed
195
196
197
        )
    }
}