aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/pomba/contextbuilder/aai/reader/JsonReader.java
blob: 586670529b3410705776b423de095cad1542f427 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/*
 * ============LICENSE_START===================================================
 * Copyright (c) 2018 Amdocs
 * ============================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=====================================================
 */
package org.onap.pomba.contextbuilder.aai.reader;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.ReadContext;
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
import com.jayway.jsonpath.spi.json.JsonProvider;
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
import com.jayway.jsonpath.spi.mapper.MappingProvider;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.onap.pomba.contextbuilder.aai.exception.AuditError;
import org.onap.pomba.contextbuilder.aai.exception.AuditException;

/**
 * Reads JSON objects. Supported by the JayWay JsonPath library.
 */
public class JsonReader {

    private Configuration jsonPathConfig;

    /**
     * Initialize the JSON reader.
     */
    public JsonReader() {
        setJsonProvider();
        this.jsonPathConfig = Configuration.builder().options(Option.SUPPRESS_EXCEPTIONS).build();
    }

    /**
     * Parse the JSON.
     *
     * @param json
     *            the JSON object
     * @return a {@link ReadContext} the parsed JSON.
     * @throws ValidationServiceException
     */
    public DocumentContext parse(String json) throws AuditException {
        DocumentContext document = null;
        try {
            document = JsonPath.using(jsonPathConfig).parse(json);
        } catch (Exception e) {
            throw new AuditException(AuditError.JSON_READER_PARSE_ERROR, e);
        }
        return document;
    }

    /**
     * Gets values from JSON objects.
     *
     * @param json
     *            the JSON object
     * @param path
     *            the path to property values. The format must comply with the JayWay JsonPath definition.
     * @return a List of values found by evaluating the path.
     * @throws ValidationServiceException
     */
    public List<String> get(String json, String path) throws AuditException {
        return getAsList(parse(json), path);
    }

    /**
     * Gets values from JSON objects. Used in combination with {@link JsonReader#parse(String)} it reduces the number of
     * times the JSON document is parsed.
     *
     * @param document
     *            a {@link DocumentContext} object with the parsed JSON
     * @param path
     *            the path to property values. The format must comply with the JayWay JsonPath definition.
     * @return a List of values found by evaluating the path, or an empty list if no values were found
     */
    public List<String> getAsList(DocumentContext document, String path) {
        List<String> result = new ArrayList<>();
        JsonElement jsonElement = document.read(path);
        if (jsonElement != null) {
            if (jsonElement.isJsonPrimitive()) {
                result.add(jsonElement.getAsString());
            } else if (jsonElement.isJsonObject()) {
                result.add(jsonElement.getAsJsonObject().toString());
            } else if (jsonElement.isJsonArray()) {
                for (JsonElement obj : jsonElement.getAsJsonArray()) {
                    Object object = jsonElementToObject(obj);
                    result.add(object == null ? null : object.toString());
                }
            }
        }
        return result;
    }

    /**
     * Get the value(s) from the specified JSON document
     *
     * @param document
     *            a {@link DocumentContext} object with the parsed JSON
     * @param path
     *            the path to property value(s). The format must comply with the JayWay JsonPath definition.
     * @return either all the values found by evaluating the path (e.g. as an array), or a String object (only) where
     *         the path evaluates to a single primitive value
     */
    public Object getObject(DocumentContext document, String path) {
        return jsonElementToObject(document.read(path));
    }

    /**
     * Convert the JSON element to a String or Array where possible, otherwise return the JSON object.
     *
     * @param jsonElement
     * @return the jsonElement converted to a Java Object
     */
    private Object jsonElementToObject(JsonElement jsonElement) {
        if (jsonElement == null) {
            return null;
        } else if (jsonElement.isJsonPrimitive()) {
            return jsonElement.getAsString();
        } else if (jsonElement.isJsonObject()) {
            return jsonElement.getAsJsonObject();
        } else if (jsonElement.isJsonArray()) {
            // Convert to a List for simplified handling within rules
            return jsonArrayToList(jsonElement.getAsJsonArray());
        } else {
            return jsonElement;
        }
    }

    private List<Object> jsonArrayToList(JsonArray jsonArray) {
        List<Object> result = new ArrayList<>();
        for (JsonElement obj : jsonArray) {
            result.add(jsonElementToObject(obj));
        }
        return result;
    }

    /**
     * @param document
     * @param path
     * @return a JsonElement from the document
     */
    public JsonElement getJsonElement(DocumentContext document, String path) {
        return document.read(path);
    }

    private void setJsonProvider() {
        Configuration.setDefaults(new Configuration.Defaults() {
            private final JsonProvider jsonProvider = new GsonJsonProvider();
            private final MappingProvider mappingProvider = new GsonMappingProvider();

            @Override
            public JsonProvider jsonProvider() {
                return jsonProvider;
            }

            @Override
            public MappingProvider mappingProvider() {
                return mappingProvider;
            }

            @Override
            public Set<Option> options() {
                return EnumSet.noneOf(Option.class);
            }
        });
    }
}