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