57e7202ffbf079c168e4a27109afa1a8fa7804a6
[vfc/nfvo/driver/vnfm/gvnfm.git] / juju / juju-vnfmadapter / Juju-vnfmadapterService / service / src / main / java / org / openo / nfvo / jujuvnfmadapter / common / VNFJsonUtil.java
1 /*
2  * Copyright 2016 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openo.nfvo.jujuvnfmadapter.common;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.text.SimpleDateFormat;
22 import java.util.ArrayList;
23 import java.util.Date;
24 import java.util.List;
25
26 import javax.servlet.http.HttpServletRequest;
27
28 import org.apache.commons.io.IOUtils;
29 import org.codehaus.jackson.map.ObjectMapper;
30 import org.codehaus.jackson.type.TypeReference;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import net.sf.ezmorph.object.DateMorpher;
35 import net.sf.json.JSON;
36 import net.sf.json.JSONArray;
37 import net.sf.json.JSONException;
38 import net.sf.json.JSONObject;
39 import net.sf.json.JsonConfig;
40 import net.sf.json.processors.JsonValueProcessor;
41 import net.sf.json.util.CycleDetectionStrategy;
42 import net.sf.json.util.JSONTokener;
43 import net.sf.json.util.JSONUtils;
44
45 /**
46  * 
47  * Virtual Network Function Json Utility class.<br>
48  * <p>
49  * </p>
50  * 
51  * @author
52  * @version     NFVO 0.5  Sep 10, 2016
53  */
54 public final class VNFJsonUtil {
55
56     private static final Logger LOG = LoggerFactory.getLogger(VNFJsonUtil.class);
57
58     private static final ObjectMapper VNFMAPPER = new ObjectMapper();
59     
60     private static final String ERROR = "error";
61     static {
62         VNFMAPPER.setDeserializationConfig(VNFMAPPER.getDeserializationConfig()
63                 .without(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES));
64     }
65
66     private VNFJsonUtil() {
67     }
68
69     /**
70      * 
71      * UnMarshal method.<br>
72      * 
73      * @param vnfJsonstr
74      * @param type
75      * @return
76      * @throws IOException
77      * @since  NFVO 0.5
78      */
79     public static <T> T unMarshal(String vnfJsonstr, Class<T> type) throws IOException {
80         return VNFMAPPER.readValue(vnfJsonstr, type);
81     }
82
83     /**
84      * 
85      * UnMarshal method.<br>
86      * 
87      * @param vnfJsonstr
88      * @param type
89      * @return
90      * @throws IOException
91      * @since  NFVO 0.5
92      */
93     public static <T> T unMarshal(String vnfJsonstr, TypeReference<T> type) throws IOException {
94         return VNFMAPPER.readValue(vnfJsonstr, type);
95     }
96
97     /**
98      * 
99      * Marshal method.<br>
100      * 
101      * @param srcObj
102      * @return
103      * @throws IOException
104      * @since  NFVO 0.5
105      */
106     public static String marshal(Object srcObj) throws IOException {
107         if(srcObj instanceof JSON) {
108             return srcObj.toString();
109         }
110         return VNFMAPPER.writeValueAsString(srcObj);
111     }
112
113     public static ObjectMapper getMapper() {
114         return VNFMAPPER;
115     }
116
117     /**
118      * 
119      * Get Json field string.<br>
120      * 
121      * @param vnfJsonObj
122      * @param fieldName
123      * @return
124      * @since  NFVO 0.5
125      */
126     public static String getJsonFieldStr(JSONObject vnfJsonObj, String fieldName) {
127         if(null == vnfJsonObj || null == vnfJsonObj.get(fieldName) || "null".equals(vnfJsonObj.getString(fieldName))) {
128             LOG.warn("getJsonFieldStr: VNFJson object field(" + fieldName + ") is null.");
129             return "";
130         }
131
132         return vnfJsonObj.getString(fieldName);
133     }
134
135     /**
136      * 
137      * Get Json field integer.<br>
138      * 
139      * @param vnfJsonObj
140      * @param fieldName
141      * @return
142      * @since  NFVO 0.5
143      */
144     public static Integer getJsonFieldInt(JSONObject vnfJsonObj, String fieldName) {
145         if(null == vnfJsonObj || null == vnfJsonObj.get(fieldName)) {
146             LOG.warn("getJsonFieldInt: VNFJson object field(" + fieldName + ") is Null");
147             return 0;
148         }
149         return vnfJsonObj.getInt(fieldName);
150     }
151
152     /**
153      * 
154      * Get Json field long.<br>
155      * 
156      * @param vnfJsonObj
157      * @param fieldName
158      * @return
159      * @since  NFVO 0.5
160      */
161     public static Long getJsonFieldLong(JSONObject vnfJsonObj, String fieldName) {
162         if(null == vnfJsonObj || null == vnfJsonObj.get(fieldName)) {
163             LOG.warn("getJsonFieldLong: VNFJson object field(" + fieldName + ") is null");
164             return 0L;
165         }
166         return vnfJsonObj.getLong(fieldName);
167     }
168
169     /**
170      * 
171      * Parse error information.<br>
172      * 
173      * @param errorInfo
174      * @return
175      * @since  NFVO 0.5
176      */
177     public static String parseErrorInfo(String errorInfo) {
178         if((errorInfo != null) && (!errorInfo.isEmpty())) {
179             JSONObject errorInfoJst = JSONObject.fromObject(errorInfo);
180             if(errorInfoJst.has(ERROR) && errorInfoJst.getJSONObject(ERROR).has("message")) {
181                 return errorInfoJst.getJSONObject(ERROR).getString("message");
182             }
183         }
184         return "System Error!";
185     }
186
187     static {
188         VNFMAPPER.setDeserializationConfig(VNFMAPPER.getDeserializationConfig()
189                 .without(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES));
190     }
191
192     /**
193      * 
194      * Convert VNF Json to objects.<br>
195      * 
196      * @param vnfJsonString
197      * @param pojoCalss
198      * @return
199      * @since  NFVO 0.5
200      */
201     @SuppressWarnings("unchecked")
202     public static <T> T vnfJsonToObjects(String vnfJsonString, Class<T> pojoCalss) {
203         JSONObject vnfJsonObject = JSONObject.fromObject(vnfJsonString);
204         return (T)JSONObject.toBean(vnfJsonObject, pojoCalss);
205     }
206
207     /**
208      * 
209      * Convert VNF Json to objects.<br>
210      * 
211      * @param vnfJsonString
212      * @param vnfJsonConfig
213      * @return
214      * @since  NFVO 0.5
215      */
216     @SuppressWarnings("unchecked")
217     public static <T> T vnfJsonToObjects(String vnfJsonString, JsonConfig vnfJsonConfig) {
218         JSONObject vnfJsonObject = JSONObject.fromObject(vnfJsonString);
219         return (T)JSONObject.toBean(vnfJsonObject, vnfJsonConfig);
220     }
221
222     /**
223      * 
224      * Convert VNF Json to lists.<br>
225      * 
226      * @param vnfJsonString
227      * @param pojoClass
228      * @return
229      * @since  NFVO 0.5
230      */
231     @SuppressWarnings("unchecked")
232     public static <T> List<T> vnfJsonToLists(String vnfJsonString, Class<T> pojoClass) {
233         JSONArray vnfJsonVNFArray = JSONArray.fromObject(vnfJsonString);
234         JSONObject vnfJsonObject;
235         List<T> list = new ArrayList<>(20);
236         for(int i = 0; i < vnfJsonVNFArray.size(); i++) {
237             vnfJsonObject = vnfJsonVNFArray.getJSONObject(i);
238             list.add((T)JSONObject.toBean(vnfJsonObject, pojoClass));
239         }
240         return list;
241     }
242
243     /**
244      * 
245      * Convert VNF Json to list.<br>
246      * 
247      * @param vnfJsonString
248      * @param pojoClass
249      * @param dataFormat
250      * @return
251      * @since  NFVO 0.5
252      */
253     @SuppressWarnings("unchecked")
254     public static <T> List<T> vnfJsonToList(String vnfJsonString, Class<T> pojoClass, String dataFormat) {
255         JsonConfig vnfJsonConfig = configJson(dataFormat);
256         JSONArray vnfJsonVNFArray = JSONArray.fromObject(vnfJsonString, vnfJsonConfig);
257         JSONObject vnfJsonObject;
258         List<T> list = new ArrayList<>(20);
259         for(int i = 0; i < vnfJsonVNFArray.size(); i++) {
260             vnfJsonObject = vnfJsonVNFArray.getJSONObject(i);
261             list.add((T)JSONObject.toBean(vnfJsonObject, pojoClass));
262         }
263         return list;
264     }
265
266     /**
267      * 
268      * Object to json string.<br>
269      * 
270      * @param javaObj
271      * @return
272      * @since  NFVO 0.5
273      */
274     public static String objectToJsonStr(Object javaObj) {
275         JSONObject vnfJson = JSONObject.fromObject(javaObj);
276         return vnfJson.toString();
277     }
278
279     /**
280      * 
281      * object to json.<br>
282      * 
283      * @param javaObj
284      * @return
285      * @since  NFVO 0.5
286      */
287     public static JSONObject objectToJson(Object javaObj) {
288         return JSONObject.fromObject(javaObj);
289     }
290
291     /**
292      * 
293      * Object to json.<br>
294      * 
295      * @param javaObj
296      * @param vnfJsonConfig
297      * @return
298      * @since  NFVO 0.5
299      */
300     public static String objectToJson(Object javaObj, JsonConfig vnfJsonConfig) {
301         JSONObject vnfJson = JSONObject.fromObject(javaObj, vnfJsonConfig);
302         return vnfJson.toString();
303     }
304
305     /**
306      * 
307      * Object to json.<br>
308      * 
309      * @param javaObj
310      * @param dataFormat
311      * @return
312      * @since  NFVO 0.5
313      */
314     public static String objectToJson(Object javaObj, String dataFormat) {
315         JsonConfig vnfJsonConfig = configJson(dataFormat);
316         JSONObject vnfJson = JSONObject.fromObject(javaObj, vnfJsonConfig);
317         return vnfJson.toString();
318
319     }
320
321     /**
322      * 
323      * List to json.<br>
324      * 
325      * @param list
326      * @return
327      * @since  NFVO 0.5
328      */
329     public static <T> String listToJson(List<T> list) {
330         JSONArray vnfJson = JSONArray.fromObject(list);
331         return vnfJson.toString();
332     }
333
334     /**
335      * 
336      * List to json.<br>
337      * 
338      * @param list
339      * @param dataFormat
340      * @return
341      * @since  NFVO 0.5
342      */
343     public static <T> String listToJson(List<T> list, String dataFormat) {
344         JsonConfig vnfJsonConfig = configJson(dataFormat);
345         JSONArray vnfJson = JSONArray.fromObject(list, vnfJsonConfig);
346         return vnfJson.toString();
347     }
348
349     /**
350      * 
351      * Config json.<br>
352      * 
353      * @param datePattern
354      * @return
355      * @since  NFVO 0.5
356      */
357     public static JsonConfig configJson(final String datePattern) {
358
359         JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {datePattern}));
360
361         JsonConfig vnfJsonConfig = new JsonConfig();
362         vnfJsonConfig.setIgnoreDefaultExcludes(false);
363         vnfJsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
364         vnfJsonConfig.registerJsonValueProcessor(Date.class, new JsonValueProcessor() {
365             @Override
366             public Object processObjectValue(String key, Object value, JsonConfig vnfJsonConfig) {
367                 if(value instanceof Date) {
368                     return new SimpleDateFormat(datePattern).format((Date)value);
369                 }
370                 return value == null ? null : value.toString();
371             }
372             @Override
373             public Object processArrayValue(Object value, JsonConfig vnfJsonConfig) {
374                 String[] vnfObj = {};
375                 SimpleDateFormat vnfSf = new SimpleDateFormat(datePattern);
376                 if(value instanceof Date[]) {
377                     Date[] dates = (Date[])value;
378                     vnfObj = new String[dates.length];
379                     for(int i = 0; i < dates.length; i++) {
380                         vnfObj[i] = vnfSf.format(dates[i]);
381                     }
382                 }
383                 return vnfObj;
384             }
385         });
386         return vnfJsonConfig;
387     }
388
389     /**
390      * @param context the HttpContext
391      * @param <T> JSONObject or JSONArray
392      * @return
393      */
394     @SuppressWarnings("unchecked")
395     public static <T> T getJsonFromContext(HttpServletRequest context) {
396         try {
397             InputStream input = context.getInputStream();
398             String vnfJsonStr = IOUtils.toString(input);
399             JSONTokener vnfVnfJsonTokener = new JSONTokener(vnfJsonStr);
400
401             // "{"
402             if(vnfVnfJsonTokener.nextClean() == Character.codePointAt("{", 0)) {
403                 return (T)JSONObject.fromObject(vnfJsonStr);
404             }
405
406             vnfVnfJsonTokener.back();
407
408             // "["
409             if(vnfVnfJsonTokener.nextClean() == Character.codePointAt("[", 0)) {
410                 return (T)JSONArray.fromObject(vnfJsonStr);
411             }
412         } catch(IOException e) {
413             LOG.error("function=getJsonFromContext,msg= IOException occurs. exception=" + e);
414         } catch(JSONException e) {
415             LOG.error("function=getJsonFromContext,msg= JSONException occurs, exception=" + e);
416         }
417         return null;
418     }
419
420 }