Merge "Other option for license agreement term"
[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 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           logger.debug("",ignore);
121           //do nothing
122         }
123       }
124     }
125     return type;
126   }
127
128
129   /**
130    * Is valid json boolean.
131    *
132    * @param json the json
133    * @return the boolean
134    */
135   //todo check https://github.com/stleary/JSON-java as replacement for this code
136   public static boolean isValidJson(String json) {
137     try {
138       return new JsonParser().parse(json).isJsonObject();
139     } catch (JsonSyntaxException jse) {
140       logger.debug("",jse);
141       return false;
142     }
143   }
144
145   /**
146    * Validate list.
147    *
148    * @param json       the json
149    * @param jsonSchema the json schema
150    * @return the list
151    */
152   public static List<String> validate(String json, String jsonSchema) {
153     List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
154     return validationErrors == null ? null
155         : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
156             .collect(Collectors.toList());
157   }
158
159   private static String mapValidationExceptionToMessage(ValidationException exception) {
160     if (exception.getViolatedSchema() instanceof EnumSchema) {
161       return mapEnumViolationToMessage(exception);
162     }
163     return exception.getMessage();
164   }
165
166   private static String mapEnumViolationToMessage(ValidationException exception) {
167     Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
168     return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
169         ? String.format("value. %s is the only possible value for this field",
170         possibleValues.iterator().next())
171         : String.format("value. Possible values: %s", CommonMethods
172             .collectionToCommaSeparatedString(
173                 possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
174   }
175
176   private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
177     logger.debug(
178         String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
179     if (json == null || jsonSchema == null) {
180       throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
181     }
182
183     Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
184     try {
185       schemaObj.validate(new JSONObject(json));
186     } catch (ValidationException ve) {
187       return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
188           : ve.getCausingExceptions();
189     }
190     return null;
191   }
192 }