2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.core.utilities.json;
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.JsonIOException;
26 import com.google.gson.JsonParser;
27 import com.google.gson.JsonSyntaxException;
28 import org.apache.commons.collections4.CollectionUtils;
29 import org.everit.json.schema.EnumSchema;
30 import org.everit.json.schema.Schema;
31 import org.everit.json.schema.ValidationException;
32 import org.everit.json.schema.loader.SchemaLoader;
33 import org.json.JSONObject;
34 import org.openecomp.core.utilities.CommonMethods;
35 import org.openecomp.sdc.logging.api.Logger;
36 import org.openecomp.sdc.logging.api.LoggerFactory;
38 import java.io.BufferedReader;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.io.InputStreamReader;
42 import java.io.Reader;
43 import java.io.StringReader;
44 import java.util.Collections;
45 import java.util.List;
47 import java.util.stream.Collectors;
52 public class JsonUtil {
53 private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
56 * Object 2 json string.
61 //TODO: refactor all other ugly code to use this
62 public static String object2Json(Object obj) {
63 return sbObject2Json(obj).toString();
68 * Sb object 2 json string buffer.
71 * @return the string buffer
73 public static StringBuffer sbObject2Json(Object obj) {
74 return new StringBuffer((new GsonBuilder()).setPrettyPrinting().create().toJson(obj));
80 * @param <T> the type parameter
81 * @param json the json
82 * @param classOfT the class of t
85 public static <T> T json2Object(String json, Class<T> classOfT) {
88 try (Reader br = new StringReader(json)) {
89 typ = new Gson().fromJson(br, classOfT);
90 } catch (IOException exception) {
93 } catch (JsonIOException | JsonSyntaxException | IOException exception) {
94 throw new RuntimeException(exception);
102 * @param <T> the type parameter
104 * @param classOfT the class of t
107 public static <T> T json2Object(InputStream is, Class<T> classOfT) {
110 try (Reader br = new BufferedReader(new InputStreamReader(is))) {
111 type = new Gson().fromJson(br, classOfT);
113 } catch (JsonIOException | JsonSyntaxException | IOException exception) {
114 throw new RuntimeException(exception);
119 } catch (IOException ignore) {
120 logger.debug("",ignore);
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.debug("",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();