5f0bc9084504f94a6e167900a30abfd5c12675ef
[sdc.git] /
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 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.sdc.logging.api.Logger;
36 import org.openecomp.sdc.logging.api.LoggerFactory;
37
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;
46 import java.util.Set;
47 import java.util.stream.Collectors;
48
49 /**
50  * The type Json util.
51  */
52 public class JsonUtil {
53   private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);
54
55   /**
56    * Object 2 json string.
57    *
58    * @param obj the obj
59    * @return the string
60    */
61   //TODO: refactor all other ugly code to use this
62   public static String object2Json(Object obj) {
63     return sbObject2Json(obj).toString();
64
65   }
66
67   /**
68    * Sb object 2 json string buffer.
69    *
70    * @param obj the obj
71    * @return the string buffer
72    */
73   public static StringBuffer sbObject2Json(Object obj) {
74     return new StringBuffer((new GsonBuilder()).setPrettyPrinting().create().toJson(obj));
75   }
76
77   /**
78    * Json 2 object t.
79    *
80    * @param <T>      the type parameter
81    * @param json     the json
82    * @param classOfT the class of t
83    * @return the t
84    */
85   public static <T> T json2Object(String json, Class<T> classOfT) {
86     T typ;
87     try {
88       try (Reader br = new StringReader(json)) {
89         typ = new Gson().fromJson(br, classOfT);
90       } catch (IOException exception) {
91         throw exception;
92       }
93     } catch (JsonIOException | JsonSyntaxException | IOException exception) {
94       throw new RuntimeException(exception);
95     }
96     return typ;
97   }
98
99   /**
100    * Json 2 object t.
101    *
102    * @param <T>      the type parameter
103    * @param is       the is
104    * @param classOfT the class of t
105    * @return the t
106    */
107   public static <T> T json2Object(InputStream is, Class<T> classOfT) {
108     T type;
109     try {
110       try (Reader br = new BufferedReader(new InputStreamReader(is))) {
111         type = new Gson().fromJson(br, classOfT);
112       }
113     } catch (JsonIOException | JsonSyntaxException | IOException exception) {
114       throw new RuntimeException(exception);
115     } finally {
116       if (is != null) {
117         try {
118           is.close();
119         } catch (IOException ignore) {
120           //do nothing
121         }
122       }
123     }
124     return type;
125   }
126
127
128   /**
129    * Is valid json boolean.
130    *
131    * @param json the json
132    * @return the boolean
133    */
134   //todo check https://github.com/stleary/JSON-java as replacement for this code
135   public static boolean isValidJson(String json) {
136     try {
137       return new JsonParser().parse(json).isJsonObject();
138     } catch (JsonSyntaxException jse) {
139       return false;
140     }
141   }
142
143   /**
144    * Validate list.
145    *
146    * @param json       the json
147    * @param jsonSchema the json schema
148    * @return the list
149    */
150   public static List<String> validate(String json, String jsonSchema) {
151     List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
152     return validationErrors == null ? null
153         : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
154             .collect(Collectors.toList());
155   }
156
157   private static String mapValidationExceptionToMessage(ValidationException exception) {
158     if (exception.getViolatedSchema() instanceof EnumSchema) {
159       return mapEnumViolationToMessage(exception);
160     }
161     return exception.getMessage();
162   }
163
164   private static String mapEnumViolationToMessage(ValidationException exception) {
165     Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
166     return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
167         ? String.format("value. %s is the only possible value for this field",
168         possibleValues.iterator().next())
169         : String.format("value. Possible values: %s", CommonMethods
170             .collectionToCommaSeparatedString(
171                 possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
172   }
173
174   private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
175     logger.debug(
176         String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
177     if (json == null || jsonSchema == null) {
178       throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
179     }
180
181     Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
182     try {
183       schemaObj.validate(new JSONObject(json));
184     } catch (ValidationException ve) {
185       return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
186           : ve.getCausingExceptions();
187     }
188     return null;
189   }
190 }