Migrate "ms/controllerblueprints" from ccsdk/apps
[ccsdk/cds.git] / ms / controllerblueprints / modules / blueprint-core / src / main / kotlin / org / onap / ccsdk / apps / controllerblueprints / core / utils / JacksonUtils.kt
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  * Modifications Copyright © 2018 IBM.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 package org.onap.ccsdk.apps.controllerblueprints.core.utils
18
19 import com.att.eelf.configuration.EELFLogger
20 import com.att.eelf.configuration.EELFManager
21 import com.fasterxml.jackson.annotation.JsonInclude
22 import com.fasterxml.jackson.databind.JsonNode
23 import com.fasterxml.jackson.databind.SerializationFeature
24 import com.fasterxml.jackson.databind.node.*
25 import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
26 import kotlinx.coroutines.Dispatchers
27 import kotlinx.coroutines.async
28 import kotlinx.coroutines.runBlocking
29 import kotlinx.coroutines.withContext
30 import org.apache.commons.io.IOUtils
31 import org.onap.ccsdk.apps.controllerblueprints.core.*
32 import java.io.File
33 import java.nio.charset.Charset
34
35 /**
36  *
37  *
38  * @author Brinda Santh
39  */
40 class JacksonUtils {
41     companion object {
42         private val log: EELFLogger = EELFManager.getInstance().getLogger(this::class.toString())
43         inline fun <reified T : Any> readValue(content: String): T =
44                 jacksonObjectMapper().readValue(content, T::class.java)
45
46         fun <T> readValue(content: String, valueType: Class<T>): T? {
47             return jacksonObjectMapper().readValue(content, valueType)
48         }
49
50         fun <T> readValue(node: JsonNode, valueType: Class<T>): T? {
51             return jacksonObjectMapper().treeToValue(node, valueType)
52         }
53
54         fun removeJsonNullNode(node: JsonNode) {
55             val it = node.iterator()
56             while (it.hasNext()) {
57                 val child = it.next()
58                 if (child.isNull) {
59                     it.remove()
60                 } else {
61                     removeJsonNullNode(child)
62                 }
63             }
64         }
65
66
67         fun getContent(fileName: String): String = getContent(normalizedFile(fileName))
68
69         fun getContent(file: File): String = runBlocking {
70             async {
71                 try {
72                     file.readText(Charsets.UTF_8)
73                 } catch (e: Exception) {
74                     throw BluePrintException("couldn't get file (${file.absolutePath}) content : ${e.message}")
75                 }
76             }.await()
77         }
78
79         fun getClassPathFileContent(fileName: String): String {
80             return runBlocking {
81                 withContext(Dispatchers.Default) {
82                     IOUtils.toString(JacksonUtils::class.java.classLoader
83                             .getResourceAsStream(fileName), Charset.defaultCharset())
84                 }
85             }
86         }
87
88         fun <T> readValueFromFile(fileName: String, valueType: Class<T>): T? {
89             val content: String = getContent(fileName)
90             return readValue(content, valueType)
91         }
92
93         fun <T> readValueFromClassPathFile(fileName: String, valueType: Class<T>): T? {
94             val content: String = getClassPathFileContent(fileName)
95             return readValue(content, valueType)
96         }
97
98         fun objectNodeFromObject(from: kotlin.Any): ObjectNode {
99             return jacksonObjectMapper().convertValue(from, ObjectNode::class.java)
100         }
101
102         fun jsonNodeFromObject(from: kotlin.Any): JsonNode {
103             return jacksonObjectMapper().convertValue(from, JsonNode::class.java)
104         }
105
106         fun jsonNodeFromClassPathFile(fileName: String): JsonNode {
107             val content: String = getClassPathFileContent(fileName)
108             return jsonNode(content)
109         }
110
111         fun jsonNodeFromFile(fileName: String): JsonNode {
112             val content: String = getContent(fileName)
113             return jsonNode(content)
114         }
115
116         fun jsonNode(content: String): JsonNode {
117             return jacksonObjectMapper().readTree(content)
118         }
119
120         fun getJson(any: kotlin.Any): String {
121             return getJson(any, false)
122         }
123
124         fun getWrappedJson(wrapper: String, any: kotlin.Any, pretty: Boolean = false): String {
125             val wrapperMap = hashMapOf<String, Any>()
126             wrapperMap[wrapper] = any
127             return getJson(wrapperMap, pretty)
128         }
129
130         fun getJson(any: kotlin.Any, pretty: Boolean = false): String {
131             val objectMapper = jacksonObjectMapper()
132             objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
133             if (pretty) {
134                 objectMapper.enable(SerializationFeature.INDENT_OUTPUT)
135             }
136             return objectMapper.writeValueAsString(any)
137         }
138
139         fun getJsonNode(any: kotlin.Any?, pretty: Boolean = false): JsonNode {
140             val objectMapper = jacksonObjectMapper()
141             objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
142             if (pretty) {
143                 objectMapper.enable(SerializationFeature.INDENT_OUTPUT)
144             }
145             return objectMapper.valueToTree(any)
146         }
147
148         fun <T> getListFromJsonNode(node: JsonNode, valueType: Class<T>): List<T> {
149             return getListFromJson(node.toString(), valueType)
150         }
151
152         fun <T> getListFromJson(content: String, valueType: Class<T>): List<T> {
153             val objectMapper = jacksonObjectMapper()
154             val javaType = objectMapper.typeFactory.constructCollectionType(List::class.java, valueType)
155             return objectMapper.readValue<List<T>>(content, javaType)
156         }
157
158         fun <T> getListFromFile(fileName: String, valueType: Class<T>): List<T> {
159             val content: String = getContent(fileName)
160             return getListFromJson(content, valueType)
161         }
162
163         fun <T> getListFromClassPathFile(fileName: String, valueType: Class<T>): List<T> {
164             val content: String = getClassPathFileContent(fileName)
165             return getListFromJson(content, valueType)
166         }
167
168         fun <T> getMapFromJson(content: String, valueType: Class<T>): MutableMap<String, T> {
169             val objectMapper = jacksonObjectMapper()
170             val mapType = objectMapper.typeFactory.constructMapType(Map::class.java, String::class.java, valueType)
171             return objectMapper.readValue(content, mapType)
172         }
173
174         fun <T> getMapFromFile(file: File, valueType: Class<T>): MutableMap<String, T> {
175             val content: String = getContent(file)
176             return getMapFromJson(content, valueType)
177         }
178
179         fun <T> getMapFromFile(fileName: String, valueType: Class<T>): MutableMap<String, T> = getMapFromFile(File(fileName), valueType)
180
181         fun <T> getInstanceFromMap(properties: MutableMap<String, JsonNode>, classType: Class<T>): T {
182             return readValue(getJson(properties), classType)
183                     ?: throw BluePrintProcessorException("failed to transform content ($properties) to type ($classType)")
184         }
185
186         fun checkJsonNodeValueOfType(type: String, jsonNode: JsonNode): Boolean {
187             if (BluePrintTypes.validPrimitiveTypes().contains(type.toLowerCase())) {
188                 return checkJsonNodeValueOfPrimitiveType(type, jsonNode)
189             } else if (BluePrintTypes.validCollectionTypes().contains(type)) {
190                 return checkJsonNodeValueOfCollectionType(type, jsonNode)
191             }
192             return false
193         }
194
195         fun checkIfPrimitiveType(primitiveType: String): Boolean {
196             return when (primitiveType.toLowerCase()) {
197                 BluePrintConstants.DATA_TYPE_STRING -> true
198                 BluePrintConstants.DATA_TYPE_BOOLEAN -> true
199                 BluePrintConstants.DATA_TYPE_INTEGER -> true
200                 BluePrintConstants.DATA_TYPE_FLOAT -> true
201                 BluePrintConstants.DATA_TYPE_DOUBLE -> true
202                 BluePrintConstants.DATA_TYPE_TIMESTAMP -> true
203                 else -> false
204             }
205         }
206
207         fun checkJsonNodeValueOfPrimitiveType(primitiveType: String, jsonNode: JsonNode): Boolean {
208             return when (primitiveType.toLowerCase()) {
209                 BluePrintConstants.DATA_TYPE_STRING -> jsonNode.isTextual
210                 BluePrintConstants.DATA_TYPE_BOOLEAN -> jsonNode.isBoolean
211                 BluePrintConstants.DATA_TYPE_INTEGER -> jsonNode.isInt
212                 BluePrintConstants.DATA_TYPE_FLOAT -> jsonNode.isDouble
213                 BluePrintConstants.DATA_TYPE_DOUBLE -> jsonNode.isDouble
214                 BluePrintConstants.DATA_TYPE_TIMESTAMP -> jsonNode.isTextual
215                 else -> false
216             }
217         }
218
219         fun checkJsonNodeValueOfCollectionType(type: String, jsonNode: JsonNode): Boolean {
220             return when (type.toLowerCase()) {
221                 BluePrintConstants.DATA_TYPE_LIST -> jsonNode.isArray
222                 BluePrintConstants.DATA_TYPE_MAP -> jsonNode.isContainerNode
223                 else -> false
224             }
225         }
226
227         fun getValue(value: JsonNode): Any {
228             return when (value) {
229                 is BooleanNode -> value.booleanValue()
230                 is IntNode -> value.intValue()
231                 is FloatNode -> value.floatValue()
232                 is DoubleNode -> value.doubleValue()
233                 is TextNode -> value.textValue()
234                 else -> value
235             }
236         }
237
238         fun getValue(value: Any, type: String): Any {
239             return when (type.toLowerCase()) {
240                 BluePrintConstants.DATA_TYPE_BOOLEAN -> (value as BooleanNode).booleanValue()
241                 BluePrintConstants.DATA_TYPE_INTEGER -> (value as IntNode).intValue()
242                 BluePrintConstants.DATA_TYPE_FLOAT -> (value as FloatNode).floatValue()
243                 BluePrintConstants.DATA_TYPE_DOUBLE -> (value as DoubleNode).doubleValue()
244                 BluePrintConstants.DATA_TYPE_STRING -> (value as TextNode).textValue()
245                 else -> (value as JsonNode)
246             }
247         }
248
249         fun populatePrimitiveValues(key: String, value: Any, primitiveType: String, objectNode: ObjectNode) {
250             when (primitiveType.toLowerCase()) {
251                 BluePrintConstants.DATA_TYPE_BOOLEAN -> objectNode.put(key, (value as BooleanNode).booleanValue())
252                 BluePrintConstants.DATA_TYPE_INTEGER -> objectNode.put(key, (value as IntNode).intValue())
253                 BluePrintConstants.DATA_TYPE_FLOAT -> objectNode.put(key, (value as FloatNode).floatValue())
254                 BluePrintConstants.DATA_TYPE_DOUBLE -> objectNode.put(key, (value as DoubleNode).doubleValue())
255                 else -> objectNode.put(key, (value as TextNode).textValue())
256             }
257         }
258
259         fun populatePrimitiveValues(value: Any, primitiveType: String, arrayNode: ArrayNode) {
260             when (primitiveType.toLowerCase()) {
261                 BluePrintConstants.DATA_TYPE_BOOLEAN -> arrayNode.add(value as Boolean)
262                 BluePrintConstants.DATA_TYPE_INTEGER -> arrayNode.add(value as Int)
263                 BluePrintConstants.DATA_TYPE_FLOAT -> arrayNode.add(value as Float)
264                 BluePrintConstants.DATA_TYPE_DOUBLE -> arrayNode.add(value as Double)
265                 BluePrintConstants.DATA_TYPE_TIMESTAMP -> arrayNode.add(value as String)
266                 else -> arrayNode.add(value as String)
267             }
268         }
269
270         fun populatePrimitiveDefaultValues(key: String, primitiveType: String, objectNode: ObjectNode) {
271             when (primitiveType.toLowerCase()) {
272                 BluePrintConstants.DATA_TYPE_BOOLEAN -> objectNode.put(key, false)
273                 BluePrintConstants.DATA_TYPE_INTEGER -> objectNode.put(key, 0)
274                 BluePrintConstants.DATA_TYPE_FLOAT -> objectNode.put(key, 0.0)
275                 BluePrintConstants.DATA_TYPE_DOUBLE -> objectNode.put(key, 0.0)
276                 else -> objectNode.put(key, "")
277             }
278         }
279
280         fun populatePrimitiveDefaultValuesForArrayNode(primitiveType: String, arrayNode: ArrayNode) {
281             when (primitiveType.toLowerCase()) {
282                 BluePrintConstants.DATA_TYPE_BOOLEAN -> arrayNode.add(false)
283                 BluePrintConstants.DATA_TYPE_INTEGER -> arrayNode.add(0)
284                 BluePrintConstants.DATA_TYPE_FLOAT -> arrayNode.add(0.0)
285                 BluePrintConstants.DATA_TYPE_DOUBLE -> arrayNode.add(0.0)
286                 else -> arrayNode.add("")
287             }
288         }
289
290         fun populateJsonNodeValues(key: String, nodeValue: JsonNode?, type: String, objectNode: ObjectNode) {
291             if (nodeValue == null || nodeValue is NullNode) {
292                 objectNode.set(key, nodeValue)
293             } else if (BluePrintTypes.validPrimitiveTypes().contains(type)) {
294                 populatePrimitiveValues(key, nodeValue, type, objectNode)
295             } else {
296                 objectNode.set(key, nodeValue)
297             }
298         }
299
300         fun convertPrimitiveResourceValue(type: String, value: String): JsonNode {
301             return when (type.toLowerCase()) {
302                 BluePrintConstants.DATA_TYPE_BOOLEAN -> jsonNodeFromObject(java.lang.Boolean.valueOf(value))
303                 BluePrintConstants.DATA_TYPE_INTEGER -> jsonNodeFromObject(Integer.valueOf(value))
304                 BluePrintConstants.DATA_TYPE_FLOAT -> jsonNodeFromObject(java.lang.Float.valueOf(value))
305                 BluePrintConstants.DATA_TYPE_DOUBLE -> jsonNodeFromObject(java.lang.Double.valueOf(value))
306                 else -> getJsonNode(value)
307             }
308         }
309
310     }
311 }