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;
29 import org.apache.commons.collections4.CollectionUtils;
30 import org.everit.json.schema.EnumSchema;
31 import org.everit.json.schema.Schema;
32 import org.everit.json.schema.ValidationException;
33 import org.everit.json.schema.loader.SchemaLoader;
34 import org.json.JSONObject;
35 import org.openecomp.core.utilities.CommonMethods;
37 import java.io.BufferedReader;
38 import java.io.IOException;
39 import java.io.InputStream;
40 import java.io.InputStreamReader;
41 import java.io.Reader;
42 import java.io.StringReader;
43 import java.util.Collections;
44 import java.util.List;
46 import java.util.stream.Collectors;
51 public class JsonUtil {
54 * Object 2 json string.
59 //TODO: refactor all other ugly code to use this
60 public static String object2Json(Object obj) {
61 return sbObject2Json(obj).toString();
66 * Sb object 2 json string buffer.
69 * @return the string buffer
71 public static StringBuffer sbObject2Json(Object obj) {
72 return new StringBuffer((new GsonBuilder()).setPrettyPrinting().create().toJson(obj));
78 * @param <T> the type parameter
79 * @param json the json
80 * @param classOfT the class of t
83 public static <T> T json2Object(String json, Class<T> classOfT) {
86 try (Reader br = new StringReader(json)) {
87 typ = new Gson().fromJson(br, classOfT);
88 } catch (IOException exception) {
91 } catch (JsonIOException | JsonSyntaxException | IOException exception) {
92 throw new RuntimeException(exception);
100 * @param <T> the type parameter
102 * @param classOfT the class of t
105 public static <T> T json2Object(InputStream is, Class<T> classOfT) {
108 try (Reader br = new BufferedReader(new InputStreamReader(is))) {
109 type = new Gson().fromJson(br, classOfT);
111 } catch (JsonIOException | JsonSyntaxException | IOException exception) {
112 throw new RuntimeException(exception);
117 } catch (IOException ignore) {
127 * Is valid json boolean.
129 * @param json the json
130 * @return the boolean
132 //todo check https://github.com/stleary/JSON-java as replacement for this code
133 public static boolean isValidJson(String json) {
135 return new JsonParser().parse(json).isJsonObject();
136 } catch (JsonSyntaxException jse) {
144 * @param json the json
145 * @param jsonSchema the json schema
148 public static List<String> validate(String json, String jsonSchema) {
149 List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
150 return validationErrors == null ? null
151 : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
152 .collect(Collectors.toList());
155 private static String mapValidationExceptionToMessage(ValidationException exception) {
156 if (exception.getViolatedSchema() instanceof EnumSchema) {
157 return mapEnumViolationToMessage(exception);
159 return exception.getMessage();
162 private static String mapEnumViolationToMessage(ValidationException exception) {
163 Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
164 return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
165 ? String.format("value. %s is the only possible value for this field",
166 possibleValues.iterator().next())
167 : String.format("value. Possible values: %s", CommonMethods
168 .collectionToCommaSeparatedString(
169 possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
172 private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
173 if (json == null || jsonSchema == null) {
174 throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
177 Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
179 schemaObj.validate(new JSONObject(json));
180 } catch (ValidationException ve) {
181 return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
182 : ve.getCausingExceptions();