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;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.JsonIOException;
27 import com.google.gson.JsonParser;
28 import com.google.gson.JsonSyntaxException;
30 import org.apache.commons.collections.CollectionUtils;
31 import org.everit.json.schema.EnumSchema;
32 import org.everit.json.schema.Schema;
33 import org.everit.json.schema.ValidationException;
34 import org.everit.json.schema.loader.SchemaLoader;
35 import org.json.JSONObject;
36 import org.openecomp.core.utilities.CommonMethods;
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 {
55 * Object 2 json string.
60 //TODO: refactor all other ugly code to use this
61 public static String object2Json(Object obj) {
62 return sbObject2Json(obj).toString();
67 * Sb object 2 json string buffer.
70 * @return the string buffer
72 public static StringBuffer sbObject2Json(Object obj) {
73 return new StringBuffer((new GsonBuilder()).setPrettyPrinting().create().toJson(obj));
79 * @param <T> the type parameter
80 * @param json the json
81 * @param classOfT the class of t
84 public static <T> T json2Object(String json, Class<T> classOfT) {
87 try (Reader br = new StringReader(json)) {
88 type = new Gson().fromJson(br, classOfT);
89 } catch (IOException e0) {
92 } catch (JsonIOException | JsonSyntaxException | IOException e0) {
93 throw new RuntimeException(e0);
101 * @param <T> the type parameter
103 * @param classOfT the class of t
106 public static <T> T json2Object(InputStream is, Class<T> classOfT) {
109 try (Reader br = new BufferedReader(new InputStreamReader(is))) {
110 type = new Gson().fromJson(br, classOfT);
112 } catch (JsonIOException | JsonSyntaxException | IOException e0) {
113 throw new RuntimeException(e0);
118 } catch (IOException ignore) {
128 * Is valid json boolean.
130 * @param json the json
131 * @return the boolean
133 //todo check https://github.com/stleary/JSON-java as replacement for this code
134 public static boolean isValidJson(String json) {
136 return new JsonParser().parse(json).isJsonObject();
137 } catch (JsonSyntaxException jse) {
145 * @param json the json
146 * @param jsonSchema the json schema
149 public static List<String> validate(String json, String jsonSchema) {
150 List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
151 return validationErrors == null ? null
152 : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
153 .collect(Collectors.toList());
156 private static String mapValidationExceptionToMessage(ValidationException e0) {
157 if (e0.getViolatedSchema() instanceof EnumSchema) {
158 return mapEnumViolationToMessage(e0);
160 return e0.getMessage();
163 private static String mapEnumViolationToMessage(ValidationException e1) {
164 Set<Object> possibleValues = ((EnumSchema) e1.getViolatedSchema()).getPossibleValues();
165 return e1.getMessage().replaceFirst("enum value", possibleValues.size() == 1
166 ? String.format("value. %s is the only possible value for this field",
167 possibleValues.iterator().next())
168 : String.format("value. Possible values: %s", CommonMethods
169 .collectionToCommaSeparatedString(
170 possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
173 private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
174 if (json == null || jsonSchema == null) {
175 throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
178 Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
180 schemaObj.validate(new JSONObject(json));
181 } catch (ValidationException ve) {
182 return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
183 : ve.getCausingExceptions();