1010 ******************************************************************************/
1111package com.redhat.devtools.intellij.kubernetes.editor
1212
13+ import com.fasterxml.jackson.databind.ObjectMapper
14+ import com.fasterxml.jackson.databind.node.ArrayNode
1315import com.intellij.json.JsonFileType
1416import com.intellij.openapi.fileTypes.FileType
1517import com.redhat.devtools.intellij.kubernetes.model.util.ResourceException
@@ -22,7 +24,6 @@ import org.jetbrains.yaml.YAMLFileType
2224object EditorResourceSerialization {
2325
2426 const val RESOURCE_SEPARATOR_YAML = " \n ---"
25- private const val RESOURCE_SEPARATOR_JSON = " ,\n "
2627
2728 /* *
2829 * Returns a list of [HasMetadata] for a given yaml or json string.
@@ -41,27 +42,49 @@ object EditorResourceSerialization {
4142 * @see JsonFileType.INSTANCE
4243 */
4344 fun deserialize (jsonYaml : String? , fileType : FileType ? , currentNamespace : String? ): List <HasMetadata > {
44- return if (jsonYaml == null
45- || ! isSupported(fileType)) {
46- emptyList()
47- } else {
48- val resources = jsonYaml
49- .split(RESOURCE_SEPARATOR_YAML )
50- .filter { jsonYaml -> jsonYaml.isNotBlank() }
51- if (resources.size > 1
52- && YAMLFileType .YML != fileType) {
53- throw ResourceException (
54- " ${fileType?.name ? : " File type" } is not supported for multi-resource documents. Only ${YAMLFileType .YML .name} is." )
45+ return try {
46+ when {
47+ jsonYaml == null ->
48+ emptyList()
49+
50+ YAMLFileType .YML == fileType ->
51+ yaml2Resources(jsonYaml, currentNamespace)
52+
53+ JsonFileType .INSTANCE == fileType ->
54+ json2Resources(jsonYaml, currentNamespace)
55+
56+ else ->
57+ emptyList()
58+ }
59+ } catch (e: RuntimeException ) {
60+ throw ResourceException (" Invalid kubernetes yaml/json" , e.cause ? : e)
61+ }
62+ }
63+
64+ private fun yaml2Resources (yaml : String , currentNamespace : String? ): List <HasMetadata > {
65+ val resources = yaml
66+ .split(RESOURCE_SEPARATOR_YAML )
67+ .filter { yaml ->
68+ yaml.isNotBlank()
5569 }
56- try {
57- resources
58- .map { jsonYaml ->
59- setMissingNamespace(currentNamespace, createResource<GenericKubernetesResource >(jsonYaml))
60- }
61- .toList()
62- } catch (e: RuntimeException ) {
63- throw ResourceException (" Invalid kubernetes yaml/json" , e.cause ? : e)
70+ return resources
71+ .map { yaml ->
72+ setMissingNamespace(currentNamespace, createResource<GenericKubernetesResource >(yaml))
6473 }
74+ .toList()
75+ }
76+
77+ private fun json2Resources (json : String? , currentNamespace : String? ): List <HasMetadata > {
78+ val mapper = ObjectMapper ()
79+ val rootNode = mapper.readTree(json)
80+ return if (rootNode.isArray) {
81+ (rootNode as ArrayNode )
82+ .mapNotNull { node ->
83+ setMissingNamespace(currentNamespace, mapper.treeToValue(node, GenericKubernetesResource ::class .java))
84+ }
85+ .toList()
86+ } else {
87+ emptyList()
6588 }
6689 }
6790
0 commit comments