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