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) {
129 * Is valid json boolean.
131 * @param json the json
132 * @return the boolean
134 //todo check https://github.com/stleary/JSON-java as replacement for this code
135 public static boolean isValidJson(String json) {
137 return new JsonParser().parse(json).isJsonObject();
138 } catch (JsonSyntaxException jse) {
146 * @param json the json
147 * @param jsonSchema the json schema
150 public static List<String> validate(String json, String jsonSchema) {
151 List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
152 return validationErrors == null ? null
153 : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
154 .collect(Collectors.toList());
157 private static String mapValidationExceptionToMessage(ValidationException exception) {
158 if (exception.getViolatedSchema() instanceof EnumSchema) {
159 return mapEnumViolationToMessage(exception);
161 return exception.getMessage();
164 private static String mapEnumViolationToMessage(ValidationException exception) {
165 Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
166 return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
167 ? String.format("value. %s is the only possible value for this field",
168 possibleValues.iterator().next())
169 : String.format("value. Possible values: %s", CommonMethods
170 .collectionToCommaSeparatedString(
171 possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
174 private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
176 String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
177 if (json == null || jsonSchema == null) {
178 throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
181 Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
183 schemaObj.validate(new JSONObject(json));
184 } catch (ValidationException ve) {
185 return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
186 : ve.getCausingExceptions();