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