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