Improve Rest Service API
[ccsdk/cds.git] / ms / controllerblueprints / modules / blueprint-core / src / main / kotlin / org / onap / ccsdk / cds / controllerblueprints / core / utils / JacksonUtils.kt
1 /*
2  * Copyright © 2017-2018 AT&T Intellectual Property.
3  * Modifications Copyright © 2018-2019 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.io.InputStream
31 import java.nio.charset.Charset
32
33 /**
34  *
35  *
36  * @author Brinda Santh
37  */
38 class JacksonUtils {
39     companion object {
40
41         val objectMapper = jacksonObjectMapper()
42
43         inline fun <reified T : Any> readValue(content: String): T =
44                 objectMapper.readValue(content, T::class.java)
45
46         inline fun <reified T : Any> readValue(stream: InputStream): T =
47                 objectMapper.readValue(stream, T::class.java)
48
49         fun <T> readValue(content: String, valueType: Class<T>): T? {
50             return objectMapper.readValue(content, valueType)
51         }
52
53         fun <T> readValue(stream: InputStream, valueType: Class<T>): T? {
54             return objectMapper.readValue(stream, valueType)
55         }
56
57         fun <T> readValue(node: JsonNode, valueType: Class<T>): T? {
58             return objectMapper.treeToValue(node, valueType)
59         }
60
61         fun removeJsonNullNode(node: JsonNode) {
62             val it = node.iterator()
63             while (it.hasNext()) {
64                 val child = it.next()
65                 if (child.isNull) {
66                     it.remove()
67                 } else {
68                     removeJsonNullNode(child)
69                 }
70             }
71         }
72
73
74         fun getContent(fileName: String): String = runBlocking {
75             try {
76                 normalizedFile(fileName).readNBText()
77             } catch (e: Exception) {
78                 throw BluePrintException("couldn't get file ($fileName) content : ${e.message}")
79             }
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 objectMapper.convertValue(from, ObjectNode::class.java)
103         }
104
105         fun jsonNodeFromObject(from: kotlin.Any): JsonNode {
106             return objectMapper.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(file: File, valueType: Class<T>): MutableMap<String, T> = runBlocking {
178             val content: String = file.readNBText()
179             getMapFromJson(content, valueType)
180         }
181
182         fun <T> getMapFromFile(fileName: String, valueType: Class<T>): MutableMap<String, T> = getMapFromFile(File(fileName), valueType)
183
184         fun <T> getInstanceFromMap(properties: MutableMap<String, JsonNode>, classType: Class<T>): T {
185             return readValue(getJson(properties), classType)
186                     ?: throw BluePrintProcessorException("failed to transform content ($properties) to type ($classType)")
187         }
188
189         fun checkJsonNodeValueOfType(type: String, jsonNode: JsonNode): Boolean {
190             if (BluePrintTypes.validPrimitiveTypes().contains(type.toLowerCase())) {
191                 return checkJsonNodeValueOfPrimitiveType(type, jsonNode)
192             } else if (BluePrintTypes.validCollectionTypes().contains(type)) {
193                 return checkJsonNodeValueOfCollectionType(type, jsonNode)
194             }
195             return false
196         }
197
198         fun checkIfPrimitiveType(primitiveType: String): Boolean {
199             return when (primitiveType.toLowerCase()) {
200                 BluePrintConstants.DATA_TYPE_STRING -> true
201                 BluePrintConstants.DATA_TYPE_BOOLEAN -> true
202                 BluePrintConstants.DATA_TYPE_INTEGER -> true
203                 BluePrintConstants.DATA_TYPE_FLOAT -> true
204                 BluePrintConstants.DATA_TYPE_DOUBLE -> true
205                 BluePrintConstants.DATA_TYPE_TIMESTAMP -> true
206                 else -> false
207             }
208         }
209
210         fun checkJsonNodeValueOfPrimitiveType(primitiveType: String, jsonNode: JsonNode): Boolean {
211             return when (primitiveType.toLowerCase()) {
212                 BluePrintConstants.DATA_TYPE_STRING -> jsonNode.isTextual
213                 BluePrintConstants.DATA_TYPE_BOOLEAN -> jsonNode.isBoolean
214                 BluePrintConstants.DATA_TYPE_INTEGER -> jsonNode.isInt
215                 BluePrintConstants.DATA_TYPE_FLOAT -> jsonNode.isDouble
216                 BluePrintConstants.DATA_TYPE_DOUBLE -> jsonNode.isDouble
217                 BluePrintConstants.DATA_TYPE_TIMESTAMP -> jsonNode.isTextual
218                 else -> false
219             }
220         }
221
222         fun checkJsonNodeValueOfCollectionType(type: String, jsonNode: JsonNode): Boolean {
223             return when (type.toLowerCase()) {
224                 BluePrintConstants.DATA_TYPE_LIST -> jsonNode.isArray
225                 BluePrintConstants.DATA_TYPE_MAP -> jsonNode.isContainerNode
226                 else -> false
227             }
228         }
229
230         fun getValue(value: JsonNode): Any {
231             return when (value) {
232                 is BooleanNode -> value.booleanValue()
233                 is IntNode -> value.intValue()
234                 is FloatNode -> value.floatValue()
235                 is DoubleNode -> value.doubleValue()
236                 is TextNode -> value.textValue()
237                 else -> value
238             }
239         }
240
241         fun getValue(value: Any, type: String): Any {
242             return when (type.toLowerCase()) {
243                 BluePrintConstants.DATA_TYPE_BOOLEAN -> (value as BooleanNode).booleanValue()
244                 BluePrintConstants.DATA_TYPE_INTEGER -> (value as IntNode).intValue()
245                 BluePrintConstants.DATA_TYPE_FLOAT -> (value as FloatNode).floatValue()
246                 BluePrintConstants.DATA_TYPE_DOUBLE -> (value as DoubleNode).doubleValue()
247                 BluePrintConstants.DATA_TYPE_STRING -> (value as TextNode).textValue()
248                 else -> (value as JsonNode)
249             }
250         }
251
252         fun populatePrimitiveValues(key: String, value: Any, primitiveType: String, objectNode: ObjectNode) {
253             when (primitiveType.toLowerCase()) {
254                 BluePrintConstants.DATA_TYPE_BOOLEAN -> objectNode.put(key, (value as BooleanNode).booleanValue())
255                 BluePrintConstants.DATA_TYPE_INTEGER -> objectNode.put(key, (value as IntNode).intValue())
256                 BluePrintConstants.DATA_TYPE_FLOAT -> objectNode.put(key, (value as FloatNode).floatValue())
257                 BluePrintConstants.DATA_TYPE_DOUBLE -> objectNode.put(key, (value as DoubleNode).doubleValue())
258                 else -> objectNode.put(key, (value as TextNode).textValue())
259             }
260         }
261
262         fun populatePrimitiveValues(value: Any, primitiveType: String, arrayNode: ArrayNode) {
263             when (primitiveType.toLowerCase()) {
264                 BluePrintConstants.DATA_TYPE_BOOLEAN -> arrayNode.add(value as Boolean)
265                 BluePrintConstants.DATA_TYPE_INTEGER -> arrayNode.add(value as Int)
266                 BluePrintConstants.DATA_TYPE_FLOAT -> arrayNode.add(value as Float)
267                 BluePrintConstants.DATA_TYPE_DOUBLE -> arrayNode.add(value as Double)
268                 BluePrintConstants.DATA_TYPE_TIMESTAMP -> arrayNode.add(value as String)
269                 else -> arrayNode.add(value as String)
270             }
271         }
272
273         fun populatePrimitiveDefaultValues(key: String, primitiveType: String, objectNode: ObjectNode) {
274             when (primitiveType.toLowerCase()) {
275                 BluePrintConstants.DATA_TYPE_BOOLEAN -> objectNode.put(key, false)
276                 BluePrintConstants.DATA_TYPE_INTEGER -> objectNode.put(key, 0)
277                 BluePrintConstants.DATA_TYPE_FLOAT -> objectNode.put(key, 0.0)
278                 BluePrintConstants.DATA_TYPE_DOUBLE -> objectNode.put(key, 0.0)
279                 else -> objectNode.put(key, "")
280             }
281         }
282
283         fun populatePrimitiveDefaultValuesForArrayNode(primitiveType: String, arrayNode: ArrayNode) {
284             when (primitiveType.toLowerCase()) {
285                 BluePrintConstants.DATA_TYPE_BOOLEAN -> arrayNode.add(false)
286                 BluePrintConstants.DATA_TYPE_INTEGER -> arrayNode.add(0)
287                 BluePrintConstants.DATA_TYPE_FLOAT -> arrayNode.add(0.0)
288                 BluePrintConstants.DATA_TYPE_DOUBLE -> arrayNode.add(0.0)
289                 else -> arrayNode.add("")
290             }
291         }
292
293         fun populateJsonNodeValues(key: String, nodeValue: JsonNode?, type: String, objectNode: ObjectNode) {
294             if (nodeValue == null || nodeValue is NullNode) {
295                 objectNode.set(key, nodeValue)
296             } else if (BluePrintTypes.validPrimitiveTypes().contains(type)) {
297                 populatePrimitiveValues(key, nodeValue, type, objectNode)
298             } else {
299                 objectNode.set(key, nodeValue)
300             }
301         }
302
303         fun convertPrimitiveResourceValue(type: String, value: String): JsonNode {
304             return when (type.toLowerCase()) {
305                 BluePrintConstants.DATA_TYPE_BOOLEAN -> jsonNodeFromObject(java.lang.Boolean.valueOf(value))
306                 BluePrintConstants.DATA_TYPE_INTEGER -> jsonNodeFromObject(Integer.valueOf(value))
307                 BluePrintConstants.DATA_TYPE_FLOAT -> jsonNodeFromObject(java.lang.Float.valueOf(value))
308                 BluePrintConstants.DATA_TYPE_DOUBLE -> jsonNodeFromObject(java.lang.Double.valueOf(value))
309                 else -> getJsonNode(value)
310             }
311         }
312
313     }
314 }