2 * Copyright © 2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openecomp.core.utilities.json;
19 import com.google.gson.Gson;
20 import com.google.gson.GsonBuilder;
21 import com.google.gson.JsonIOException;
22 import com.google.gson.JsonParser;
23 import com.google.gson.JsonSyntaxException;
25 import java.io.BufferedReader;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.Reader;
30 import java.io.StringReader;
31 import java.util.Collections;
32 import java.util.List;
34 import java.util.stream.Collectors;
36 import org.apache.commons.collections4.CollectionUtils;
37 import org.everit.json.schema.EnumSchema;
38 import org.everit.json.schema.Schema;
39 import org.everit.json.schema.ValidationException;
40 import org.everit.json.schema.loader.SchemaLoader;
41 import org.json.JSONObject;
42 import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
43 import org.openecomp.core.utilities.CommonMethods;
44 import org.openecomp.core.utilities.deserializers.RequirementDefinitionDeserializer;
46 import org.openecomp.sdc.logging.api.Logger;
47 import org.openecomp.sdc.logging.api.LoggerFactory;
53 public class JsonUtil {
54 private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
55 private static final GsonBuilder gsonBuilder;
56 private static final Gson gson;
59 gsonBuilder = new GsonBuilder();
60 gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new
61 RequirementDefinitionDeserializer());
62 gson = gsonBuilder.create();
69 * Object 2 json string.
74 public static String object2Json(Object obj) {
75 return sbObject2Json(obj).toString();
80 * Sb object 2 json string builder.
83 * @return the string builder
85 public static StringBuilder sbObject2Json(Object obj) {
86 return new StringBuilder(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
92 * @param <T> the type parameter
93 * @param json the json
94 * @param classOfT the class of t
97 public static <T> T json2Object(String json, Class<T> classOfT) {
100 try (Reader br = new StringReader(json)) {
101 typ = gson.fromJson(br, classOfT);
103 } catch (JsonIOException | JsonSyntaxException | IOException exception) {
104 throw new RuntimeException(exception);
112 * @param <T> the type parameter
114 * @param classOfT the class of t
117 public static <T> T json2Object(InputStream is, Class<T> classOfT) {
119 try (Reader br = new BufferedReader(new InputStreamReader(is))) {
120 type = new Gson().fromJson(br, classOfT);
122 catch (JsonIOException | JsonSyntaxException | IOException exception) {
123 throw new RuntimeException(exception);
130 * Is valid json boolean.
132 * @param json the json
133 * @return the boolean
135 //todo check https://github.com/stleary/JSON-java as replacement for this code
136 public static boolean isValidJson(String json) {
138 return new JsonParser().parse(json).isJsonObject();
139 } catch (JsonSyntaxException jse) {
140 LOGGER.error("Invalid json, Failed to parse json", jse);
148 * @param json the json
149 * @param jsonSchema the json schema
152 public static List<String> validate(String json, String jsonSchema) {
153 List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
154 return validationErrors == null ? null
155 : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
156 .collect(Collectors.toList());
159 private static String mapValidationExceptionToMessage(ValidationException exception) {
160 if (exception.getViolatedSchema() instanceof EnumSchema) {
161 return mapEnumViolationToMessage(exception);
163 return exception.getMessage();
166 private static String mapEnumViolationToMessage(ValidationException exception) {
167 Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
168 return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
169 ? String.format("value. %s is the only possible value for this field",
170 possibleValues.iterator().next())
171 : String.format("value. Possible values: %s", CommonMethods
172 .collectionToCommaSeparatedString(
173 possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
176 private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
178 String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
179 if (json == null || jsonSchema == null) {
180 throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
183 Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
185 schemaObj.validate(new JSONObject(json));
186 } catch (ValidationException ve) {
187 return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
188 : ve.getCausingExceptions();