190eba16d604bf4728825b81e5deb3808a1e23f4
[sdc.git] / openecomp-be / lib / openecomp-core-lib / openecomp-utilities-lib / src / main / java / org / openecomp / core / utilities / json / JsonUtil.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.core.utilities.json;
22
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
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;
40
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;
49 import java.util.Set;
50 import java.util.stream.Collectors;
51
52 /**
53  * The type Json util.
54  */
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;
59
60   static {
61     gsonBuilder = new GsonBuilder();
62     gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new
63         RequirementDefinitionDeserializer());
64     gson = gsonBuilder.create();
65   }
66
67   private JsonUtil() {
68   }
69
70   /**
71    * Object 2 json string.
72    *
73    * @param obj the obj
74    * @return the string
75    */
76   public static String object2Json(Object obj) {
77     return sbObject2Json(obj).toString();
78
79   }
80
81   /**
82    * Sb object 2 json string builder.
83    *
84    * @param obj the obj
85    * @return the string builder
86    */
87   public static StringBuilder sbObject2Json(Object obj) {
88     return new StringBuilder(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
89   }
90
91   /**
92    * Json 2 object t.
93    *
94    * @param <T>      the type parameter
95    * @param json     the json
96    * @param classOfT the class of t
97    * @return the t
98    */
99   public static <T> T json2Object(String json, Class<T> classOfT) {
100     T typ;
101     try {
102       try (Reader br = new StringReader(json)) {
103         typ = gson.fromJson(br, classOfT);
104       }
105     } catch (JsonIOException | JsonSyntaxException | IOException exception) {
106       throw new RuntimeException(exception);
107     }
108     return typ;
109   }
110
111   /**
112    * Json 2 object t.
113    *
114    * @param <T>      the type parameter
115    * @param is       the is
116    * @param classOfT the class of t
117    * @return the t
118    */
119   public static <T> T json2Object(InputStream is, Class<T> classOfT) {
120     T type;
121     try {
122       try (Reader br = new BufferedReader(new InputStreamReader(is))) {
123         type = new Gson().fromJson(br, classOfT);
124       }
125     } catch (JsonIOException | JsonSyntaxException | IOException exception) {
126       throw new RuntimeException(exception);
127     } finally {
128       if (is != null) {
129         try {
130           is.close();
131         } catch (IOException ignore) {
132           logger.debug("",ignore);
133           //do nothing
134         }
135       }
136     }
137     return type;
138   }
139
140
141   /**
142    * Is valid json boolean.
143    *
144    * @param json the json
145    * @return the boolean
146    */
147   //todo check https://github.com/stleary/JSON-java as replacement for this code
148   public static boolean isValidJson(String json) {
149     try {
150       return new JsonParser().parse(json).isJsonObject();
151     } catch (JsonSyntaxException jse) {
152       logger.debug("",jse);
153       return false;
154     }
155   }
156
157   /**
158    * Validate list.
159    *
160    * @param json       the json
161    * @param jsonSchema the json schema
162    * @return the list
163    */
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());
169   }
170
171   private static String mapValidationExceptionToMessage(ValidationException exception) {
172     if (exception.getViolatedSchema() instanceof EnumSchema) {
173       return mapEnumViolationToMessage(exception);
174     }
175     return exception.getMessage();
176   }
177
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()))));
186   }
187
188   private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
189     logger.debug(
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");
193     }
194
195     Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
196     try {
197       schemaObj.validate(new JSONObject(json));
198     } catch (ValidationException ve) {
199       return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
200           : ve.getCausingExceptions();
201     }
202     return null;
203   }
204 }