JsonToYamlByRuleWriter.kt
/*
Copyright (C) 2026 Sber
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
In any derivative products, you must retain the information of
owner of the original code and provide clear attribution to the project
https://dochub.info
The use of this product or its derivatives for any purpose cannot be a secret.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Maintainers:
Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025
Contributors:
Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025
*/
package org.archtool.archloader.service.zip.parsing
import java.nio.file.Path
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.archtool.archloader.exception.UserDataException
import tools.jackson.databind.JsonNode
import tools.jackson.dataformat.yaml.YAMLMapper
@Service
class JsonToYamlByRuleWriter(
private val yamlMapper: YAMLMapper,
) {
private val log = LoggerFactory.getLogger(javaClass)
fun jsonToYamlInZip(payload: JsonNode, zipOutputPath: Path, rules: Set<JsonElementExtractionRule>) {
val outputFile = zipOutputPath.toFile()
val allKeys = payload.propertyNames().toMutableSet()
val missingRequiredKeys = getMissingRequiredKeys(allKeys = allKeys, rules = rules)
if (missingRequiredKeys.isNotEmpty()) {
throw UserDataException("При обработке payload не найдены обязательные ключи $missingRequiredKeys")
}
ZipOutputStream(outputFile.outputStream()).use { zipOut ->
allKeys.forEach { key ->
val attrToSave = payload.get(key)
if (attrToSave == null) {
log.error(
"КРИТИЧЕСКАЯ ОШИБКА: атрибут {} объявлен в propertyNames(), но get() вернул null. Это указывает на повреждение payload.json",
key
)
throw RuntimeException("Невозможно прочитать атрибут '$key' из payload — он объявлен в списке ключей, но невозможно получить")
}
log.trace("Прочитан элемент {} и значение {}", key, attrToSave)
var readyRule = rules.firstOrNull { rule -> rule.attrName == key }
if (readyRule == null) {
log.trace("Для элемента {} не задано правило в конфигурации, сохраним в {}", key, OTHER_DIR_PATH)
readyRule = generateDefaultRule(key)
}
try {
zipOut.putNextEntry(ZipEntry(readyRule.pathToSave))
} catch (e: Exception) {
throw RuntimeException(
"Ошибка записи в итоговый файл элемента, не удалось создать entry в zip ${readyRule.pathToSave}",
e
)
}
try {
val payload = yamlMapper.createObjectNode()
payload.set(readyRule.attrName, attrToSave)
yamlMapper.writeValue(zipOut, payload)
} catch (e: Exception) {
throw RuntimeException("Ошибка записи в итоговый файл элемента ${readyRule.attrName}", e)
} finally {
zipOut.closeEntry()
}
}
if (log.isDebugEnabled) {
logKeyDiff(rules, allKeys)
}
}
}
private fun getMissingRequiredKeys(
allKeys: MutableSet<String>,
rules: Set<JsonElementExtractionRule>,
): List<String> {
return rules.filter { it.required }
.map { it.attrName }
.filterNot { allKeys.contains(it) }
}
private fun generateDefaultRule(attrName: String): JsonElementExtractionRule {
return JsonElementExtractionRule(
attrName = attrName,
pathToSave = "$OTHER_DIR_PATH$attrName.yaml",
required = false
)
}
private fun logKeyDiff(
rules: Set<JsonElementExtractionRule>,
allKeys: MutableSet<String>,
) {
val remainingRuleKeys = rules.map { it.attrName }.toMutableSet()
allKeys.forEach { remainingRuleKeys.remove(it) }
if (remainingRuleKeys.isNotEmpty()) {
log.debug("В конфигурации есть ключи, которых не было в payload {}", remainingRuleKeys)
} else {
log.debug("Все ключи из конфигурации были найдены в payload")
}
}
companion object {
private const val OTHER_DIR_PATH = "other/"
}
}