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