Fix occurences not deserialized properly
[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.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;
39
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;
48 import java.util.Set;
49 import java.util.stream.Collectors;
50
51 /**
52  * The type Json util.
53  */
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;
58
59   static {
60     gsonBuilder = new GsonBuilder();
61     gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new
62         RequirementDefinitionDeserializer());
63     gson = gsonBuilder.create();
64   }
65
66   /**
67    * Object 2 json string.
68    *
69    * @param obj the obj
70    * @return the string
71    */
72   //TODO: refactor all other ugly code to use this
73   public static String object2Json(Object obj) {
74     return sbObject2Json(obj).toString();
75
76   }
77
78   /**
79    * Sb object 2 json string buffer.
80    *
81    * @param obj the obj
82    * @return the string buffer
83    */
84   public static StringBuffer sbObject2Json(Object obj) {
85     return new StringBuffer((new GsonBuilder()).setPrettyPrinting().create().toJson(obj));
86   }
87
88   /**
89    * Json 2 object t.
90    *
91    * @param <T>      the type parameter
92    * @param json     the json
93    * @param classOfT the class of t
94    * @return the t
95    */
96   public static <T> T json2Object(String json, Class<T> classOfT) {
97     T typ;
98     try {
99       try (Reader br = new StringReader(json)) {
100         typ = gson.fromJson(br, classOfT);
101       }
102     } catch (JsonIOException | JsonSyntaxException | IOException exception) {
103       throw new RuntimeException(exception);
104     }
105     return typ;
106   }
107
108   /**
109    * Json 2 object t.
110    *
111    * @param <T>      the type parameter
112    * @param is       the is
113    * @param classOfT the class of t
114    * @return the t
115    */
116   public static <T> T json2Object(InputStream is, Class<T> classOfT) {
117     T type;
118     try {
119       try (Reader br = new BufferedReader(new InputStreamReader(is))) {
120         type = new Gson().fromJson(br, classOfT);
121       }
122     } catch (JsonIOException | JsonSyntaxException | IOException exception) {
123       throw new RuntimeException(exception);
124     } finally {
125       if (is != null) {
126         try {
127           is.close();
128         } catch (IOException ignore) {
129           logger.debug("",ignore);
130           //do nothing
131         }
132       }
133     }
134     return type;
135   }
136
137
138   /**
139    * Is valid json boolean.
140    *
141    * @param json the json
142    * @return the boolean
143    */
144   //todo check https://github.com/stleary/JSON-java as replacement for this code
145   public static boolean isValidJson(String json) {
146     try {
147       return new JsonParser().parse(json).isJsonObject();
148     } catch (JsonSyntaxException jse) {
149       logger.debug("",jse);
150       return false;
151     }
152   }
153
154   /**
155    * Validate list.
156    *
157    * @param json       the json
158    * @param jsonSchema the json schema
159    * @return the list
160    */
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());
166   }
167
168   private static String mapValidationExceptionToMessage(ValidationException exception) {
169     if (exception.getViolatedSchema() instanceof EnumSchema) {
170       return mapEnumViolationToMessage(exception);
171     }
172     return exception.getMessage();
173   }
174
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()))));
183   }
184
185   private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
186     logger.debug(
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");
190     }
191
192     Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
193     try {
194       schemaObj.validate(new JSONObject(json));
195     } catch (ValidationException ve) {
196       return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
197           : ve.getCausingExceptions();
198     }
199     return null;
200   }
201 }