cc875d6d9cafb3fe4aa53045d208bc0354aeffe5
[clamp.git] / src / main / java / org / onap / clamp / clds / util / JsonUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2018-2019 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.time.Instant;
36 import java.util.ArrayList;
37 import java.util.List;
38 import java.util.Optional;
39 import java.util.Spliterator;
40 import java.util.Spliterators;
41 import java.util.stream.Collectors;
42 import java.util.stream.StreamSupport;
43
44 import org.onap.clamp.clds.service.SecureServicePermission;
45 import org.onap.clamp.clds.service.SecureServicePermissionDeserializer;
46 import org.onap.clamp.dao.model.gson.converter.InstantDeserializer;
47 import org.onap.clamp.dao.model.gson.converter.InstantSerializer;
48
49 /**
50  * This class is used to access the GSON with restricted type access.
51  */
52 public class JsonUtils {
53
54     protected static final EELFLogger logger = EELFManager.getInstance().getLogger(JsonUtils.class);
55     private static final String LOG_ELEMENT_NOT_FOUND = "Value '{}' for key 'name' not found in JSON";
56     private static final String LOG_ELEMENT_NOT_FOUND_IN_JSON = "Value '{}' for key 'name' not found in JSON {}";
57
58     public static final Gson GSON = new GsonBuilder()
59             .registerTypeAdapter(SecureServicePermission.class, new SecureServicePermissionDeserializer()).create();
60
61     public static final Gson GSON_JPA_MODEL = new GsonBuilder()
62             .registerTypeAdapter(Instant.class, new InstantSerializer())
63             .registerTypeAdapter(Instant.class, new InstantDeserializer()).setPrettyPrinting()
64             .excludeFieldsWithoutExposeAnnotation().create();
65
66     private JsonUtils() {
67     }
68
69     /**
70      * typeAdapter Return the value field of the json node element that has a name
71      * field equals to the given name.
72      */
73     public static String getStringValueByName(JsonElement jsonElement, String name) {
74         String value = extractJsonValueFromElement(jsonElement, name).map(JsonUtils::extractStringValueFromElement)
75                 .orElse(null);
76         if (value == null) {
77             if (logger.isDebugEnabled()) {
78                 logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, jsonElement.toString());
79             } else {
80                 logger.warn(LOG_ELEMENT_NOT_FOUND, name);
81             }
82         }
83         return value;
84     }
85
86     /**
87      * Return an array of values for the field of the json node element that has a
88      * name field equals to the given name.
89      */
90     public static List<String> getStringValuesByName(JsonElement jsonElement, String name) {
91         List<String> values = extractJsonValueFromElement(jsonElement, name)
92                 .map(JsonUtils::extractStringValuesFromElement).orElse(new ArrayList<>());
93         if (values.isEmpty()) {
94             if (logger.isDebugEnabled()) {
95                 logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, jsonElement.toString());
96             } else {
97                 logger.warn(LOG_ELEMENT_NOT_FOUND, name);
98             }
99         }
100         return values;
101     }
102
103     /**
104      * Return the int value field of the json node element that has a name field
105      * equals to the given name.
106      */
107     public static Integer getIntValueByName(JsonElement element, String name) {
108         String value = getStringValueByName(element, name);
109         return Integer.valueOf(value);
110     }
111
112     /**
113      * Return the Json value field of the json node element that has a name field
114      * equals to the given name.
115      */
116     public static JsonObject getJsonObjectByName(JsonElement jsonElement, String name) {
117         JsonObject jsonObject = extractJsonValueFromElement(jsonElement, name).map(JsonElement::getAsJsonObject)
118                 .orElse(null);
119         if (jsonObject == null) {
120             logger.warn(LOG_ELEMENT_NOT_FOUND, name);
121         } else {
122             logger.debug(LOG_ELEMENT_NOT_FOUND_IN_JSON, name, jsonElement.toString());
123         }
124         return jsonObject;
125     }
126
127     private static Optional<JsonElement> extractJsonValueFromElement(JsonElement jsonElement, String name) {
128         if (jsonElement != null) {
129             if (jsonElement.isJsonArray()) {
130                 return extractValueJsonFromArray(jsonElement, name);
131             } else if (hasMatchingParameterName(name, jsonElement)) {
132                 return Optional.of(jsonElement);
133             }
134         }
135         return Optional.empty();
136     }
137
138     private static Optional<JsonElement> extractValueJsonFromArray(JsonElement jsonElement, String name) {
139         for (JsonElement element : jsonElement.getAsJsonArray()) {
140             if (hasMatchingParameterName(name, element)) {
141                 return Optional.of(element.getAsJsonObject().get("value"));
142             }
143         }
144         return Optional.empty();
145     }
146
147     private static boolean hasMatchingParameterName(String name, JsonElement element) {
148         return element.isJsonObject() && element.getAsJsonObject().has("name")
149                 && name.equals(element.getAsJsonObject().get("name").getAsString());
150     }
151
152     private static String extractStringValueFromElement(JsonElement element) {
153         if (element.isJsonArray()) {
154             return element.getAsJsonArray().get(0).getAsString();
155         } else if (element.isJsonPrimitive()) {
156             return element.getAsJsonPrimitive().getAsString();
157         } else {
158             return GSON.toJson(element);
159         }
160     }
161
162     private static List<String> extractStringValuesFromElement(JsonElement element) {
163         if (element.isJsonArray()) {
164             return StreamSupport
165                     .stream(Spliterators.spliteratorUnknownSize(element.getAsJsonArray().iterator(),
166                             Spliterator.ORDERED), false)
167                     .filter(JsonElement::isJsonPrimitive).map(JsonElement::getAsJsonPrimitive)
168                     .filter(JsonPrimitive::isString).map(JsonPrimitive::getAsString).collect(Collectors.toList());
169         } else {
170             String value = extractStringValueFromElement(element);
171             return Lists.newArrayList(value);
172         }
173
174     }
175 }