ParserConfigLoader.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.utils
import java.nio.file.Path
import java.nio.file.Paths
import org.archtool.archloader.configuration.properties.ArchProperties
import org.archtool.archloader.service.zip.parsing.JsonElementExtractionRule
import org.springframework.core.io.Resource
import org.springframework.core.io.ResourceLoader
import org.springframework.stereotype.Component
import tools.jackson.databind.DeserializationFeature
import tools.jackson.dataformat.yaml.YAMLMapper
import tools.jackson.module.kotlin.KotlinFeature
import tools.jackson.module.kotlin.KotlinModule
@Component
class ParserConfigLoader(
private val resourceLoader: ResourceLoader,
) {
// отдельный маппер, т.к. надо отключить FAIL_ON_NULL_FOR_PRIMITIVES и NullIsSameAsDefault только для этого конфига
private val yamlMapper = YAMLMapper.builder()
.addModule(KotlinModule.Builder().configure(KotlinFeature.NullIsSameAsDefault, true).build())
.disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES).build()
fun loadRulesByType(properties: ArchProperties): Map<String, Set<JsonElementExtractionRule>> {
val result = mutableMapOf<String, Set<JsonElementExtractionRule>>()
val mainConfigResource = loadResource(properties.configPath)
val mainConfig = try {
yamlMapper.readValue(mainConfigResource.inputStream, ArchConfigs::class.java)
} catch (e: Exception) {
throw IllegalStateException(
"Не удалось распарсить YAML-конфиг для загрузки списка архитектур и их правил (env или application.* файл): ${properties.configPath}",
e
)
}
mainConfig.types.forEach { config ->
val archType = config.type
val parsedRules = parseAndValidateYaml(config)
result[archType] = parsedRules
}
return result
}
private fun loadResource(location: String): Resource {
val resource = when {
location.startsWith("classpath:") -> resourceLoader.getResource(location)
else -> {
val fileLocation = if (!location.startsWith("file:")) {
"file:$location"
} else {
location
}
resourceLoader.getResource(fileLocation)
}
}
if (!resource.exists()) {
throw IllegalStateException("Конфигурационный файл не найден: $location")
}
return resource
}
private fun parseAndValidateYaml(config: ArchConfigs.Config): Set<JsonElementExtractionRule> {
val sourcePath = config.file
val resource = loadResource(sourcePath)
val configFile = try {
yamlMapper.readValue(resource.inputStream, ParserConfigFile::class.java)
} catch (e: Exception) {
throw IllegalStateException("${sourcePath}: Не удалось распарсить YAML-конфиг: $sourcePath для архитектуры ${config.type}", e)
}
val resultSetOfRules = mutableSetOf<JsonElementExtractionRule>()
// Список pathToSave, которые указаны в правилах. Используется для проверки дублей, т.к. они запрещены
val seenPathThSave = mutableSetOf<Path>()
configFile.rules.forEachIndexed { index, rule ->
// Валидация pathToSave
val pathToSave = rule.pathToSave.trim()
if (pathToSave.isEmpty()) {
throw IllegalStateException("${sourcePath}: Пустой путь сохранения в правиле ${rule.attrName} [$index]")
}
if (pathToSave.startsWith("/") || pathToSave.startsWith("\\")) {
throw IllegalStateException("${sourcePath}: Путь сохранения не должен начинаться со слеша: '$pathToSave' (правило ${rule.attrName} [$index])")
}
if (pathToSave.contains("..")) {
throw IllegalStateException("${sourcePath}: Путь содержит недопустимую навигацию '..': '$pathToSave' (правило ${rule.attrName} [$index])")
}
val normalizedPath = Paths.get(pathToSave).normalize()
if (!seenPathThSave.add(normalizedPath)) {
throw IllegalStateException("Дубль пути сохранения: '$pathToSave' ($normalizedPath) в файле $sourcePath (правило ${rule.attrName} [$index])")
}
val isNewElement = resultSetOfRules.add(
JsonElementExtractionRule(
attrName = rule.attrName, pathToSave = normalizedPath.toString(), required = rule.required
)
)
if (!isNewElement) {
throw IllegalStateException("Дубль названия атрибута: '${rule.attrName}' в файле $sourcePath (правило ${rule.attrName} [$index])")
}
}
return resultSetOfRules
}
private data class ParserConfigFile(
val rules: List<JsonElementExtractionRule>,
)
/**
* Список настроек архитектур
*/
private data class ArchConfigs(
val types: List<Config>,
) {
/**
* Отдельная архитектура и путь до ее конфигурации
*/
data class Config(
val type: String,
val file: String,
)
}
}