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