2 * ============LICENSE_START=======================================================
\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
12 * http://www.apache.org/licenses/LICENSE-2.0
\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
22 package org.openecomp.mso.bpmn.core.json;
\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
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
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
42 * Utility class for JSON processing
\r
47 public class JsonUtils {
\r
49 private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
\r
50 private static int MSOJsonIndentFactor = 3;
\r
53 * Uses the JSONObject static method to convert a XML doc to JSON.
\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
59 public static String xml2json(String xml, Boolean pretty) {
\r
60 // String isDebugLogEnabled = "true";
\r
62 // name spaces cause problems, so just remove them
\r
63 JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml));
\r
65 return jsonObj.toString();
\r
67 // add an indent to make it 'pretty'
\r
68 return jsonObj.toString(MSOJsonIndentFactor);
\r
70 } catch (Exception e){
\r
71 msoLogger.debug("xml2json(): unable to parse xml and convert to json. Exception was: " + e.toString(), e);
\r
77 * Invokes xml2json(String, Boolean) defaulting to 'pretty' output.
\r
79 * @param xml String containing the XML doc
\r
80 * @return String containing the JSON translation
\r
82 public static String xml2json(String xml) {
\r
83 return xml2json(xml, true);
\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
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
96 public static String json2xml(String jsonStr, Boolean pretty) {
\r
97 // String isDebugLogEnabled = "true";
\r
99 JSONObject jsonObj = new JSONObject(jsonStr);
\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
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
109 } catch (Exception e){
\r
110 msoLogger.debug("json2xml(): unable to parse json and convert to xml. Exception was: " + e.toString(), e);
\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
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
124 public static String toXMLString(Object obj, String tagName) throws JSONException {
\r
125 StringBuffer strBuf = new StringBuffer();
\r
128 JSONObject jsonObj;
\r
130 Iterator<String> keys;
\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
143 // iterate thru the keys.
\r
144 jsonObj = (JSONObject) obj;
\r
145 keys = jsonObj.keys();
\r
146 while (keys.hasNext()) {
\r
148 // msoLogger.debug("toXMLString(): key is " + k);
\r
149 curObj = jsonObj.opt(key);
\r
150 if (curObj == null) {
\r
153 if (curObj instanceof String) {
\r
154 str = (String) curObj;
\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
165 strBuf.append('\n');
\r
167 strBuf.append(XML.escape(jsonArr.get(i).toString()));
\r
170 strBuf.append(XML.escape(curObj.toString()));
\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
190 // msoLogger.debug("toXMLString(): recursive call toXML() with tagName null");
\r
191 // append the opening tag for the array (before 1st element)
\r
193 strBuf.append("<");
\r
194 strBuf.append(key);
\r
195 strBuf.append(">");
\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
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
213 // msoLogger.debug("toXMLString(): recursive call toXMLString() with tagName: " + key);
\r
214 strBuf.append(toXMLString(curObj, key));
\r
216 // msoLogger.debug("toXML(): partial XML: " + strBuf.toString());
\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
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
236 return strBuf.toString();
\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
247 * Invokes json2xml(String, Boolean) defaulting to 'pretty' output.
\r
249 * @param jsonStr String containing the XML doc
\r
250 * @return String containing the JSON translation
\r
252 public static String json2xml(String jsonStr) {
\r
253 return json2xml(jsonStr, true);
\r
257 * Formats the JSON String using the value of MSOJsonIndentFactor.
\r
259 * @param jsonStr String containing the JSON doc
\r
260 * @return String containing the formatted JSON doc
\r
262 public static String prettyJson(String jsonStr) {
\r
263 // String isDebugLogEnabled = "true";
\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
274 * Returns an Iterator over the JSON keys in the specified JSON doc.
\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
280 public static Iterator <String> getJsonIterator(String jsonStr) throws JSONException {
\r
281 return new JSONObject(jsonStr).keys();
\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
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
295 public static String getJsonRootProperty(String jsonStr) throws JSONException {
\r
296 Iterator<String> iter = getJsonIterator(jsonStr);
\r
298 if (!iter.hasNext()) {
\r
299 throw new JSONException("Empty JSON object");
\r
302 String rootPropertyName = iter.next();
\r
304 if (iter.hasNext()) {
\r
305 throw new JSONException("JSON object has more than one root property");
\r
308 return rootPropertyName;
\r
312 * Invokes the getJsonRawValue() method and returns the String equivalent of
\r
313 * the object returned.
\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
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
322 public static String getJsonValue(String jsonStr, String keys) {
\r
323 // String isDebugLogEnabled = "true";
\r
325 Object rawValue = getJsonRawValue(jsonStr, keys);
\r
326 if (rawValue == null) {
\r
329 if (rawValue instanceof String) {
\r
330 msoLogger.debug("getJsonValue(): the raw value is a String Object=" + ((String) rawValue));
\r
331 return (String) rawValue;
\r
333 msoLogger.debug("getJsonValue(): the raw value is NOT a String Object=" + rawValue.toString());
\r
334 return rawValue.toString();
\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
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
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
351 public static String getJsonNodeValue(String jsonStr, String keys) {
\r
352 // String isDebugLogEnabled = "true";
\r
354 Object rawValue = getJsonRawValue(jsonStr, keys, true);
\r
355 if (rawValue == null) {
\r
358 if (rawValue instanceof String) {
\r
359 msoLogger.debug("getJsonNodeValue(): the raw value is a String Object=" + ((String) rawValue));
\r
360 return (String) rawValue;
\r
362 msoLogger.debug("getJsonNodeValue(): the raw value is NOT a String Object=" + rawValue.toString());
\r
363 return rawValue.toString();
\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
373 * Invokes the getJsonRawValue() method and returns the String equivalent of
\r
374 * the object returned.
\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
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
383 public static int getJsonIntValue(String jsonStr, String keys) {
\r
384 // String isDebugLogEnabled = "true";
\r
386 Object rawValue = getJsonRawValue(jsonStr, keys);
\r
387 if (rawValue == null) {
\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
394 msoLogger.debug("getJsonValue(): the raw value is NOT an Integer Object=" + rawValue.toString());
\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
405 * Invokes the getJsonRawValue() method and returns the boolean equivalent of
\r
406 * the object returned.
\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
412 public static boolean getJsonBooleanValue(String jsonStr, String keys) {
\r
414 Object rawValue = getJsonRawValue(jsonStr, keys);
\r
415 if (rawValue == null) {
\r
418 if (rawValue instanceof Boolean) {
\r
419 msoLogger.debug("getJsonValue(): the raw value is a Boolean Object=" + ((String) rawValue));
\r
420 return (Boolean) rawValue;
\r
422 msoLogger.debug("getJsonValue(): the raw value is NOT an Boolean Object=" + rawValue.toString());
\r
426 } catch (Exception e) {
\r
427 msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString(),e);
\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
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
442 public static String getJsonParamValue(String jsonStr, String keys, String name) {
\r
443 return getJsonParamValue(jsonStr, keys, name, 0);
\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
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
457 public static String getJsonParamValue(String jsonStr, String keys, String name, int index) {
\r
458 // String isDebugLogEnabled = "true";
\r
460 Object rawValue = getJsonRawValue(jsonStr, keys);
\r
461 if (rawValue == null) {
\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
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
490 msoLogger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject=" + rawValue.toString());
\r
494 msoLogger.debug("getJsonParamValue(): content value NOT found for name: " + name);
\r
497 msoLogger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object=" + rawValue.toString());
\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, je);
\r
504 } catch (Exception e) {
\r
505 msoLogger.debug("getJsonParamValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString(), e);
\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
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
518 public static String getJsonValueForKey(String jsonStr, String key) {
\r
519 // String isDebugLogEnabled = "true";
\r
521 JSONObject jsonObj = new JSONObject(jsonStr);
\r
522 return getJsonValueForKey(jsonObj, key);
\r
523 } catch (Exception e) {
\r
524 msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString(), e);
\r
530 * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the
\r
531 * single key/field name specified. Returns the associated value if found or null if the key is not found
\r
533 * @param jsonObj JSONObject representation of the the JSON doc
\r
534 * @param key key to the target value
\r
535 * @return String field value associated with key
\r
537 public static String getJsonValueForKey(JSONObject jsonObj, String key) {
\r
538 // String isDebugLogEnabled = "true";
\r
539 String keyValue = null;
\r
541 if (jsonObj.has(key)) {
\r
542 msoLogger.debug("getJsonValueForKey(): found value for key=" + key);
\r
543 Object value = jsonObj.get(key);
\r
547 return ((String) value);
\r
549 msoLogger.debug("getJsonValueForKey(): iterating over the keys");
\r
550 Iterator <String> itr = jsonObj.keys();
\r
551 while (itr.hasNext()) {
\r
552 String nextKey = (String) itr.next();
\r
553 Object obj = jsonObj.get(nextKey);
\r
554 if (obj instanceof JSONObject) {
\r
555 msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");
\r
556 keyValue = getJsonValueForKey((JSONObject) obj, key);
\r
557 if (keyValue != null) {
\r
558 msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key);
\r
562 msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");
\r
566 } catch (JSONException je) {
\r
567 // JSONObject::get() throws this exception if one of the specified keys is not found
\r
568 msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key, je);
\r
570 } catch (Exception e) {
\r
571 msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString(), e);
\r
577 * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the
\r
578 * single key/field name specified. Returns the associated value if found or null if the key is not found
\r
580 * @param jsonObj JSONObject representation of the the JSON doc
\r
581 * @param key key to the target value
\r
582 * @return String field value associated with key
\r
584 public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) {
\r
585 // String isDebugLogEnabled = "true";
\r
586 Integer keyValue = 0;
\r
588 if (jsonObj.has(key)) {
\r
589 msoLogger.debug("getJsonValueForKey(): found value for key=" + key);
\r
590 return (Integer) jsonObj.get(key);
\r
592 msoLogger.debug("getJsonValueForKey(): iterating over the keys");
\r
593 Iterator <String> itr = jsonObj.keys();
\r
594 while (itr.hasNext()) {
\r
595 String nextKey = (String) itr.next();
\r
596 Object obj = jsonObj.get(nextKey);
\r
597 if (obj instanceof JSONObject) {
\r
598 msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");
\r
599 keyValue = getJsonIntValueForKey((JSONObject) obj, key);
\r
600 if (keyValue != null) {
\r
601 msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key);
\r
605 msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");
\r
609 } catch (JSONException je) {
\r
610 // JSONObject::get() throws this exception if one of the specified keys is not found
\r
611 msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key, je);
\r
613 } catch (Exception e) {
\r
614 msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString(),e);
\r
620 * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the
\r
621 * single key/field name specified. Returns the associated value if found or null if the key is not found
\r
623 * @param jsonObj JSONObject representation of the the JSON doc
\r
624 * @param key key to the target value
\r
625 * @return String field value associated with key
\r
627 public static Boolean getJsonBooleanValueForKey(JSONObject jsonObj, String key) {
\r
628 Boolean keyValue = false;
\r
630 if (jsonObj.has(key)) {
\r
631 msoLogger.debug("getJsonBooleanValueForKey(): found value for key=" + key);
\r
632 return (Boolean) jsonObj.get(key);
\r
634 msoLogger.debug("getJsonBooleanValueForKey(): iterating over the keys");
\r
635 Iterator <String> itr = jsonObj.keys();
\r
636 while (itr.hasNext()) {
\r
637 String nextKey = (String) itr.next();
\r
638 Object obj = jsonObj.get(nextKey);
\r
639 if (obj instanceof JSONObject) {
\r
640 msoLogger.debug("getJsonBooleanValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");
\r
641 keyValue = getJsonBooleanValueForKey((JSONObject) obj, key);
\r
642 if (keyValue != null) {
\r
643 msoLogger.debug("getJsonBooleanValueForKey(): found value=" + keyValue + ", for key=" + key);
\r
647 msoLogger.debug("getJsonBooleanValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");
\r
651 } catch (JSONException je) {
\r
652 // JSONObject::get() throws this exception if one of the specified keys is not found
\r
653 msoLogger.debug("getJsonBooleanValueForKey(): caught JSONException attempting to retrieve value for key=" + key,je);
\r
655 } catch (Exception e) {
\r
656 msoLogger.debug("getJsonBooleanValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString(),e);
\r
662 * Boolean method to determine if a key path is valid for the JSON doc. Invokes
\r
665 * @param jsonStr String containing the JSON doc
\r
666 * @param keys full key path to the target value in the format of "key1.key2.key3..."
\r
667 * @return Boolean true if keys points to value in the JSON doc
\r
669 public static Boolean jsonValueExists(String jsonStr, String keys) {
\r
670 if (getJsonRawValue(jsonStr, keys) == null) {
\r
678 * Inserts the new key/value pair at the appropriate location in the JSON
\r
679 * document after first determining if keyed field already exists. If
\r
680 * it does exist, return the JSON unmodified, otherwise return the new JSON
\r
681 * Note: this method currently only supports String value inserts.
\r
683 * @param jsonStr String containing the JSON doc
\r
684 * @param keys full key path to the value to be added in the format of "key1.key2.key3..."
\r
685 * @return String containing the updated JSON doc
\r
687 public static String addJsonValue(String jsonStr, String keys, String value) {
\r
688 // String isDebugLogEnabled = "true";
\r
689 // only attempt to insert the key/value pair if it does not exist
\r
690 if (!jsonValueExists(jsonStr, keys)) {
\r
691 return putJsonValue(jsonStr, keys, value);
\r
693 msoLogger.debug("addJsonValue(): JSON add failed, key=" + keys + "/value=" + (String) value + " already exists");
\r
699 * Updates the value for the specified key in the JSON document
\r
700 * after first determining if keyed field exists. If it does
\r
701 * not exist, return the JSON unmodified, otherwise return the updated JSON.
\r
702 * Note: this method currently only supports String value updates.
\r
704 * @param jsonStr String containing the JSON doc
\r
705 * @param keys full key path to the value to be updated in the format of "key1.key2.key3..."
\r
706 * @return String containing the updated JSON doc
\r
708 public static String updJsonValue(String jsonStr, String keys, String newValue) {
\r
709 // String isDebugLogEnabled = "true";
\r
710 // only attempt to modify the key/value pair if it exists
\r
711 if (jsonValueExists(jsonStr, keys)) {
\r
712 return putJsonValue(jsonStr, keys, newValue);
\r
714 msoLogger.debug("updJsonValue(): JSON update failed, no value exists for key=" + keys);
\r
720 * Deletes the value for the specified key in the JSON document
\r
721 * after first determining if keyed field exists. If it does
\r
722 * not exist, return the JSON unmodified, otherwise return the updated JSON
\r
724 * @param jsonStr String containing the JSON doc
\r
725 * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."
\r
726 * @return String containing the updated JSON doc
\r
728 public static String delJsonValue(String jsonStr, String keys) {
\r
729 // String isDebugLogEnabled = "true";
\r
730 // only attempt to remove the key/value pair if it exists
\r
731 if (jsonValueExists(jsonStr, keys)) {
\r
732 // passing a null value results in a delete
\r
733 return putJsonValue(jsonStr, keys, null);
\r
735 msoLogger.debug("delJsonValue(): JSON delete failed, no value exists for key=" + keys);
\r
741 * Walks the JSON doc using the full key path to retrieve the associated
\r
742 * value. All but the last key points to the 'parent' object name(s) in order
\r
743 * in the JSON hierarchy with the last key pointing to the target value.
\r
744 * The value returned is a Java object.
\r
746 * @param jsonStr String containing the JSON doc
\r
747 * @param keys full key path to the target value in the format of "key1.key2.key3..."
\r
748 * @return Object field value associated with keys
\r
750 private static Object getJsonRawValue(String jsonStr, String keys) {
\r
751 return getJsonRawValue(jsonStr, keys, false);
\r
755 * Walks the JSON doc using the full key path to retrieve the associated
\r
756 * value. All but the last key points to the 'parent' object name(s) in order
\r
757 * in the JSON hierarchy with the last key pointing to the target value.
\r
758 * The value returned is a Java object.
\r
760 * @param jsonStr String containing the JSON doc
\r
761 * @param keys full key path to the target value in the format of "key1.key2.key3..."
\r
762 * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped"
\r
763 * Note: wrap does not apply to returned scalar values
\r
764 * @return Object field value associated with keys
\r
766 private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) {
\r
767 // String isDebugLogEnabled = "true";
\r
768 String keyStr = "";
\r
770 JSONObject jsonObj = new JSONObject(jsonStr);
\r
771 StringTokenizer keyTokens = new StringTokenizer(keys, ".");
\r
772 while (keyTokens.hasMoreElements()) {
\r
773 keyStr = keyTokens.nextToken();
\r
774 Object keyValue = jsonObj.get(keyStr);
\r
775 if (keyValue instanceof JSONObject) {
\r
776 msoLogger.debug("getJsonRawValue(): key=" + keyStr + " points to json object");
\r
777 jsonObj = (JSONObject) keyValue;
\r
779 if (keyTokens.hasMoreElements()) {
\r
780 msoLogger.debug("getJsonRawValue(): value found prior to last key for key=" + keyStr);
\r
785 // return the json 'node' that the key points to
\r
786 // note: since this is a json object and not a scalar value,
\r
787 // use the wrap flag to determine if the object should
\r
788 // be wrapped with a root node value
\r
789 // (the last key in the keys String)
\r
791 JSONObject wrappedJsonObj = new JSONObject();
\r
792 wrappedJsonObj.put(keyStr, jsonObj);
\r
793 return wrappedJsonObj.toString();
\r
795 return jsonObj.toString();
\r
798 } catch (JSONException je) {
\r
799 // JSONObject::get() throws this exception if one of the specified keys is not found
\r
800 msoLogger.debug("getJsonRawValue(): caught JSONException attempting to retrieve raw value for key=" + keyStr,je);
\r
801 } catch (Exception e) {
\r
802 msoLogger.debug("getJsonRawValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString(),e);
\r
808 * Private method invoked by the public add, update, and delete methods.
\r
810 * @param jsonStr String containing the JSON doc
\r
811 * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."
\r
812 * @return String containing the updated JSON doc
\r
814 private static String putJsonValue(String jsonStr, String keys, String value) {
\r
815 // String isDebugLogEnabled = "true";
\r
816 String keyStr = "";
\r
818 JSONObject jsonObj = new JSONObject(jsonStr);
\r
819 JSONObject jsonObjOut = jsonObj;
\r
820 StringTokenizer keyTokens = new StringTokenizer(keys, ".");
\r
821 while (keyTokens.hasMoreElements()) {
\r
822 keyStr = keyTokens.nextToken();
\r
823 if (keyTokens.hasMoreElements()) {
\r
824 Object keyValue = jsonObj.get(keyStr);
\r
825 if (keyValue instanceof JSONObject) {
\r
826 msoLogger.debug("putJsonValue(): key=" + keyStr + " points to json object");
\r
827 jsonObj = (JSONObject) keyValue;
\r
829 msoLogger.debug("putJsonValue(): key=" + keyStr + " not the last key but points to non-json object: " + (String) keyValue);
\r
832 } else { // at the last/new key value
\r
833 jsonObj.put(keyStr, value);
\r
834 return jsonObjOut.toString(3);
\r
837 // should not hit this point if the key points to a valid key value
\r
840 } catch (JSONException je) {
\r
841 // JSONObject::get() throws this exception if one of the specified keys is not found
\r
842 msoLogger.debug("putJsonValue(): caught JSONException attempting to retrieve value for key=" + keyStr,je);
\r
844 } catch (Exception e) {
\r
845 msoLogger.debug("putJsonValue(): unable to parse json to put value for key=" + keys + ". Exception was: " + e.toString(),e);
\r
851 * This json util method converts a json array of Key Value
\r
852 * pair objects into a Java Map.
\r
855 * @param entryArray - the getJsonValue of a json Array of key/value pairs
\r
857 * @return Map - a Map containing the entries
\r
859 public Map<String, String> entryArrayToMap(Execution execution, String entryArray) {
\r
860 msoLogger.debug("Started Entry Array To Map Util Method");
\r
862 Map<String, String> map = new HashMap<>();
\r
865 String entryListJson = "{ \"entry\":" + entryArray + "}";
\r
866 JSONObject obj = new JSONObject(entryListJson);
\r
867 JSONArray arr = obj.getJSONArray("entry");
\r
868 for (int i = 0; i < arr.length(); i++){
\r
869 JSONObject jo = arr.getJSONObject(i);
\r
870 String key = jo.getString("key");
\r
871 String value =jo.getString("value");
\r
872 map.put(key, value);
\r
874 msoLogger.debug("Outgoing Map is: " + map);
\r
875 msoLogger.debug("Completed Entry Array To Map Util Method");
\r
880 * This json util method converts a json array of Key Value
\r
881 * pair objects into a Java Map.
\r
884 * @param entryArray - the getJsonValue of a json Array of key/value pairs
\r
885 * @param keyNode - the name of the node that represents the key
\r
886 * @param valueNode - the name of the node that represents the value
\r
888 * @return Map - a Map containing the entries
\r
891 public Map<String, String> entryArrayToMap(Execution execution, String entryArray, String keyNode, String valueNode) {
\r
892 msoLogger.debug("Started Entry Array To Map Util Method");
\r
894 Map<String, String> map = new HashMap<>();
\r
896 String entryListJson = "{ \"entry\":" + entryArray + "}";
\r
897 JSONObject obj = new JSONObject(entryListJson);
\r
898 JSONArray arr = obj.getJSONArray("entry");
\r
899 for (int i = 0; i < arr.length(); i++){
\r
900 JSONObject jo = arr.getJSONObject(i);
\r
901 String key = jo.getString(keyNode);
\r
902 String value =jo.getString(valueNode);
\r
903 map.put(key, value);
\r
905 msoLogger.debug("Outgoing Map is: " + map);
\r
906 msoLogger.debug("Completed Entry Array To Map Util Method");
\r
911 * This json util method converts a json Array of Strings
\r
912 * to a Java List. It takes each String in the json Array
\r
913 * and puts it in a Java List<String>.
\r
916 * @param stringArray - the getJsonValue of a json array of strings
\r
918 * @return List - a java list containing the strings
\r
922 public List<String> StringArrayToList(Execution execution, String jsonArrayOfStrings) {
\r
923 msoLogger.debug("Started String Array To List Util Method");
\r
925 List<String> list = new ArrayList<>();
\r
927 String stringListJson = "{ \"strings\":" + jsonArrayOfStrings + "}";
\r
928 JSONObject obj = new JSONObject(stringListJson);
\r
929 JSONArray arr = obj.getJSONArray("strings");
\r
930 for (int i = 0; i < arr.length(); i++){
\r
931 String s = arr.getString(i);
\r
934 msoLogger.debug("Outgoing List is: " + list);
\r
935 msoLogger.debug("Completed String Array To List Util Method");
\r
941 * Invokes the getJsonRawValue() method to determine if the
\r
942 * json element/variable exist. Returns true if the
\r
943 * json element exist
\r
945 * @param jsonStr String containing the JSON doc
\r
946 * @param keys full key path to the target value in the format of "key1.key2.key3..."
\r
947 * @return boolean field value associated with keys
\r
951 public static boolean jsonElementExist(String jsonStr, String keys) {
\r
954 Object rawValue = getJsonRawValue(jsonStr, keys);
\r
955 if (rawValue == null) {
\r
960 } catch (Exception e) {
\r
961 msoLogger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: " + e.toString(),e);
\r