f59864ac0da842607f20a821f1a370d9eaba7d8e
[clamp.git] / src / main / java / org / onap / clamp / clds / util / JsonUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2018 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  *
22  */
23
24 package org.onap.clamp.clds.util;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.google.common.collect.Lists;
29 import com.google.gson.Gson;
30 import com.google.gson.GsonBuilder;
31 import com.google.gson.JsonElement;
32 import com.google.gson.JsonObject;
33 import com.google.gson.JsonPrimitive;
34
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.Optional;
38 import java.util.Spliterator;
39 import java.util.Spliterators;
40 import java.util.stream.Collectors;
41 import java.util.stream.StreamSupport;
42
43 import org.onap.clamp.clds.model.properties.AbstractModelElement;
44 import org.onap.clamp.clds.service.SecureServicePermission;
45 import org.onap.clamp.clds.service.SecureServicePermissionDeserializer;
46
47 /**
48  * This class is used to access the GSON with restricted type access.
49  */
50 public class JsonUtils {
51
52     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractModelElement.class);
53     private static final String LOG_ELEMENT_NOT_FOUND = "Value '{}' for key 'name' not found in JSON";
54     private static final String LOG_ELEMENT_NOT_FOUND_IN_JSON = "Value '{}' for key 'name' not found in JSON {}";
55
56     public static final Gson GSON = new GsonBuilder()
57         .registerTypeAdapter(SecureServicePermission.class, new SecureServicePermissionDeserializer()).create();
58
59     private JsonUtils() {
60     }
61
62     /**
63      * Return the value field of the json node element that has a name field equals
64      * to the given name.
65      */
66     public static String getStringValueByName(JsonElement jsonElement, String name) {
67         String value = extractJsonValueFromElement(jsonElement, name).map(JsonUtils::extractStringValueFromElement)
68             .orElse(null);
69         if (value == null) {
70             if (logger.isDebugEnabled()) {
71                 logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, jsonElement.toString());
72             } else {
73                 logger.warn(LOG_ELEMENT_NOT_FOUND, name);
74             }
75         }
76         return value;
77     }
78
79     /**
80      * Return an array of values for the field of the json node element that has a
81      * name field equals to the given name.
82      */
83     public static List<String> getStringValuesByName(JsonElement jsonElement, String name) {
84         List<String> values = extractJsonValueFromElement(jsonElement, name)
85             .map(JsonUtils::extractStringValuesFromElement).orElse(new ArrayList<>());
86         if (values.isEmpty()) {
87             if (logger.isDebugEnabled()) {
88                 logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, jsonElement.toString());
89             } else {
90                 logger.warn(LOG_ELEMENT_NOT_FOUND, name);
91             }
92         }
93         return values;
94     }
95
96     /**
97      * Return the int value field of the json node element that has a name field
98      * equals to the given name.
99      */
100     public static Integer getIntValueByName(JsonElement element, String name) {
101         String value = getStringValueByName(element, name);
102         return Integer.valueOf(value);
103     }
104
105     /**
106      * Return the Json value field of the json node element that has a name field
107      * equals to the given name.
108      */
109     public static JsonObject getJsonObjectByName(JsonElement jsonElement, String name) {
110         JsonObject jsonObject = extractJsonValueFromElement(jsonElement, name).map(JsonElement::getAsJsonObject)
111             .orElse(null);
112         if (jsonObject == null) {
113             logger.warn(LOG_ELEMENT_NOT_FOUND, name);
114         } else {
115             logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, jsonElement.toString());
116         }
117         return jsonObject;
118     }
119
120     private static Optional<JsonElement> extractJsonValueFromElement(JsonElement jsonElement, String name) {
121         if (jsonElement != null) {
122             if (jsonElement.isJsonArray()) {
123                 return extractValueJsonFromArray(jsonElement, name);
124             } else if (hasMatchingParameterName(name, jsonElement)) {
125                 return Optional.of(jsonElement);
126             }
127         }
128         return Optional.empty();
129     }
130
131     private static Optional<JsonElement> extractValueJsonFromArray(JsonElement jsonElement, String name) {
132         for (JsonElement element : jsonElement.getAsJsonArray()) {
133             if (hasMatchingParameterName(name, element)) {
134                 return Optional.of(element.getAsJsonObject().get("value"));
135             }
136         }
137         return Optional.empty();
138     }
139
140     private static boolean hasMatchingParameterName(String name, JsonElement element) {
141         return element.isJsonObject() && element.getAsJsonObject().has("name")
142             && name.equals(element.getAsJsonObject().get("name").getAsString());
143     }
144
145     private static String extractStringValueFromElement(JsonElement element) {
146         if (element.isJsonArray()) {
147             return element.getAsJsonArray().get(0).getAsString();
148         } else if (element.isJsonPrimitive()) {
149             return element.getAsJsonPrimitive().getAsString();
150         } else {
151             return GSON.toJson(element);
152         }
153     }
154
155     private static List<String> extractStringValuesFromElement(JsonElement element) {
156         if (element.isJsonArray()) {
157             return StreamSupport
158                 .stream(Spliterators.spliteratorUnknownSize(element.getAsJsonArray().iterator(), Spliterator.ORDERED),
159                     false)
160                 .filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsJsonPrimitive)
161                 .filter(JsonPrimitive::isString).map(JsonPrimitive::getAsString).collect(Collectors.toList());
162         } else {
163             String value = extractStringValueFromElement(element);
164             return Lists.newArrayList(value);
165         }
166
167     }
168 }