bmpn sonar issue fix
[so.git] / bpmn / MSOCoreBPMN / src / main / java / org / openecomp / mso / bpmn / core / json / JsonUtils.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP - SO\r
4  * ================================================================================\r
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.\r
7  * ================================================================================\r
8  * Licensed under the Apache License, Version 2.0 (the "License");\r
9  * you may not use this file except in compliance with the License.\r
10  * You may obtain a copy of the License at\r
11  * \r
12  *      http://www.apache.org/licenses/LICENSE-2.0\r
13  * \r
14  * Unless required by applicable law or agreed to in writing, software\r
15  * distributed under the License is distributed on an "AS IS" BASIS,\r
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
17  * See the License for the specific language governing permissions and\r
18  * limitations under the License.\r
19  * ============LICENSE_END=========================================================\r
20  */\r
21 \r
22 package org.openecomp.mso.bpmn.core.json;\r
23 \r
24 import java.util.ArrayList;\r
25 import java.util.Iterator;\r
26 import java.util.List;\r
27 import java.util.Map;\r
28 import java.util.HashMap;\r
29 import java.util.StringTokenizer;\r
30 \r
31 import org.camunda.bpm.engine.runtime.Execution;\r
32 import org.json.JSONArray;\r
33 import org.json.JSONException;\r
34 import org.json.JSONObject;\r
35 import org.json.XML;\r
36 \r
37 //import org.openecomp.mso.bpmn.core.BPMNLogger;\r
38 import org.openecomp.mso.bpmn.core.xml.XmlTool;\r
39 import org.openecomp.mso.logger.MsoLogger;\r
40 \r
41 /**\r
42  * Utility class for JSON processing\r
43  * \r
44  * @version 1.0\r
45  */\r
46 \r
47 public class JsonUtils {\r
48 \r
49         private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);\r
50         private static int MSOJsonIndentFactor = 3;\r
51 \r
52         /**\r
53          * Uses the JSONObject static method to convert a XML doc to JSON.\r
54          *\r
55          * @param  xml          String containing the XML doc\r
56          * @param  pretty       flag to determine if the output should be formatted\r
57          * @return String containing the JSON translation\r
58          */\r
59         public static String xml2json(String xml, Boolean pretty) {\r
60 //              String isDebugLogEnabled = "true";\r
61                 try {\r
62                         // name spaces cause problems, so just remove them\r
63                         JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml));\r
64                         if (!pretty) {\r
65                                 return jsonObj.toString();\r
66                         } else {\r
67                                 // add an indent to make it 'pretty'\r
68                                 return jsonObj.toString(MSOJsonIndentFactor);\r
69                         }\r
70                 } catch (Exception e){\r
71                                 msoLogger.debug("xml2json(): unable to parse xml and convert to json. Exception was: " + e.toString(), e);\r
72                                 return null;\r
73                 }\r
74         }\r
75 \r
76         /**\r
77          * Invokes xml2json(String, Boolean) defaulting to 'pretty' output.\r
78          *\r
79          * @param  xml  String containing the XML doc\r
80          * @return String containing the JSON translation\r
81          */\r
82         public static String xml2json(String xml) {\r
83                 return xml2json(xml, true);\r
84         }\r
85 \r
86         /**\r
87          * Uses the JSONObject static method to convert a JSON doc to XML.\r
88          * Note: this method may not generate valid XML if the JSONObject\r
89          * contains JSONArrays which are used to represent XML attributes\r
90          * in the JSON doc.\r
91          *\r
92          * @param  jsonStr      String containing the JSON doc\r
93          * @param  pretty       flag to determine if the output should be formatted\r
94          * @return String containing the XML translation\r
95          */\r
96         public static String json2xml(String jsonStr, Boolean pretty) {\r
97 //              String isDebugLogEnabled = "true";\r
98                 try {\r
99                         JSONObject jsonObj = new JSONObject(jsonStr);\r
100                         if (pretty) {\r
101 //                              return XmlTool.normalize(XML.toString(jsonObj));\r
102 //                              use the local class method which properly handles certain JSONArray content\r
103                                 return XmlTool.normalize(toXMLString(jsonObj, null));\r
104                         } else {\r
105 //                              return XML.toString(jsonObj);\r
106 //                              use the local class method which properly handles certain JSONArray content\r
107                                 return toXMLString(jsonObj, null);\r
108                         }\r
109                 } catch (Exception e){\r
110                                 msoLogger.debug("json2xml(): unable to parse json and convert to xml. Exception was: " + e.toString(), e);\r
111                                 return null;\r
112                 }\r
113         }\r
114 \r
115         /**\r
116          * Uses a modified version of the org.json.XML toString() algorithm\r
117          * to convert a JSONObject to an XML Doc. The intent of this is to\r
118          * correctly generate XML from JSON including TAGs for JSONArrays\r
119          *\r
120          * @param  jsonObj      org.json.JSON object to be converted to XML\r
121          * @param  tagName      optional XML tagname supplied primarily during recursive calls\r
122          * @return String containing the XML translation\r
123          */\r
124         public static String toXMLString(Object obj, String tagName) throws JSONException {\r
125                 StringBuffer strBuf = new StringBuffer();\r
126                 int i;\r
127                 JSONArray jsonArr;\r
128                 JSONObject jsonObj;\r
129                 String key;\r
130                 Iterator<String> keys;\r
131                 int len;\r
132                 String str;\r
133                 Object curObj;\r
134                 if (obj instanceof JSONObject) {\r
135                         // msoLogger.debug("toXMLString(): is a JSONObject");\r
136                         // append "<tagName>" to the XML output\r
137                         if (tagName != null) {\r
138 //                              msoLogger.debug("toXMLString(): adding opening tagName: " + tagName);\r
139                                 strBuf.append("<");\r
140                                 strBuf.append(tagName);\r
141                                 strBuf.append(">");\r
142                         }\r
143                         // iterate thru the keys.\r
144                         jsonObj = (JSONObject) obj;\r
145                         keys = jsonObj.keys();\r
146                         while (keys.hasNext()) {\r
147                                 key = keys.next().toString();\r
148                                 // msoLogger.debug("toXMLString(): key is " + k);\r
149                                 curObj = jsonObj.opt(key);\r
150                                 if (curObj == null) {\r
151                                         curObj = "";\r
152                                 }\r
153                                 if (curObj instanceof String) {\r
154                                         str = (String) curObj;\r
155                                 } else {\r
156                                         str = null;\r
157                                 }\r
158                                 // append the content to the XML output\r
159                                 if (key.equals("content")) {\r
160                                         if (curObj instanceof JSONArray) {\r
161                                                 jsonArr = (JSONArray) curObj;\r
162                                                 len = jsonArr.length();\r
163                                                 for (i = 0; i < len; i += 1) {\r
164                                                         if (i > 0) {\r
165                                                                 strBuf.append('\n');\r
166                                                         }\r
167                                                         strBuf.append(XML.escape(jsonArr.get(i).toString()));\r
168                                                 }\r
169                                         } else {\r
170                                                 strBuf.append(XML.escape(curObj.toString()));\r
171                                         }\r
172                                 // append an array of similar keys to the XML output\r
173                                 } else if (curObj instanceof JSONArray) {\r
174                                         jsonArr = (JSONArray) curObj;\r
175                                         len = jsonArr.length();\r
176 //                                      msoLogger.debug("toXMLString(): found JSONArray: " + key + ", size: " + len);\r
177                                         for (i = 0; i < len; i += 1) {\r
178                                                 curObj = jsonArr.get(i);\r
179                                                 if (curObj instanceof JSONArray) {\r
180 //                                                      The XML tags for the nested array should be generated below when this method\r
181 //                                                      is called recursively and the JSONArray object is passed\r
182 //                                                      strBuf.append("<");\r
183 //                                                      strBuf.append(key);\r
184 //                                                      strBuf.append(">");\r
185                                                         strBuf.append(toXMLString(curObj, null));\r
186 //                                                      strBuf.append("</");\r
187 //                                                      strBuf.append(key);\r
188 //                                                      strBuf.append(">");\r
189                                                 } else {\r
190 //                                                      msoLogger.debug("toXMLString(): recursive call toXML() with tagName null");\r
191                                                         // append the opening tag for the array (before 1st element)\r
192                                                         if (i == 0) {\r
193                                                                 strBuf.append("<");\r
194                                                                 strBuf.append(key);\r
195                                                                 strBuf.append(">");\r
196                                                         }\r
197                                                         // append the opening tag for the array\r
198                                                         strBuf.append(toXMLString(curObj, null));\r
199                                                         // append the closing tag for the array (after last element)\r
200                                                         if (i == (len - 1)) {\r
201                                                                 strBuf.append("</");\r
202                                                                 strBuf.append(key);\r
203                                                                 strBuf.append(">");\r
204                                                         }\r
205                                                 }\r
206                                         }\r
207                                 } else if (curObj.equals("")) {\r
208                                         // append a closing tag "<key>" to the XML output\r
209                                         strBuf.append("<");\r
210                                         strBuf.append(key);\r
211                                         strBuf.append("/>");\r
212                                 } else {\r
213 //                                      msoLogger.debug("toXMLString(): recursive call toXMLString() with tagName: " + key);\r
214                                         strBuf.append(toXMLString(curObj, key));\r
215                                 }\r
216                                 // msoLogger.debug("toXML(): partial XML: " + strBuf.toString());\r
217                         }\r
218                         if (tagName != null) {\r
219                                 // append the closing tag "</tagName>" to the XML output\r
220 //                              msoLogger.debug("toXMLString(): adding closing tagName: " + tagName);\r
221                                 strBuf.append("</");\r
222                                 strBuf.append(tagName);\r
223                                 strBuf.append(">");\r
224                         }\r
225                         return strBuf.toString();\r
226                 // XML does not have good support for arrays. If an array appears in a place\r
227                 // where XML is lacking, synthesize an < array > element.\r
228                 } else if (obj instanceof JSONArray) {\r
229                         jsonArr = (JSONArray) obj;\r
230                         len = jsonArr.length();\r
231                         for (i = 0; i < len; ++i) {\r
232                                 curObj = jsonArr.opt(i);\r
233                                 strBuf.append(toXMLString(curObj, (tagName == null) ? "array"\r
234                                                 : tagName));\r
235                         }\r
236                         return strBuf.toString();\r
237                 } else {\r
238 //                      msoLogger.debug("toXML(): in else block with tagName: " + tagName);\r
239                         str = (obj == null) ? "null" : XML.escape(obj.toString());\r
240                         return (tagName == null) ? "\"" + str + "\""\r
241                                         : (str.length() == 0) ? "<" + tagName + "/>" : "<"\r
242                                                         + tagName + ">" + str + "</" + tagName + ">";\r
243                 }\r
244         }\r
245 \r
246         /**\r
247          * Invokes json2xml(String, Boolean) defaulting to 'pretty' output.\r
248          *\r
249          * @param  jsonStr      String containing the XML doc\r
250          * @return String containing the JSON translation\r
251          */\r
252         public static String json2xml(String jsonStr) {\r
253                 return json2xml(jsonStr, true);\r
254         }\r
255 \r
256         /**\r
257          * Formats the JSON String using the value of MSOJsonIndentFactor.\r
258          *\r
259          * @param  jsonStr      String containing the JSON doc\r
260          * @return String containing the formatted JSON doc\r
261          */\r
262         public static String prettyJson(String jsonStr) {\r
263 //              String isDebugLogEnabled = "true";\r
264                 try {\r
265                         JSONObject jsonObj = new JSONObject(jsonStr);\r
266                         return jsonObj.toString(MSOJsonIndentFactor);\r
267                 } catch (Exception e){\r
268                         msoLogger.debug("prettyJson(): unable to parse/format json input. Exception was: " + e.toString(), e);\r
269                         return null;\r
270                 }\r
271         }\r
272 \r
273         /**\r
274          * Returns an Iterator over the JSON keys in the specified JSON doc.\r
275          *\r
276          * @param  jsonStr      String containing the JSON doc\r
277          * @return Iterator over the JSON keys\r
278          * @throws JSONException if the doc cannot be parsed\r
279          */\r
280         public static Iterator <String> getJsonIterator(String jsonStr) throws JSONException {\r
281                 return new JSONObject(jsonStr).keys();\r
282         }\r
283 \r
284         /**\r
285          * Returns the name of the "root" property in the specified JSON doc. The\r
286          * "root" property is the single top-level property in the JSON doc. An\r
287          * exception is thrown if the doc is empty or if it contains more than one\r
288          * top-level property.\r
289          *\r
290          * @param  jsonStr      String containing the JSON doc\r
291          * @return the name of the "root" property\r
292          * @throws JSONException if the doc cannot be parsed, or if it is empty, or if\r
293          *         it contains more than one top-level property\r
294          */\r
295         public static String getJsonRootProperty(String jsonStr) throws JSONException {\r
296                 Iterator<String> iter = getJsonIterator(jsonStr);\r
297 \r
298                 if (!iter.hasNext()) {\r
299                         throw new JSONException("Empty JSON object");\r
300                 }\r
301 \r
302                 String rootPropertyName = iter.next();\r
303 \r
304                 if (iter.hasNext()) {\r
305                         throw new JSONException("JSON object has more than one root property");\r
306                 }\r
307 \r
308                 return rootPropertyName;\r
309         }\r
310 \r
311         /**\r
312          * Invokes the getJsonRawValue() method and returns the String equivalent of\r
313          * the object returned.\r
314          *\r
315          * TBD: May need separate methods for boolean, float, and integer fields if the\r
316          * String representation is not sufficient to meet client needs.\r
317          *\r
318          * @param  jsonStr      String containing the JSON doc\r
319          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
320          * @return String field value associated with keys\r
321          */\r
322         public static String getJsonValue(String jsonStr, String keys) {\r
323 //              String isDebugLogEnabled = "true";\r
324                 try {\r
325                                 Object rawValue = getJsonRawValue(jsonStr, keys);\r
326                                 if (rawValue == null) {\r
327                                         return null;\r
328                                 } else {\r
329                                         if (rawValue instanceof String) {\r
330                                                 msoLogger.debug("getJsonValue(): the raw value is a String Object=" + ((String) rawValue).toString());\r
331                                                 return (String) rawValue;\r
332                                         } else {\r
333                                                 msoLogger.debug("getJsonValue(): the raw value is NOT a String Object=" + rawValue.toString());\r
334                                                 return rawValue.toString();\r
335                                         }\r
336                                 }\r
337                 } catch (Exception e) {\r
338                                 msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString(),e);\r
339                 }\r
340                 return null;\r
341         }\r
342 \r
343         /**\r
344          * Invokes the getJsonRawValue() method with the wrap flag set to true\r
345          * and returns the String equivalent of the json node object returned.\r
346          *\r
347          * @param  jsonStr      String containing the JSON doc\r
348          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
349          * @return String field value associated with keys\r
350          */\r
351         public static String getJsonNodeValue(String jsonStr, String keys) {\r
352 //              String isDebugLogEnabled = "true";\r
353                 try {\r
354                                 Object rawValue = getJsonRawValue(jsonStr, keys, true);\r
355                                 if (rawValue == null) {\r
356                                         return null;\r
357                                 } else {\r
358                                         if (rawValue instanceof String) {\r
359                                                 msoLogger.debug("getJsonNodeValue(): the raw value is a String Object=" + ((String) rawValue).toString());\r
360                                                 return (String) rawValue;\r
361                                         } else {\r
362                                                 msoLogger.debug("getJsonNodeValue(): the raw value is NOT a String Object=" + rawValue.toString());\r
363                                                 return rawValue.toString();\r
364                                         }\r
365                                 }\r
366                 } catch (Exception e) {\r
367                                 msoLogger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field=" + keys + ". Exception was: " + e.toString(), e);\r
368                 }\r
369                 return null;\r
370         }\r
371 \r
372         /**\r
373          * Invokes the getJsonRawValue() method and returns the String equivalent of\r
374          * the object returned.\r
375          *\r
376          * TBD: May need separate methods for boolean, float, and integer fields if the\r
377          * String representation is not sufficient to meet client needs.\r
378          *\r
379          * @param  jsonStr      String containing the JSON doc\r
380          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
381          * @return String field value associated with keys\r
382          */\r
383         public static int getJsonIntValue(String jsonStr, String keys) {\r
384 //              String isDebugLogEnabled = "true";\r
385                 try {\r
386                                 Object rawValue = getJsonRawValue(jsonStr, keys);\r
387                                 if (rawValue == null) {\r
388                                         return 0;\r
389                                 } else {\r
390                                         if (rawValue instanceof Integer) {\r
391                                                 msoLogger.debug("getJsonValue(): the raw value is an Integer Object=" + ((String) rawValue).toString());\r
392                                                 return (Integer) rawValue;\r
393                                         } else {\r
394                                                 msoLogger.debug("getJsonValue(): the raw value is NOT an Integer Object=" + rawValue.toString());\r
395                                                 return 0;\r
396                                         }\r
397                                 }\r
398                 } catch (Exception e) {\r
399                                 msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString(), e);\r
400                 }\r
401                 return 0;\r
402         }\r
403 \r
404         /**\r
405          * Invokes the getJsonRawValue() method and returns the boolean equivalent of\r
406          * the object returned.\r
407          *\r
408          * @param  jsonStr      String containing the JSON doc\r
409          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
410          * @return boolean field value associated with keys - default is false\r
411          */\r
412         public static boolean getJsonBooleanValue(String jsonStr, String keys) {\r
413                 String isDebugLogEnabled = "true";\r
414                 try {\r
415                                 Object rawValue = getJsonRawValue(jsonStr, keys);\r
416                                 if (rawValue == null) {\r
417                                         return false;\r
418                                 } else {\r
419                                         if (rawValue instanceof Boolean) {\r
420                                                 msoLogger.debug("getJsonValue(): the raw value is a Boolean Object=" + ((String) rawValue).toString());\r
421                                                 return (Boolean) rawValue;\r
422                                         } else {\r
423                                                 msoLogger.debug("getJsonValue(): the raw value is NOT an Boolean Object=" + rawValue.toString());\r
424                                                 return false;\r
425                                         }\r
426                                 }\r
427                 } catch (Exception e) {\r
428                                 msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString(),e);\r
429                 }\r
430                 return false;\r
431         }\r
432 \r
433         /**\r
434          * Invokes the getJsonParamValue() method to obtain the JSONArray associated with\r
435          * the specified keys. The JSONArray is then walked to retrieve the first array\r
436          * value associated with the specified field name (index=0).\r
437          *\r
438          * @param  jsonStr      String containing the JSON doc\r
439          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
440          * @param  name         field name for the param to be retrieved\r
441          * @return String param value associated with field name\r
442          */\r
443         public static String getJsonParamValue(String jsonStr, String keys, String name) {\r
444                 return getJsonParamValue(jsonStr, keys, name, 0);\r
445         }\r
446 \r
447         /**\r
448          * Invokes the getJsonRawValue() method to obtain the JSONArray associated with\r
449          * the specified keys. The JSONArray is then walked to retrieve the nth array\r
450          * value associated with the specified field name and index.\r
451          *\r
452          * @param  jsonStr      String containing the JSON doc\r
453          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
454          * @param  name         field name for the param to be retrieved\r
455          * @param  index    the nth param associated with name starting at 0\r
456          * @return String param value associated with field name\r
457          */\r
458         public static String getJsonParamValue(String jsonStr, String keys, String name, int index) {\r
459 //              String isDebugLogEnabled = "true";\r
460                 try {\r
461                         Object rawValue = getJsonRawValue(jsonStr, keys);\r
462                         if (rawValue == null) {\r
463                                 return null;\r
464                         } else {\r
465                                 if (rawValue instanceof JSONArray) {\r
466                                         msoLogger.debug("getJsonParamValue(): keys=" + keys + " points to JSONArray: " + ((JSONArray) rawValue).toString());\r
467                                         int arrayLen = ((JSONArray) rawValue).length();\r
468                                         if (index < 0 || arrayLen < index+1) {\r
469                                                 msoLogger.debug("getJsonParamValue(): index: " + index + " is out of bounds for array size of " + arrayLen);\r
470                                                 return null;\r
471                                         }\r
472                                         int foundCnt = 0;\r
473                                         for (int i = 0; i < arrayLen; i++) {\r
474                                                 msoLogger.debug("getJsonParamValue(): index: " + i + ", value: " + ((JSONArray) rawValue).get(i).toString());\r
475                                                 if (((JSONArray) rawValue).get(i) instanceof JSONObject) {\r
476                                                         msoLogger.debug("getJsonParamValue(): index: " + i + " is a JSONObject");\r
477                                                         JSONObject jsonObj = (JSONObject)((JSONArray) rawValue).get(i);\r
478                                                         String parmValue = jsonObj.get(name).toString();\r
479                                                         if (parmValue != null) {\r
480                                                                 msoLogger.debug("getJsonParamValue(): found value: " + parmValue + " for name: " + name + " and index: " + i);\r
481                                                                 if (foundCnt == index) {\r
482                                                                         return parmValue;\r
483                                                                 } else {\r
484                                                                         foundCnt++;\r
485                                                                         continue;\r
486                                                                 }\r
487                                                         } else {\r
488                                                                 continue;\r
489                                                         }\r
490                                                 } else {\r
491                                                         msoLogger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject=" + rawValue.toString());\r
492                                                         return null;\r
493                                                 }\r
494                                         }\r
495                                         msoLogger.debug("getJsonParamValue(): content value NOT found for name: " + name);\r
496                                         return null;\r
497                                 } else {\r
498                                         msoLogger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object=" + rawValue.toString());\r
499                                         return null;\r
500                                 }\r
501                         }\r
502                 } catch (JSONException je) {\r
503                                 // JSONObject::get() throws this exception if one of the specified keys is not found\r
504                                 msoLogger.debug("getJsonParamValue(): caught JSONException attempting to retrieve param value for keys:" + keys + ", name=" + name, je);\r
505                 } catch (Exception e) {\r
506                                 msoLogger.debug("getJsonParamValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString(), e);\r
507                 }\r
508                 return null;\r
509         }\r
510 \r
511         /**\r
512          * Wrapper to generate the JSONObject to pass to the getJsonValueForKey(JSONObject, String)\r
513          * method so that recursion over the subobjects can be supported there\r
514          *\r
515          * @param  jsonStr      String containing the JSON doc\r
516          * @param  key          key to the target value\r
517          * @return String field value associated with key\r
518          */\r
519         public static String getJsonValueForKey(String jsonStr, String key) {\r
520 //              String isDebugLogEnabled = "true";\r
521                 try {\r
522                         JSONObject jsonObj = new JSONObject(jsonStr);\r
523                         if (jsonObj != null) {\r
524                                 return getJsonValueForKey(jsonObj, key);\r
525                         }\r
526                 } catch (Exception e) {\r
527                                 msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString(), e);\r
528                 }\r
529                 return null;\r
530         }\r
531 \r
532         /**\r
533          * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the\r
534          * single key/field name specified. Returns the associated value if found or null if the key is not found\r
535          *\r
536          * @param  jsonObj      JSONObject representation of the the JSON doc\r
537          * @param  key          key to the target value\r
538          * @return String field value associated with key\r
539          */\r
540         public static String getJsonValueForKey(JSONObject jsonObj, String key) {\r
541 //              String isDebugLogEnabled = "true";\r
542                 String keyValue = null;\r
543                 try {\r
544                         if (jsonObj.has(key)) {\r
545                                 msoLogger.debug("getJsonValueForKey(): found value for key=" + key);\r
546                                 Object value = jsonObj.get(key);\r
547                                 if (value == null)\r
548                                         return null;\r
549                                 else\r
550                                         return ((String) value);\r
551                         } else {\r
552                                 msoLogger.debug("getJsonValueForKey(): iterating over the keys");\r
553                                 Iterator <String> itr = jsonObj.keys();\r
554                                 while (itr.hasNext()) {\r
555                                         String nextKey = (String) itr.next();\r
556                                         Object obj = jsonObj.get(nextKey);\r
557                                         if (obj instanceof JSONObject) {\r
558                                                 msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");\r
559                                                 keyValue = getJsonValueForKey((JSONObject) obj, key);\r
560                                                 if (keyValue != null) {\r
561                                                         msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key);\r
562                                                         break;\r
563                                                 }\r
564                                         } else {\r
565                                                 msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");\r
566                                         }\r
567                                 }\r
568                         }\r
569                 } catch (JSONException je) {\r
570                                 // JSONObject::get() throws this exception if one of the specified keys is not found\r
571                                 msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key, je);\r
572                                 keyValue = null;\r
573                 } catch (Exception e) {\r
574                                 msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString(), e);\r
575                 }\r
576                 return keyValue;\r
577         }\r
578 \r
579         /**\r
580          * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the\r
581          * single key/field name specified. Returns the associated value if found or null if the key is not found\r
582          *\r
583          * @param  jsonObj      JSONObject representation of the the JSON doc\r
584          * @param  key          key to the target value\r
585          * @return String field value associated with key\r
586          */\r
587         public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) {\r
588 //              String isDebugLogEnabled = "true";\r
589                 Integer keyValue = 0;\r
590                 try {\r
591                         if (jsonObj.has(key)) {\r
592                                 msoLogger.debug("getJsonValueForKey(): found value for key=" + key);\r
593                                 return ((Integer) jsonObj.get(key));\r
594                         } else {\r
595                                 msoLogger.debug("getJsonValueForKey(): iterating over the keys");\r
596                                 Iterator <String> itr = jsonObj.keys();\r
597                                 while (itr.hasNext()) {\r
598                                         String nextKey = (String) itr.next();\r
599                                         Object obj = jsonObj.get(nextKey);\r
600                                         if (obj instanceof JSONObject) {\r
601                                                 msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");\r
602                                                 keyValue = getJsonIntValueForKey((JSONObject) obj, key);\r
603                                                 if (keyValue != null) {\r
604                                                         msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key);\r
605                                                         break;\r
606                                                 }\r
607                                         } else {\r
608                                                 msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");\r
609                                         }\r
610                                 }\r
611                         }\r
612                 } catch (JSONException je) {\r
613                                 // JSONObject::get() throws this exception if one of the specified keys is not found\r
614                                 msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key, je);\r
615                                 keyValue = null;\r
616                 } catch (Exception e) {\r
617                                 msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString(),e);\r
618                 }\r
619                 return keyValue;\r
620         }\r
621 \r
622         /**\r
623          * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the\r
624          * single key/field name specified. Returns the associated value if found or null if the key is not found\r
625          *\r
626          * @param  jsonObj      JSONObject representation of the the JSON doc\r
627          * @param  key          key to the target value\r
628          * @return String field value associated with key\r
629          */\r
630         public static Boolean getJsonBooleanValueForKey(JSONObject jsonObj, String key) {\r
631                 String isDebugLogEnabled = "true";\r
632                 Boolean keyValue = false;\r
633                 try {\r
634                         if (jsonObj.has(key)) {\r
635                                 msoLogger.debug("getJsonBooleanValueForKey(): found value for key=" + key);\r
636                                 return ((Boolean) jsonObj.get(key));\r
637                         } else {\r
638                                 msoLogger.debug("getJsonBooleanValueForKey(): iterating over the keys");\r
639                                 Iterator <String> itr = jsonObj.keys();\r
640                                 while (itr.hasNext()) {\r
641                                         String nextKey = (String) itr.next();\r
642                                         Object obj = jsonObj.get(nextKey);\r
643                                         if (obj instanceof JSONObject) {\r
644                                                 msoLogger.debug("getJsonBooleanValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");\r
645                                                 keyValue = getJsonBooleanValueForKey((JSONObject) obj, key);\r
646                                                 if (keyValue != null) {\r
647                                                         msoLogger.debug("getJsonBooleanValueForKey(): found value=" + keyValue + ", for key=" + key);\r
648                                                         break;\r
649                                                 }\r
650                                         } else {\r
651                                                 msoLogger.debug("getJsonBooleanValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");\r
652                                         }\r
653                                 }\r
654                         }\r
655                 } catch (JSONException je) {\r
656                                 // JSONObject::get() throws this exception if one of the specified keys is not found\r
657                                 msoLogger.debug("getJsonBooleanValueForKey(): caught JSONException attempting to retrieve value for key=" + key,je);\r
658                                 keyValue = null;\r
659                 } catch (Exception e) {\r
660                                 msoLogger.debug("getJsonBooleanValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString(),e);\r
661                 }\r
662                 return keyValue;\r
663         }\r
664 \r
665         /**\r
666          * Boolean method to determine if a key path is valid for the JSON doc. Invokes\r
667          * getJsonValue().\r
668          *\r
669          * @param  jsonStr      String containing the JSON doc\r
670          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
671          * @return Boolean true if keys points to value in the JSON doc\r
672          */\r
673         public static Boolean jsonValueExists(String jsonStr, String keys) {\r
674                 if (getJsonRawValue(jsonStr, keys) == null) {\r
675                         return false;\r
676                 } else {\r
677                         return true;\r
678                 }\r
679         }\r
680 \r
681         /**\r
682          * Inserts the new key/value pair at the appropriate location in the JSON\r
683          * document after first determining if keyed field already exists. If\r
684          * it does exist, return the JSON unmodified, otherwise return the new JSON\r
685          * Note: this method currently only supports String value inserts.\r
686          *\r
687          * @param  jsonStr      String containing the JSON doc\r
688          * @param  keys         full key path to the value to be added in the format of "key1.key2.key3..."\r
689          * @return String containing the updated JSON doc\r
690          */\r
691         public static String addJsonValue(String jsonStr, String keys, String value) {\r
692 //              String isDebugLogEnabled = "true";\r
693                 // only attempt to insert the key/value pair if it does not exist\r
694                 if (!jsonValueExists(jsonStr, keys)) {\r
695                         return putJsonValue(jsonStr, keys, value);\r
696                 } else {\r
697                         msoLogger.debug("addJsonValue(): JSON add failed, key=" + keys + "/value=" + (String) value + " already exists");\r
698                         return jsonStr;\r
699                 }\r
700         }\r
701 \r
702         /**\r
703          * Updates the value for the specified key in the JSON document\r
704          * after first determining if keyed field exists. If it does\r
705          * not exist, return the JSON unmodified, otherwise return the updated JSON.\r
706          * Note: this method currently only supports String value updates.\r
707          *\r
708          * @param  jsonStr      String containing the JSON doc\r
709          * @param  keys         full key path to the value to be updated in the format of "key1.key2.key3..."\r
710          * @return String containing the updated JSON doc\r
711          */\r
712         public static String updJsonValue(String jsonStr, String keys, String newValue) {\r
713 //              String isDebugLogEnabled = "true";\r
714                 // only attempt to modify the key/value pair if it exists\r
715                 if (jsonValueExists(jsonStr, keys)) {\r
716                         return putJsonValue(jsonStr, keys, newValue);\r
717                 } else {\r
718                         msoLogger.debug("updJsonValue(): JSON update failed, no value exists for key=" + keys);\r
719                         return jsonStr;\r
720                 }\r
721         }\r
722 \r
723         /**\r
724          * Deletes the value for the specified key in the JSON document\r
725          * after first determining if keyed field exists. If it does\r
726          * not exist, return the JSON unmodified, otherwise return the updated JSON\r
727          *\r
728          * @param  jsonStr      String containing the JSON doc\r
729          * @param  keys         full key path to the value to be deleted in the format of "key1.key2.key3..."\r
730          * @return String containing the updated JSON doc\r
731          */\r
732         public static String delJsonValue(String jsonStr, String keys) {\r
733 //              String isDebugLogEnabled = "true";\r
734                 // only attempt to remove the key/value pair if it exists\r
735                 if (jsonValueExists(jsonStr, keys)) {\r
736                         // passing a null value results in a delete\r
737                         return putJsonValue(jsonStr, keys, null);\r
738                 } else {\r
739                         msoLogger.debug("delJsonValue(): JSON delete failed, no value exists for key=" + keys);\r
740                         return jsonStr;\r
741                 }\r
742         }\r
743 \r
744         /**\r
745          * Walks the JSON doc using the full key path to retrieve the associated\r
746          * value. All but the last key points to the 'parent' object name(s) in order\r
747          * in the JSON hierarchy with the last key pointing to the target value.\r
748          * The value returned is a Java object.\r
749          *\r
750          * @param  jsonStr      String containing the JSON doc\r
751          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
752          * @return Object field value associated with keys\r
753          */\r
754         private static Object getJsonRawValue(String jsonStr, String keys) {\r
755                 return getJsonRawValue(jsonStr, keys, false);\r
756         }\r
757 \r
758         /**\r
759          * Walks the JSON doc using the full key path to retrieve the associated\r
760          * value. All but the last key points to the 'parent' object name(s) in order\r
761          * in the JSON hierarchy with the last key pointing to the target value.\r
762          * The value returned is a Java object.\r
763          *\r
764          * @param  jsonStr      String containing the JSON doc\r
765          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
766          * @param  wrap         Boolean which determines if returned JSONObjects sould be "wrapped"\r
767          *                  Note: wrap does not apply to returned scalar values\r
768          * @return Object field value associated with keys\r
769          */\r
770         private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) {\r
771 //              String isDebugLogEnabled = "true";\r
772                 String keyStr = "";\r
773                 try {\r
774                         JSONObject jsonObj = new JSONObject(jsonStr);\r
775                         StringTokenizer keyTokens = new StringTokenizer(keys, ".");\r
776                         while (keyTokens.hasMoreElements()) {\r
777                                 keyStr = keyTokens.nextToken();\r
778                                 Object keyValue = jsonObj.get(keyStr);\r
779                                 if (keyValue instanceof JSONObject) {\r
780                                         msoLogger.debug("getJsonRawValue(): key=" + keyStr + " points to json object");\r
781                                         jsonObj = (JSONObject) keyValue;\r
782                                 } else {\r
783                                         if (keyTokens.hasMoreElements()) {\r
784                                                 msoLogger.debug("getJsonRawValue(): value found prior to last key for key=" + keyStr);\r
785                                         }\r
786                                         return keyValue;\r
787                                 }\r
788                         }\r
789                         // return the json 'node' that the key points to\r
790                         // note: since this is a json object and not a scalar value,\r
791                         //       use the wrap flag to determine if the object should\r
792                         //       be wrapped with a root node value\r
793                         //       (the last key in the keys String)\r
794                         if (wrap) {\r
795                                 JSONObject wrappedJsonObj = new JSONObject();\r
796                                 wrappedJsonObj.put(keyStr, jsonObj);\r
797                                 return wrappedJsonObj.toString();\r
798                         } else {\r
799                                 return jsonObj.toString();\r
800                         }\r
801 \r
802                 } catch (JSONException je) {\r
803                                 // JSONObject::get() throws this exception if one of the specified keys is not found\r
804                                 msoLogger.debug("getJsonRawValue(): caught JSONException attempting to retrieve raw value for key=" + keyStr,je);\r
805                 } catch (Exception e) {\r
806                                 msoLogger.debug("getJsonRawValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString(),e);\r
807                 }\r
808                 return null;\r
809         }\r
810 \r
811         /**\r
812          * Private method invoked by the public add, update, and delete methods.\r
813          *\r
814          * @param  jsonStr      String containing the JSON doc\r
815          * @param  keys         full key path to the value to be deleted in the format of "key1.key2.key3..."\r
816          * @return String containing the updated JSON doc\r
817          */\r
818         private static String putJsonValue(String jsonStr, String keys, String value) {\r
819 //              String isDebugLogEnabled = "true";\r
820                 String keyStr = "";\r
821                 try {\r
822                         JSONObject jsonObj = new JSONObject(jsonStr);\r
823                         JSONObject jsonObjOut = jsonObj;\r
824                         StringTokenizer keyTokens = new StringTokenizer(keys, ".");\r
825                         while (keyTokens.hasMoreElements()) {\r
826                                 keyStr = keyTokens.nextToken();\r
827                                 if (keyTokens.hasMoreElements()) {\r
828                                         Object keyValue = jsonObj.get(keyStr);\r
829                                         if (keyValue instanceof JSONObject) {\r
830                                                 msoLogger.debug("putJsonValue(): key=" + keyStr + " points to json object");\r
831                                                 jsonObj = (JSONObject) keyValue;\r
832                                         } else {\r
833                                                 msoLogger.debug("putJsonValue(): key=" + keyStr + " not the last key but points to non-json object: " + (String) keyValue);\r
834                                                 return null;\r
835                                         }\r
836                                 } else { // at the last/new key value\r
837                                         jsonObj.put(keyStr, value);\r
838                                         return jsonObjOut.toString(3);\r
839                                 }\r
840                         }\r
841                         // should not hit this point if the key points to a valid key value\r
842                         return null;\r
843 \r
844                 } catch (JSONException je) {\r
845                                 // JSONObject::get() throws this exception if one of the specified keys is not found\r
846                                 msoLogger.debug("putJsonValue(): caught JSONException attempting to retrieve value for key=" + keyStr,je);\r
847                                 return null;\r
848                 } catch (Exception e) {\r
849                                 msoLogger.debug("putJsonValue(): unable to parse json to put value for key=" + keys + ". Exception was: " + e.toString(),e);\r
850                 }\r
851                 return null;\r
852         }\r
853 \r
854         /**\r
855          * This json util method converts a json array of Key Value\r
856          * pair objects into a Java Map.\r
857          *\r
858          * @param execution\r
859          * @param entryArray - the getJsonValue of a json Array of key/value pairs\r
860          *\r
861          * @return Map - a Map containing the entries\r
862          */\r
863         public Map<String, String> entryArrayToMap(Execution execution, String entryArray) {\r
864                 msoLogger.debug("Started Entry Array To Map Util Method");\r
865 \r
866                 Map<String, String> map = new HashMap<String, String>();\r
867 \r
868                 //Populate Map\r
869                 String entryListJson = "{ \"entry\":" + entryArray + "}";\r
870                 JSONObject obj = new JSONObject(entryListJson);\r
871                 JSONArray arr = obj.getJSONArray("entry");\r
872                 for (int i = 0; i < arr.length(); i++){\r
873                         JSONObject jo = arr.getJSONObject(i);\r
874                         String key = jo.getString("key");\r
875                         String value =jo.getString("value");\r
876                         map.put(key, value);\r
877                 }\r
878                 msoLogger.debug("Outgoing Map is: " + map);\r
879                 msoLogger.debug("Completed Entry Array To Map Util Method");\r
880                 return map;\r
881         }\r
882 \r
883         /**\r
884          * This json util method converts a json array of Key Value\r
885          * pair objects into a Java Map.\r
886          *\r
887          * @param execution\r
888          * @param entryArray - the getJsonValue of a json Array of key/value pairs\r
889          * @param keyNode - the name of the node that represents the key\r
890          * @param valueNode - the name of the node that represents the value\r
891          *\r
892          * @return Map - a Map containing the entries\r
893          *\r
894          */\r
895         public Map<String, String> entryArrayToMap(Execution execution, String entryArray, String keyNode, String valueNode) {\r
896                 msoLogger.debug("Started Entry Array To Map Util Method");\r
897 \r
898                 Map<String, String> map = new HashMap<String, String>();\r
899                 //Populate Map\r
900                 String entryListJson = "{ \"entry\":" + entryArray + "}";\r
901                 JSONObject obj = new JSONObject(entryListJson);\r
902                 JSONArray arr = obj.getJSONArray("entry");\r
903                 for (int i = 0; i < arr.length(); i++){\r
904                         JSONObject jo = arr.getJSONObject(i);\r
905                         String key = jo.getString(keyNode);\r
906                         String value =jo.getString(valueNode);\r
907                         map.put(key, value);\r
908                 }\r
909                 msoLogger.debug("Outgoing Map is: " + map);\r
910                 msoLogger.debug("Completed Entry Array To Map Util Method");\r
911                 return map;\r
912         }\r
913 \r
914         /**\r
915          * This json util method converts a json Array of Strings\r
916          * to a Java List. It takes each String in the json Array\r
917          * and puts it in a Java List<String>.\r
918          *\r
919          * @param execution\r
920          * @param stringArray - the getJsonValue of a json array of strings\r
921          *\r
922          * @return List - a java list containing the strings\r
923          *\r
924          *\r
925          */\r
926         public List<String> StringArrayToList(Execution execution, String jsonArrayOfStrings) {\r
927                 msoLogger.debug("Started  String Array To List Util Method");\r
928 \r
929                 List<String> list = new ArrayList<String>();\r
930                 //Populate List\r
931                 String stringListJson = "{ \"strings\":" + jsonArrayOfStrings + "}";\r
932                 JSONObject obj = new JSONObject(stringListJson);\r
933                 JSONArray arr = obj.getJSONArray("strings");\r
934                 for (int i = 0; i < arr.length(); i++){\r
935                         String s = arr.getString(i);\r
936                         list.add(s);\r
937                 }\r
938                 msoLogger.debug("Outgoing List is: " + list);\r
939                 msoLogger.debug("Completed String Array To List Util Method");\r
940                 return list;\r
941         }\r
942 \r
943         /**\r
944          *\r
945          * Invokes the getJsonRawValue() method to determine if the\r
946          * json element/variable exist. Returns true if the\r
947          * json element exist\r
948          *\r
949          * @param  jsonStr      String containing the JSON doc\r
950          * @param  keys         full key path to the target value in the format of "key1.key2.key3..."\r
951          * @return boolean field value associated with keys\r
952          *\r
953          *\r
954          */\r
955         public static boolean jsonElementExist(String jsonStr, String keys) {\r
956 \r
957                 try {\r
958                         Object rawValue = getJsonRawValue(jsonStr, keys);\r
959                         if (rawValue == null) {\r
960                                 return false;\r
961                         } else {\r
962                                 return true;\r
963                         }\r
964                 } catch (Exception e) {\r
965                                 msoLogger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: " + e.toString(),e);\r
966                 }\r
967                 return true;\r
968         }\r
969 \r
970 }