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;
36 import org.openecomp.core.utilities.deserializers.RequirementDefinitionDeserializer;
37 import org.openecomp.sdc.logging.api.Logger;
38 import org.openecomp.sdc.logging.api.LoggerFactory;
39 import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
41 import java.io.BufferedReader;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.InputStreamReader;
45 import java.io.Reader;
46 import java.io.StringReader;
47 import java.util.Collections;
48 import java.util.List;
50 import java.util.stream.Collectors;
55 public class JsonUtil {
56 private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
57 private static final GsonBuilder gsonBuilder;
58 private static final Gson gson;
61 gsonBuilder = new GsonBuilder();
62 gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new
63 RequirementDefinitionDeserializer());
64 gson = gsonBuilder.create();
71 * Object 2 json string.
76 public static String object2Json(Object obj) {
77 return sbObject2Json(obj).toString();
82 * Sb object 2 json string builder.
85 * @return the string builder
87 public static StringBuilder sbObject2Json(Object obj) {
88 return new StringBuilder(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
94 * @param <T> the type parameter
95 * @param json the json
96 * @param classOfT the class of t
99 public static <T> T json2Object(String json, Class<T> classOfT) {
102 try (Reader br = new StringReader(json)) {
103 typ = gson.fromJson(br, classOfT);
105 } catch (JsonIOException | JsonSyntaxException | IOException exception) {
106 throw new RuntimeException(exception);
114 * @param <T> the type parameter
116 * @param classOfT the class of t
119 public static <T> T json2Object(InputStream is, Class<T> classOfT) {
122 try (Reader br = new BufferedReader(new InputStreamReader(is))) {
123 type = new Gson().fromJson(br, classOfT);
125 } catch (JsonIOException | JsonSyntaxException | IOException exception) {
126 throw new RuntimeException(exception);
131 } catch (IOException ignore) {
132 logger.debug("",ignore);
142 * Is valid json boolean.
144 * @param json the json
145 * @return the boolean
147 //todo check https://github.com/stleary/JSON-java as replacement for this code
148 public static boolean isValidJson(String json) {
150 return new JsonParser().parse(json).isJsonObject();
151 } catch (JsonSyntaxException jse) {
152 logger.debug("",jse);
160 * @param json the json
161 * @param jsonSchema the json schema
164 public static List<String> validate(String json, String jsonSchema) {
165 List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
166 return validationErrors == null ? null
167 : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
168 .collect(Collectors.toList());
171 private static String mapValidationExceptionToMessage(ValidationException exception) {
172 if (exception.getViolatedSchema() instanceof EnumSchema) {
173 return mapEnumViolationToMessage(exception);
175 return exception.getMessage();
178 private static String mapEnumViolationToMessage(ValidationException exception) {
179 Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
180 return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
181 ? String.format("value. %s is the only possible value for this field",
182 possibleValues.iterator().next())
183 : String.format("value. Possible values: %s", CommonMethods
184 .collectionToCommaSeparatedString(
185 possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
188 private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
190 String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
191 if (json == null || jsonSchema == null) {
192 throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
195 Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
197 schemaObj.validate(new JSONObject(json));
198 } catch (ValidationException ve) {
199 return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
200 : ve.getCausingExceptions();