Migrate "ms/controllerblueprints" from ccsdk/apps
[ccsdk/cds.git] / ms / controllerblueprints / modules / blueprint-core / src / main / kotlin / org / onap / ccsdk / cds / controllerblueprints / core / utils / JsonParserUtils.kt
1 /*
2  *  Copyright © 2018 IBM.
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  */
16
17 package org.onap.ccsdk.cds.controllerblueprints.core.utils
18
19
20 import com.fasterxml.jackson.databind.JsonNode
21 import com.jayway.jsonpath.Configuration
22 import com.jayway.jsonpath.JsonPath
23 import com.jayway.jsonpath.Option
24 import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider
25 import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider
26
27 class JsonParserUtils {
28     companion object {
29
30         //TODO("Optimise this")
31         val JACKSON_JSON_NODE_CONFIGURATION = Configuration.builder()
32                 .mappingProvider(JacksonMappingProvider()).jsonProvider(JacksonJsonNodeJsonProvider()).build()
33
34         val PATH_CONFIGURATION = Configuration.builder().options(Option.AS_PATH_LIST).build()
35
36         fun paths(jsonContent: String, expression: String): List<String> {
37             return JsonPath.using(PATH_CONFIGURATION).parse(jsonContent).read(expression)
38         }
39
40         fun paths(jsonNode: JsonNode, expression: String): List<String> {
41             return paths(jsonNode.toString(), expression)
42         }
43
44         fun parse(jsonContent: String, expression: String): JsonNode {
45             return JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION).parse(jsonContent).read(expression)
46         }
47
48         fun parse(jsonNode: JsonNode, expression: String): JsonNode {
49             return parse(jsonNode.toString(), expression)
50         }
51
52         fun parseNSet(jsonContent: String, expression: String, value: JsonNode): JsonNode {
53             return JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION).parse(jsonContent).set(expression, value).json()
54         }
55
56         fun parseNSet(jsonNode: JsonNode, expression: String, valueNode: JsonNode): JsonNode {
57             return parseNSet(jsonNode.toString(), expression, valueNode)
58         }
59     }
60 }