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