diff options
| author | Paul-Christian Volkmer | 2023-10-05 10:51:49 +0200 |
|---|---|---|
| committer | Paul-Christian Volkmer | 2023-10-05 10:51:49 +0200 |
| commit | 7440fe1e23e730fd526a814cfde7cc86e105cf70 (patch) | |
| tree | 5c8ad5eae99f9add6624ac45efa4816f52a51005 /src/main/kotlin/dev/dnpm | |
| parent | 3f5c5e28fafa4aa35cb0744c28743074346e0a9c (diff) | |
Issue #12: Basic implementation of transformation service
Diffstat (limited to 'src/main/kotlin/dev/dnpm')
| -rw-r--r-- | src/main/kotlin/dev/dnpm/etl/processor/services/TransformationService.kt | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/main/kotlin/dev/dnpm/etl/processor/services/TransformationService.kt b/src/main/kotlin/dev/dnpm/etl/processor/services/TransformationService.kt new file mode 100644 index 0000000..9be0216 --- /dev/null +++ b/src/main/kotlin/dev/dnpm/etl/processor/services/TransformationService.kt @@ -0,0 +1,62 @@ +package dev.dnpm.etl.processor.services + +import com.fasterxml.jackson.databind.ObjectMapper +import com.jayway.jsonpath.JsonPath +import com.jayway.jsonpath.PathNotFoundException +import de.ukw.ccc.bwhc.dto.MtbFile + +class TransformationService(private val objectMapper: ObjectMapper) { + fun transform(mtbFile: MtbFile, vararg transformations: Transformation): MtbFile { + var json = objectMapper.writeValueAsString(mtbFile) + + transformations.forEach { transformation -> + val jsonPath = JsonPath.parse(json) + + try { + val before = transformation.path.substringBeforeLast(".") + val last = transformation.path.substringAfterLast(".") + + val existingValue = if (transformation.existingValue is Number) transformation.existingValue else transformation.existingValue.toString() + val newValue = if (transformation.newValue is Number) transformation.newValue else transformation.newValue.toString() + + jsonPath.set("$.$before.[?]$last", newValue, { + it.item(HashMap::class.java)[last] == existingValue + }) + } catch (e: PathNotFoundException) { + // Ignore + } + + json = jsonPath.jsonString() + } + + return objectMapper.readValue(json, MtbFile::class.java) + } + +} + +class Transformation private constructor(internal val path: String) { + + lateinit var existingValue: Any + private set + lateinit var newValue: Any + private set + + infix fun from(value: Any): Transformation { + this.existingValue = value + return this + } + + infix fun to(value: Any): Transformation { + this.newValue = value + return this + } + + companion object { + + fun of(path: String): Transformation { + return Transformation(path) + } + + } + +} |
