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.core.utilities.deserializers.RequirementDefinitionDeserializer;
36 import org.openecomp.sdc.logging.api.Logger;
37 import org.openecomp.sdc.logging.api.LoggerFactory;
38 import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition;
40 import java.io.BufferedReader;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.InputStreamReader;
44 import java.io.Reader;
45 import java.io.StringReader;
46 import java.util.Collections;
47 import java.util.List;
49 import java.util.stream.Collectors;
54 public class JsonUtil {
55 private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
56 private static final GsonBuilder gsonBuilder;
57 private static final Gson gson;
60 gsonBuilder = new GsonBuilder();
61 gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new
62 RequirementDefinitionDeserializer());
63 gson = gsonBuilder.create();
67 * Object 2 json string.
72 //TODO: refactor all other ugly code to use this
73 public static String object2Json(Object obj) {
74 return sbObject2Json(obj).toString();
79 * Sb object 2 json string buffer.
82 * @return the string buffer
84 public static StringBuffer sbObject2Json(Object obj) {
85 return new StringBuffer((new GsonBuilder()).setPrettyPrinting().create().toJson(obj));
91 * @param <T> the type parameter
92 * @param json the json
93 * @param classOfT the class of t
96 public static <T> T json2Object(String json, Class<T> classOfT) {
99 try (Reader br = new StringReader(json)) {
100 typ = gson.fromJson(br, classOfT);
102 } catch (JsonIOException | JsonSyntaxException | IOException exception) {
103 throw new RuntimeException(exception);
111 * @param <T> the type parameter
113 * @param classOfT the class of t
116 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);
128 } catch (IOException ignore) {
129 logger.debug("",ignore);
139 * Is valid json boolean.
141 * @param json the json
142 * @return the boolean
144 //todo check https://github.com/stleary/JSON-java as replacement for this code
145 public static boolean isValidJson(String json) {
147 return new JsonParser().parse(json).isJsonObject();
148 } catch (JsonSyntaxException jse) {
149 logger.debug("",jse);
157 * @param json the json
158 * @param jsonSchema the json schema
161 public static List<String> validate(String json, String jsonSchema) {
162 List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
163 return validationErrors == null ? null
164 : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
165 .collect(Collectors.toList());
168 private static String mapValidationExceptionToMessage(ValidationException exception) {
169 if (exception.getViolatedSchema() instanceof EnumSchema) {
170 return mapEnumViolationToMessage(exception);
172 return exception.getMessage();
175 private static String mapEnumViolationToMessage(ValidationException exception) {
176 Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
177 return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
178 ? String.format("value. %s is the only possible value for this field",
179 possibleValues.iterator().next())
180 : String.format("value. Possible values: %s", CommonMethods
181 .collectionToCommaSeparatedString(
182 possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
185 private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
187 String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
188 if (json == null || jsonSchema == null) {
189 throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
192 Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
194 schemaObj.validate(new JSONObject(json));
195 } catch (ValidationException ve) {
196 return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
197 : ve.getCausingExceptions();