-/*-
- * ============LICENSE_START=======================================================
- * OPENECOMP - MSO
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.mso.bpmn.core.json;
-
-import java.util.Iterator;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.StringTokenizer;
-
-import org.camunda.bpm.engine.runtime.Execution;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.json.XML;
-
-//import org.openecomp.mso.bpmn.core.BPMNLogger;
-import org.openecomp.mso.bpmn.core.xml.XmlTool;
-import org.openecomp.mso.logger.MsoLogger;
-
-/**
- * Utility class for JSON processing
- *
- * @version 1.0
- */
-
-public class JsonUtils {
-
- private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
- private static int MSOJsonIndentFactor = 3;
-
- /**
- * Uses the JSONObject static method to convert a XML doc to JSON.
- *
- * @param xml String containing the XML doc
- * @param pretty flag to determine if the output should be formatted
- * @return String containing the JSON translation
- */
- public static String xml2json(String xml, Boolean pretty) {
-// String isDebugLogEnabled = "true";
- try {
- // name spaces cause problems, so just remove them
- JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml));
- if (!pretty) {
- return jsonObj.toString();
- } else {
- // add an indent to make it 'pretty'
- return jsonObj.toString(MSOJsonIndentFactor);
- }
- } catch (Exception e){
- msoLogger.debug("xml2json(): unable to parse xml and convert to json. Exception was: " + e.toString());
- return null;
- }
- }
-
- /**
- * Invokes xml2json(String, Boolean) defaulting to 'pretty' output.
- *
- * @param xml String containing the XML doc
- * @return String containing the JSON translation
- */
- public static String xml2json(String xml) {
- return xml2json(xml, true);
- }
-
- /**
- * Uses the JSONObject static method to convert a JSON doc to XML.
- * Note: this method may not generate valid XML if the JSONObject
- * contains JSONArrays which are used to represent XML attributes
- * in the JSON doc.
- *
- * @param jsonStr String containing the JSON doc
- * @param pretty flag to determine if the output should be formatted
- * @return String containing the XML translation
- */
- public static String json2xml(String jsonStr, Boolean pretty) {
-// String isDebugLogEnabled = "true";
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- if (pretty) {
- // use the local class method which properly handles certain JSONArray content
- return XmlTool.normalize(toXMLString(jsonObj, null));
- } else {
-// use the local class method which properly handles certain JSONArray content
- return toXMLString(jsonObj, null);
- }
- } catch (Exception e){
- msoLogger.debug("json2xml(): unable to parse json and convert to xml. Exception was: " + e.toString());
- return null;
- }
- }
-
- /**
- * Uses a modified version of the org.json.XML toString() algorithm
- * to convert a JSONObject to an XML Doc. The intent of this is to
- * correctly generate XML from JSON including TAGs for JSONArrays
- *
- * @param jsonObj org.json.JSON object to be converted to XML
- * @param tagName optional XML tagname supplied primarily during recursive calls
- * @return String containing the XML translation
- */
- public static String toXMLString(Object obj, String tagName) throws JSONException {
- StringBuffer strBuf = new StringBuffer();
- int i;
- JSONArray jsonArr;
- JSONObject jsonObj;
- String key;
- Iterator<String> keys;
- int len;
- String str;
- Object curObj;
- if (obj instanceof JSONObject) {
- // msoLogger.debug("toXMLString(): is a JSONObject");
- // append "<tagName>" to the XML output
- if (tagName != null) {
-// msoLogger.debug("toXMLString(): adding opening tagName: " + tagName);
- strBuf.append("<");
- strBuf.append(tagName);
- strBuf.append(">");
- }
- // iterate thru the keys.
- jsonObj = (JSONObject) obj;
- keys = jsonObj.keys();
- while (keys.hasNext()) {
- key = keys.next().toString();
- // msoLogger.debug("toXMLString(): key is " + k);
- curObj = jsonObj.opt(key);
- if (curObj == null) {
- curObj = "";
- }
- if (curObj instanceof String) {
- str = (String) curObj;
- } else {
- str = null;
- }
- // append the content to the XML output
- if (key.equals("content")) {
- if (curObj instanceof JSONArray) {
- jsonArr = (JSONArray) curObj;
- len = jsonArr.length();
- for (i = 0; i < len; i += 1) {
- if (i > 0) {
- strBuf.append('\n');
- }
- strBuf.append(XML.escape(jsonArr.get(i).toString()));
- }
- } else {
- strBuf.append(XML.escape(curObj.toString()));
- }
- // append an array of similar keys to the XML output
- } else if (curObj instanceof JSONArray) {
- jsonArr = (JSONArray) curObj;
- len = jsonArr.length();
-// msoLogger.debug("toXMLString(): found JSONArray: " + key + ", size: " + len);
- for (i = 0; i < len; i += 1) {
- curObj = jsonArr.get(i);
- if (curObj instanceof JSONArray) {
-// The XML tags for the nested array should be generated below when this method
-// is called recursively and the JSONArray object is passed
-// strBuf.append("<");
-// strBuf.append(key);
-// strBuf.append(">");
- strBuf.append(toXMLString(curObj, null));
-// strBuf.append("</");
-// strBuf.append(key);
-// strBuf.append(">");
- } else {
-// msoLogger.debug("toXMLString(): recursive call toXML() with tagName null");
- // append the opening tag for the array (before 1st element)
- if (i == 0) {
- strBuf.append("<");
- strBuf.append(key);
- strBuf.append(">");
- }
- // append the opening tag for the array
- strBuf.append(toXMLString(curObj, null));
- // append the closing tag for the array (after last element)
- if (i == (len - 1)) {
- strBuf.append("</");
- strBuf.append(key);
- strBuf.append(">");
- }
- }
- }
- } else if (curObj.equals("")) {
- // append a closing tag "<key>" to the XML output
- strBuf.append("<");
- strBuf.append(key);
- strBuf.append("/>");
- } else {
-// msoLogger.debug("toXMLString(): recursive call toXMLString() with tagName: " + key);
- strBuf.append(toXMLString(curObj, key));
- }
- // msoLogger.debug("toXML(): partial XML: " + strBuf.toString());
- }
- if (tagName != null) {
- // append the closing tag "</tagName>" to the XML output
-// msoLogger.debug("toXMLString(): adding closing tagName: " + tagName);
- strBuf.append("</");
- strBuf.append(tagName);
- strBuf.append(">");
- }
- return strBuf.toString();
- // XML does not have good support for arrays. If an array appears in a place
- // where XML is lacking, synthesize an < array > element.
- } else if (obj instanceof JSONArray) {
- jsonArr = (JSONArray) obj;
- len = jsonArr.length();
- for (i = 0; i < len; ++i) {
- curObj = jsonArr.opt(i);
- strBuf.append(toXMLString(curObj, (tagName == null) ? "array"
- : tagName));
- }
- return strBuf.toString();
- } else {
-// msoLogger.debug("toXML(): in else block with tagName: " + tagName);
- str = (obj == null) ? "null" : XML.escape(obj.toString());
- return (tagName == null) ? "\"" + str + "\""
- : (str.length() == 0) ? "<" + tagName + "/>" : "<"
- + tagName + ">" + str + "</" + tagName + ">";
- }
- }
-
- /**
- * Formats the JSON String using the value of MSOJsonIndentFactor.
- *
- * @param jsonStr String containing the JSON doc
- * @return String containing the formatted JSON doc
- */
- public static String prettyJson(String jsonStr) {
-// String isDebugLogEnabled = "true";
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- return jsonObj.toString(MSOJsonIndentFactor);
- } catch (Exception e){
- msoLogger.debug("prettyJson(): unable to parse/format json input. Exception was: " + e.toString());
- return null;
- }
- }
-
- /**
- * Invokes json2xml(String, Boolean) defaulting to 'pretty' output.
- *
- * @param jsonStr String containing the XML doc
- * @return String containing the JSON translation
- */
- public static String json2xml(String jsonStr) {
- return json2xml(jsonStr, true);
- }
-
- /**
- * Returns an Iterator over the JSON keys in the specified JSON doc.
- *
- * @param jsonStr String containing the JSON doc
- * @return Iterator over the JSON keys
- * @throws JSONException if the doc cannot be parsed
- */
- public static Iterator <String> getJsonIterator(String jsonStr) throws JSONException {
- return new JSONObject(jsonStr).keys();
- }
-
- /**
- * Returns the name of the "root" property in the specified JSON doc. The
- * "root" property is the single top-level property in the JSON doc. An
- * exception is thrown if the doc is empty or if it contains more than one
- * top-level property.
- *
- * @param jsonStr String containing the JSON doc
- * @return the name of the "root" property
- * @throws JSONException if the doc cannot be parsed, or if it is empty, or if
- * it contains more than one top-level property
- */
- public static String getJsonRootProperty(String jsonStr) throws JSONException {
- Iterator<String> iter = getJsonIterator(jsonStr);
-
- if (!iter.hasNext()) {
- throw new JSONException("Empty JSON object");
- }
-
- String rootPropertyName = iter.next();
-
- if (iter.hasNext()) {
- throw new JSONException("JSON object has more than one root property");
- }
-
- return rootPropertyName;
- }
-
- /**
- * Invokes the getJsonRawValue() method and returns the String equivalent of
- * the object returned.
- *
- * TBD: May need separate methods for boolean, float, and integer fields if the
- * String representation is not sufficient to meet client needs.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return String field value associated with keys
- */
- public static String getJsonValue(String jsonStr, String keys) {
-// String isDebugLogEnabled = "true";
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys);
- if (rawValue == null) {
- return null;
- } else {
- if (rawValue instanceof String) {
- msoLogger.debug("getJsonValue(): the raw value is a String Object=" + ((String) rawValue).toString());
- return (String) rawValue;
- } else {
- msoLogger.debug("getJsonValue(): the raw value is NOT a String Object=" + rawValue.toString());
- return rawValue.toString();
- }
- }
- } catch (Exception e) {
- msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString());
- }
- return null;
- }
-
-
- /**
- * Invokes the getJsonRawValue() method with the wrap flag set to true
- * and returns the String equivalent of the json node object returned.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return String field value associated with keys
- */
- public static String getJsonNodeValue(String jsonStr, String keys) {
-// String isDebugLogEnabled = "true";
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys, true);
- if (rawValue == null) {
- return null;
- } else {
- if (rawValue instanceof String) {
- msoLogger.debug("getJsonNodeValue(): the raw value is a String Object=" + ((String) rawValue).toString());
- return (String) rawValue;
- } else {
- msoLogger.debug("getJsonNodeValue(): the raw value is NOT a String Object=" + rawValue.toString());
- return rawValue.toString();
- }
- }
- } catch (Exception e) {
- msoLogger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field=" + keys + ". Exception was: " + e.toString());
- }
- return null;
- }
-
- /**
- * Invokes the getJsonRawValue() method and returns the String equivalent of
- * the object returned.
- *
- * TBD: May need separate methods for boolean, float, and integer fields if the
- * String representation is not sufficient to meet client needs.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return String field value associated with keys
- */
- public static int getJsonIntValue(String jsonStr, String keys) {
-// String isDebugLogEnabled = "true";
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys);
- if (rawValue == null) {
- return 0;
- } else {
- if (rawValue instanceof Integer) {
- msoLogger.debug("getJsonValue(): the raw value is an Integer Object=" + ((String) rawValue).toString());
- return (Integer) rawValue;
- } else {
- msoLogger.debug("getJsonValue(): the raw value is NOT an Integer Object=" + rawValue.toString());
- return 0;
- }
- }
- } catch (Exception e) {
- msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString());
- }
- return 0;
- }
-
- /**
- * Invokes the getJsonParamValue() method to obtain the JSONArray associated with
- * the specified keys. The JSONArray is then walked to retrieve the first array
- * value associated with the specified field name (index=0).
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @param name field name for the param to be retrieved
- * @return String param value associated with field name
- */
- public static String getJsonParamValue(String jsonStr, String keys, String name) {
- return getJsonParamValue(jsonStr, keys, name, 0);
- }
-
- /**
- * Invokes the getJsonRawValue() method to obtain the JSONArray associated with
- * the specified keys. The JSONArray is then walked to retrieve the nth array
- * value associated with the specified field name and index
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @param name field name for the param to be retrieved
- * @param index the nth param associated with name starting at 0
- * @return String param value associated with field name
- */
- public static String getJsonParamValue(String jsonStr, String keys, String name, int index) {
-// String isDebugLogEnabled = "true";
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys);
- if (rawValue == null) {
- return null;
- } else {
- if (rawValue instanceof JSONArray) {
- msoLogger.debug("getJsonParamValue(): keys=" + keys + " points to JSONArray: " + ((JSONArray) rawValue).toString());
- int arrayLen = ((JSONArray) rawValue).length();
- if (index < 0 || arrayLen < index+1) {
- msoLogger.debug("getJsonParamValue(): index: " + index + " is out of bounds for array size of " + arrayLen);
- return null;
- }
- int foundCnt = 0;
- for (int i = 0; i < arrayLen; i++) {
- msoLogger.debug("getJsonParamValue(): index: " + i + ", value: " + ((JSONArray) rawValue).get(i).toString());
- if (((JSONArray) rawValue).get(i) instanceof JSONObject) {
- msoLogger.debug("getJsonParamValue(): index: " + i + " is a JSONObject");
- JSONObject jsonObj = (JSONObject)((JSONArray) rawValue).get(i);
- String parmValue = jsonObj.get(name).toString();
- if (parmValue != null) {
- msoLogger.debug("getJsonParamValue(): found value: " + parmValue + " for name: " + name + " and index: " + i);
- if (foundCnt == index) {
- return parmValue;
- } else {
- foundCnt++;
- continue;
- }
- } else {
- continue;
- }
- } else {
- msoLogger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject=" + rawValue.toString());
- return null;
- }
- }
- msoLogger.debug("getJsonParamValue(): content value NOT found for name: " + name);
- return null;
- } else {
- msoLogger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object=" + rawValue.toString());
- return null;
- }
- }
- } catch (JSONException je) {
- // JSONObject::get() throws this exception if one of the specified keys is not found
- msoLogger.debug("getJsonParamValue(): caught JSONException attempting to retrieve param value for keys:" + keys + ", name=" + name);
- } catch (Exception e) {
- msoLogger.debug("getJsonParamValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString());
- }
- return null;
- }
-
- /**
- * Wrapper to generate the JSONObject to pass to the getJsonValueForKey(JSONObject, String)
- * method so that recursion over the subobjects can be supported there
- *
- * @param jsonStr String containing the JSON doc
- * @param key key to the target value
- * @return String field value associated with key
- */
- public static String getJsonValueForKey(String jsonStr, String key) {
-// String isDebugLogEnabled = "true";
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- if (jsonObj != null) {
- return getJsonValueForKey(jsonObj, key);
- }
- } catch (Exception e) {
- msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString());
- }
- return null;
- }
-
- /**
- * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the
- * single key/field name specified. Returns the associated value if found or null if the key is not found
- *
- * @param jsonObj JSONObject representation of the the JSON doc
- * @param key key to the target value
- * @return String field value associated with key
- */
- public static String getJsonValueForKey(JSONObject jsonObj, String key) {
-// String isDebugLogEnabled = "true";
- String keyValue = null;
- try {
- if (jsonObj.has(key)) {
- msoLogger.debug("getJsonValueForKey(): found value for key=" + key);
- return ((String) jsonObj.get(key));
- } else {
- msoLogger.debug("getJsonValueForKey(): iterating over the keys");
- Iterator <String> itr = jsonObj.keys();
- while (itr.hasNext()) {
- String nextKey = (String) itr.next();
- Object obj = jsonObj.get(nextKey);
- if (obj instanceof JSONObject) {
- msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");
- keyValue = getJsonValueForKey((JSONObject) obj, key);
- if (keyValue != null) {
- msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key);
- break;
- }
- } else {
- msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");
- }
- }
- }
- } catch (JSONException je) {
- // JSONObject::get() throws this exception if one of the specified keys is not found
- msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key);
- keyValue = null;
- } catch (Exception e) {
- msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString());
- }
- return keyValue;
- }
-
- /**
- * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the
- * single key/field name specified. Returns the associated value if found or null if the key is not found
- *
- * @param jsonObj JSONObject representation of the the JSON doc
- * @param key key to the target value
- * @return String field value associated with key
- */
- public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) {
-// String isDebugLogEnabled = "true";
- Integer keyValue = 0;
- try {
- if (jsonObj.has(key)) {
- msoLogger.debug("getJsonValueForKey(): found value for key=" + key);
- return ((Integer) jsonObj.get(key));
- } else {
- msoLogger.debug("getJsonValueForKey(): iterating over the keys");
- Iterator <String> itr = jsonObj.keys();
- while (itr.hasNext()) {
- String nextKey = (String) itr.next();
- Object obj = jsonObj.get(nextKey);
- if (obj instanceof JSONObject) {
- msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");
- keyValue = getJsonIntValueForKey((JSONObject) obj, key);
- if (keyValue != null) {
- msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key);
- break;
- }
- } else {
- msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");
- }
- }
- }
- } catch (JSONException je) {
- // JSONObject::get() throws this exception if one of the specified keys is not found
- msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key);
- keyValue = null;
- } catch (Exception e) {
- msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString());
- }
- return keyValue;
- }
-
- /**
- * Boolean method to determine if a key path is valid for the JSON doc. Invokes
- * getJsonValue().
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return Boolean true if keys points to value in the JSON doc
- */
- public static Boolean jsonValueExists(String jsonStr, String keys) {
- if (getJsonRawValue(jsonStr, keys) == null) {
- return false;
- } else {
- return true;
- }
- }
-
- /**
- * Inserts the new key/value pair at the appropriate location in the JSON
- * document after first determining if keyed field already exists. If
- * it does exist, return the JSON unmodified, otherwise return the new JSON
- * Note: this method currently only supports String value inserts.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the value to be added in the format of "key1.key2.key3..."
- * @return String containing the updated JSON doc
- */
- public static String addJsonValue(String jsonStr, String keys, String value) {
-// String isDebugLogEnabled = "true";
- // only attempt to insert the key/value pair if it does not exist
- if (!jsonValueExists(jsonStr, keys)) {
- return putJsonValue(jsonStr, keys, value);
- } else {
- msoLogger.debug("addJsonValue(): JSON add failed, key=" + keys + "/value=" + (String) value + " already exists");
- return jsonStr;
- }
- }
-
- /**
- * Updates the value for the specified key in the JSON document
- * after first determining if keyed field exists. If it does
- * not exist, return the JSON unmodified, otherwise return the updated JSON.
- * Note: this method currently only supports String value updates.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the value to be updated in the format of "key1.key2.key3..."
- * @return String containing the updated JSON doc
- */
- public static String updJsonValue(String jsonStr, String keys, String newValue) {
-// String isDebugLogEnabled = "true";
- // only attempt to modify the key/value pair if it exists
- if (jsonValueExists(jsonStr, keys)) {
- return putJsonValue(jsonStr, keys, newValue);
- } else {
- msoLogger.debug("updJsonValue(): JSON update failed, no value exists for key=" + keys);
- return jsonStr;
- }
- }
-
- /**
- * Deletes the value for the specified key in the JSON document
- * after first determining if keyed field exists. If it does
- * not exist, return the JSON unmodified, otherwise return the updated JSON
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."
- * @return String containing the updated JSON doc
- */
- public static String delJsonValue(String jsonStr, String keys) {
-// String isDebugLogEnabled = "true";
- // only attempt to remove the key/value pair if it exists
- if (jsonValueExists(jsonStr, keys)) {
- // passing a null value results in a delete
- return putJsonValue(jsonStr, keys, null);
- } else {
- msoLogger.debug("delJsonValue(): JSON delete failed, no value exists for key=" + keys);
- return jsonStr;
- }
- }
-
- /**
- * Walks the JSON doc using the full key path to retrieve the associated
- * value. All but the last key points to the 'parent' object name(s) in order
- * in the JSON hierarchy with the last key pointing to the target value.
- * The value returned is a Java object.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return Object field value associated with keys
- */
- private static Object getJsonRawValue(String jsonStr, String keys) {
- return getJsonRawValue(jsonStr, keys, false);
- }
-
- /**
- * Walks the JSON doc using the full key path to retrieve the associated
- * value. All but the last key points to the 'parent' object name(s) in order
- * in the JSON hierarchy with the last key pointing to the target value.
- * The value returned is a Java object.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped"
- * Note: wrap does not apply to returned scalar values
- * @return Object field value associated with keys
- */
- private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) {
-// String isDebugLogEnabled = "true";
- String keyStr = "";
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- StringTokenizer keyTokens = new StringTokenizer(keys, ".");
- while (keyTokens.hasMoreElements()) {
- keyStr = keyTokens.nextToken();
- Object keyValue = jsonObj.get(keyStr);
- if (keyValue instanceof JSONObject) {
- msoLogger.debug("getJsonRawValue(): key=" + keyStr + " points to json object");
- jsonObj = (JSONObject) keyValue;
- } else {
- if (keyTokens.hasMoreElements()) {
- msoLogger.debug("getJsonRawValue(): value found prior to last key for key=" + keyStr);
- }
- return keyValue;
- }
- }
- // return the json 'node' that the key points to
- // note: since this is a json object and not a scalar value,
- // use the wrap flag to determine if the object should
- // be wrapped with a root node value
- // (the last key in the keys String)
- if (wrap) {
- JSONObject wrappedJsonObj = new JSONObject();
- wrappedJsonObj.put(keyStr, jsonObj);
- return wrappedJsonObj.toString();
- } else {
- return jsonObj.toString();
- }
-
- } catch (JSONException je) {
- // JSONObject::get() throws this exception if one of the specified keys is not found
- msoLogger.debug("getJsonRawValue(): caught JSONException attempting to retrieve raw value for key=" + keyStr);
- } catch (Exception e) {
- msoLogger.debug("getJsonRawValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString());
- }
- return null;
- }
-
- /**
- * Private method invoked by the public add, update, and delete methods.
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."
- * @return String containing the updated JSON doc
- */
- private static String putJsonValue(String jsonStr, String keys, String value) {
-// String isDebugLogEnabled = "true";
- String keyStr = "";
- try {
- JSONObject jsonObj = new JSONObject(jsonStr);
- JSONObject jsonObjOut = jsonObj;
- StringTokenizer keyTokens = new StringTokenizer(keys, ".");
- while (keyTokens.hasMoreElements()) {
- keyStr = keyTokens.nextToken();
- if (keyTokens.hasMoreElements()) {
- Object keyValue = jsonObj.get(keyStr);
- if (keyValue instanceof JSONObject) {
- msoLogger.debug("putJsonValue(): key=" + keyStr + " points to json object");
- jsonObj = (JSONObject) keyValue;
- } else {
- msoLogger.debug("putJsonValue(): key=" + keyStr + " not the last key but points to non-json object: " + (String) keyValue);
- return null;
- }
- } else { // at the last/new key value
- jsonObj.put(keyStr, value);
- return jsonObjOut.toString(3);
- }
- }
- // should not hit this point if the key points to a valid key value
- return null;
-
- } catch (JSONException je) {
- // JSONObject::get() throws this exception if one of the specified keys is not found
- msoLogger.debug("putJsonValue(): caught JSONException attempting to retrieve value for key=" + keyStr);
- return null;
- } catch (Exception e) {
- msoLogger.debug("putJsonValue(): unable to parse json to put value for key=" + keys + ". Exception was: " + e.toString());
- }
- return null;
- }
-
- /**
- * This json util method converts a json "Key" and "Value"
- * entry Array to a Java map.
- *
- * @param execution
- * @param entryArray - the json value of the entry Array
- *
- * @return map - a Map containing the entries
- *
- */
- public Map<String, String> entryArrayToMap(Execution execution, String entryArray) {
- msoLogger.debug("Started Entry Array To Map Util Method");
-
- Map<String, String> map = new HashMap<String, String>();
-
- //Populate Map
- String entryListJson = "{ \"entry\":" + entryArray + "}";
- JSONObject obj = new JSONObject(entryListJson);
- JSONArray arr = obj.getJSONArray("entry");
- for (int i = 0; i < arr.length(); i++){
- JSONObject jo = arr.getJSONObject(i);
- String key = jo.getString("key");
- String value =jo.getString("value");
- map.put(key, value);
- }
- msoLogger.debug("Outgoing Map is: " + map);
- msoLogger.debug("Completed Entry Array To Map Util Method");
- return map;
- }
-
-
- /**
- * Invokes the getJsonRawValue() method to determine if the
- * json element/variable exist. Returns true if the
- * json element exist
- *
- * @param jsonStr String containing the JSON doc
- * @param keys full key path to the target value in the format of "key1.key2.key3..."
- * @return boolean field value associated with keys
- */
- public static boolean jsonElementExist(String jsonStr, String keys) {
-
- try {
- Object rawValue = getJsonRawValue(jsonStr, keys);
- if (rawValue == null) {
- return false;
- } else {
- return true;
- }
- } catch (Exception e) {
- msoLogger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: " + e.toString());
- }
- return true;
- }
-
-}
-
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * OPENECOMP - MSO\r
+ * ================================================================================\r
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * \r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * \r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+\r
+package org.openecomp.mso.bpmn.core.json;\r
+\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+import java.util.HashMap;\r
+import java.util.StringTokenizer;\r
+\r
+import org.camunda.bpm.engine.runtime.Execution;\r
+import org.json.JSONArray;\r
+import org.json.JSONException;\r
+import org.json.JSONObject;\r
+import org.json.XML;\r
+\r
+//import org.openecomp.mso.bpmn.core.BPMNLogger;\r
+import org.openecomp.mso.bpmn.core.xml.XmlTool;\r
+import org.openecomp.mso.logger.MsoLogger;\r
+\r
+/**\r
+ * Utility class for JSON processing\r
+ * \r
+ * @version 1.0\r
+ */\r
+\r
+public class JsonUtils {\r
+\r
+ private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);\r
+ private static int MSOJsonIndentFactor = 3;\r
+\r
+ /**\r
+ * Uses the JSONObject static method to convert a XML doc to JSON.\r
+ *\r
+ * @param xml String containing the XML doc\r
+ * @param pretty flag to determine if the output should be formatted\r
+ * @return String containing the JSON translation\r
+ */\r
+ public static String xml2json(String xml, Boolean pretty) {\r
+// String isDebugLogEnabled = "true";\r
+ try {\r
+ // name spaces cause problems, so just remove them\r
+ JSONObject jsonObj = XML.toJSONObject(XmlTool.removeNamespaces(xml));\r
+ if (!pretty) {\r
+ return jsonObj.toString();\r
+ } else {\r
+ // add an indent to make it 'pretty'\r
+ return jsonObj.toString(MSOJsonIndentFactor);\r
+ }\r
+ } catch (Exception e){\r
+ msoLogger.debug("xml2json(): unable to parse xml and convert to json. Exception was: " + e.toString());\r
+ return null;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Invokes xml2json(String, Boolean) defaulting to 'pretty' output.\r
+ *\r
+ * @param xml String containing the XML doc\r
+ * @return String containing the JSON translation\r
+ */\r
+ public static String xml2json(String xml) {\r
+ return xml2json(xml, true);\r
+ }\r
+\r
+ /**\r
+ * Uses the JSONObject static method to convert a JSON doc to XML.\r
+ * Note: this method may not generate valid XML if the JSONObject\r
+ * contains JSONArrays which are used to represent XML attributes\r
+ * in the JSON doc.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param pretty flag to determine if the output should be formatted\r
+ * @return String containing the XML translation\r
+ */\r
+ public static String json2xml(String jsonStr, Boolean pretty) {\r
+// String isDebugLogEnabled = "true";\r
+ try {\r
+ JSONObject jsonObj = new JSONObject(jsonStr);\r
+ if (pretty) {\r
+ // use the local class method which properly handles certain JSONArray content\r
+ return XmlTool.normalize(toXMLString(jsonObj, null));\r
+ } else {\r
+// use the local class method which properly handles certain JSONArray content\r
+ return toXMLString(jsonObj, null);\r
+ }\r
+ } catch (Exception e){\r
+ msoLogger.debug("json2xml(): unable to parse json and convert to xml. Exception was: " + e.toString());\r
+ return null;\r
+ }\r
+ }\r
+ \r
+ /**\r
+ * Uses a modified version of the org.json.XML toString() algorithm\r
+ * to convert a JSONObject to an XML Doc. The intent of this is to\r
+ * correctly generate XML from JSON including TAGs for JSONArrays\r
+ *\r
+ * @param jsonObj org.json.JSON object to be converted to XML\r
+ * @param tagName optional XML tagname supplied primarily during recursive calls\r
+ * @return String containing the XML translation\r
+ */\r
+ public static String toXMLString(Object obj, String tagName) throws JSONException {\r
+ StringBuffer strBuf = new StringBuffer();\r
+ int i;\r
+ JSONArray jsonArr;\r
+ JSONObject jsonObj;\r
+ String key;\r
+ Iterator<String> keys;\r
+ int len;\r
+ String str;\r
+ Object curObj;\r
+ if (obj instanceof JSONObject) {\r
+ // msoLogger.debug("toXMLString(): is a JSONObject");\r
+ // append "<tagName>" to the XML output\r
+ if (tagName != null) {\r
+// msoLogger.debug("toXMLString(): adding opening tagName: " + tagName);\r
+ strBuf.append("<");\r
+ strBuf.append(tagName);\r
+ strBuf.append(">");\r
+ }\r
+ // iterate thru the keys.\r
+ jsonObj = (JSONObject) obj;\r
+ keys = jsonObj.keys();\r
+ while (keys.hasNext()) {\r
+ key = keys.next().toString();\r
+ // msoLogger.debug("toXMLString(): key is " + k);\r
+ curObj = jsonObj.opt(key);\r
+ if (curObj == null) {\r
+ curObj = "";\r
+ }\r
+ if (curObj instanceof String) {\r
+ str = (String) curObj;\r
+ } else {\r
+ str = null;\r
+ }\r
+ // append the content to the XML output\r
+ if (key.equals("content")) {\r
+ if (curObj instanceof JSONArray) {\r
+ jsonArr = (JSONArray) curObj;\r
+ len = jsonArr.length();\r
+ for (i = 0; i < len; i += 1) {\r
+ if (i > 0) {\r
+ strBuf.append('\n');\r
+ }\r
+ strBuf.append(XML.escape(jsonArr.get(i).toString()));\r
+ }\r
+ } else {\r
+ strBuf.append(XML.escape(curObj.toString()));\r
+ }\r
+ // append an array of similar keys to the XML output\r
+ } else if (curObj instanceof JSONArray) {\r
+ jsonArr = (JSONArray) curObj;\r
+ len = jsonArr.length();\r
+// msoLogger.debug("toXMLString(): found JSONArray: " + key + ", size: " + len);\r
+ for (i = 0; i < len; i += 1) {\r
+ curObj = jsonArr.get(i);\r
+ if (curObj instanceof JSONArray) {\r
+// The XML tags for the nested array should be generated below when this method\r
+// is called recursively and the JSONArray object is passed \r
+// strBuf.append("<");\r
+// strBuf.append(key);\r
+// strBuf.append(">");\r
+ strBuf.append(toXMLString(curObj, null));\r
+// strBuf.append("</");\r
+// strBuf.append(key);\r
+// strBuf.append(">");\r
+ } else {\r
+// msoLogger.debug("toXMLString(): recursive call toXML() with tagName null");\r
+ // append the opening tag for the array (before 1st element)\r
+ if (i == 0) {\r
+ strBuf.append("<");\r
+ strBuf.append(key);\r
+ strBuf.append(">");\r
+ }\r
+ // append the opening tag for the array\r
+ strBuf.append(toXMLString(curObj, null));\r
+ // append the closing tag for the array (after last element)\r
+ if (i == (len - 1)) {\r
+ strBuf.append("</");\r
+ strBuf.append(key);\r
+ strBuf.append(">");\r
+ }\r
+ }\r
+ }\r
+ } else if (curObj.equals("")) {\r
+ // append a closing tag "<key>" to the XML output\r
+ strBuf.append("<");\r
+ strBuf.append(key);\r
+ strBuf.append("/>");\r
+ } else {\r
+// msoLogger.debug("toXMLString(): recursive call toXMLString() with tagName: " + key);\r
+ strBuf.append(toXMLString(curObj, key));\r
+ }\r
+ // msoLogger.debug("toXML(): partial XML: " + strBuf.toString());\r
+ }\r
+ if (tagName != null) {\r
+ // append the closing tag "</tagName>" to the XML output\r
+// msoLogger.debug("toXMLString(): adding closing tagName: " + tagName);\r
+ strBuf.append("</");\r
+ strBuf.append(tagName);\r
+ strBuf.append(">");\r
+ }\r
+ return strBuf.toString();\r
+ // XML does not have good support for arrays. If an array appears in a place\r
+ // where XML is lacking, synthesize an < array > element.\r
+ } else if (obj instanceof JSONArray) {\r
+ jsonArr = (JSONArray) obj;\r
+ len = jsonArr.length();\r
+ for (i = 0; i < len; ++i) {\r
+ curObj = jsonArr.opt(i);\r
+ strBuf.append(toXMLString(curObj, (tagName == null) ? "array"\r
+ : tagName));\r
+ }\r
+ return strBuf.toString();\r
+ } else {\r
+// msoLogger.debug("toXML(): in else block with tagName: " + tagName);\r
+ str = (obj == null) ? "null" : XML.escape(obj.toString());\r
+ return (tagName == null) ? "\"" + str + "\""\r
+ : (str.length() == 0) ? "<" + tagName + "/>" : "<"\r
+ + tagName + ">" + str + "</" + tagName + ">";\r
+ }\r
+ }\r
+ \r
+ /**\r
+ * Formats the JSON String using the value of MSOJsonIndentFactor.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @return String containing the formatted JSON doc\r
+ */\r
+ public static String prettyJson(String jsonStr) {\r
+// String isDebugLogEnabled = "true";\r
+ try {\r
+ JSONObject jsonObj = new JSONObject(jsonStr);\r
+ return jsonObj.toString(MSOJsonIndentFactor);\r
+ } catch (Exception e){\r
+ msoLogger.debug("prettyJson(): unable to parse/format json input. Exception was: " + e.toString());\r
+ return null;\r
+ }\r
+ }\r
+ \r
+ /**\r
+ * Invokes json2xml(String, Boolean) defaulting to 'pretty' output.\r
+ *\r
+ * @param jsonStr String containing the XML doc\r
+ * @return String containing the JSON translation\r
+ */\r
+ public static String json2xml(String jsonStr) {\r
+ return json2xml(jsonStr, true);\r
+ }\r
+ \r
+ /**\r
+ * Returns an Iterator over the JSON keys in the specified JSON doc.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @return Iterator over the JSON keys\r
+ * @throws JSONException if the doc cannot be parsed\r
+ */\r
+ public static Iterator <String> getJsonIterator(String jsonStr) throws JSONException {\r
+ return new JSONObject(jsonStr).keys();\r
+ }\r
+ \r
+ /**\r
+ * Returns the name of the "root" property in the specified JSON doc. The\r
+ * "root" property is the single top-level property in the JSON doc. An\r
+ * exception is thrown if the doc is empty or if it contains more than one\r
+ * top-level property.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @return the name of the "root" property\r
+ * @throws JSONException if the doc cannot be parsed, or if it is empty, or if\r
+ * it contains more than one top-level property\r
+ */\r
+ public static String getJsonRootProperty(String jsonStr) throws JSONException {\r
+ Iterator<String> iter = getJsonIterator(jsonStr);\r
+\r
+ if (!iter.hasNext()) {\r
+ throw new JSONException("Empty JSON object");\r
+ }\r
+\r
+ String rootPropertyName = iter.next();\r
+\r
+ if (iter.hasNext()) {\r
+ throw new JSONException("JSON object has more than one root property");\r
+ }\r
+\r
+ return rootPropertyName;\r
+ }\r
+\r
+ /**\r
+ * Invokes the getJsonRawValue() method and returns the String equivalent of\r
+ * the object returned.\r
+ * \r
+ * TBD: May need separate methods for boolean, float, and integer fields if the\r
+ * String representation is not sufficient to meet client needs.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."\r
+ * @return String field value associated with keys\r
+ */\r
+ public static String getJsonValue(String jsonStr, String keys) {\r
+// String isDebugLogEnabled = "true";\r
+ try {\r
+ Object rawValue = getJsonRawValue(jsonStr, keys);\r
+ if (rawValue == null) {\r
+ return null;\r
+ } else {\r
+ if (rawValue instanceof String) {\r
+ msoLogger.debug("getJsonValue(): the raw value is a String Object=" + ((String) rawValue).toString());\r
+ return (String) rawValue;\r
+ } else {\r
+ msoLogger.debug("getJsonValue(): the raw value is NOT a String Object=" + rawValue.toString());\r
+ return rawValue.toString();\r
+ }\r
+ }\r
+ } catch (Exception e) {\r
+ msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString());\r
+ }\r
+ return null;\r
+ }\r
+ \r
+ \r
+ /**\r
+ * Invokes the getJsonRawValue() method with the wrap flag set to true\r
+ * and returns the String equivalent of the json node object returned.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."\r
+ * @return String field value associated with keys\r
+ */\r
+ public static String getJsonNodeValue(String jsonStr, String keys) {\r
+// String isDebugLogEnabled = "true";\r
+ try {\r
+ Object rawValue = getJsonRawValue(jsonStr, keys, true);\r
+ if (rawValue == null) {\r
+ return null;\r
+ } else {\r
+ if (rawValue instanceof String) {\r
+ msoLogger.debug("getJsonNodeValue(): the raw value is a String Object=" + ((String) rawValue).toString());\r
+ return (String) rawValue;\r
+ } else {\r
+ msoLogger.debug("getJsonNodeValue(): the raw value is NOT a String Object=" + rawValue.toString());\r
+ return rawValue.toString();\r
+ }\r
+ }\r
+ } catch (Exception e) {\r
+ msoLogger.debug("getJsonNodeValue(): unable to parse json to retrieve node for field=" + keys + ". Exception was: " + e.toString());\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * Invokes the getJsonRawValue() method and returns the String equivalent of\r
+ * the object returned.\r
+ * \r
+ * TBD: May need separate methods for boolean, float, and integer fields if the\r
+ * String representation is not sufficient to meet client needs.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."\r
+ * @return String field value associated with keys\r
+ */\r
+ public static int getJsonIntValue(String jsonStr, String keys) {\r
+// String isDebugLogEnabled = "true";\r
+ try {\r
+ Object rawValue = getJsonRawValue(jsonStr, keys);\r
+ if (rawValue == null) {\r
+ return 0;\r
+ } else {\r
+ if (rawValue instanceof Integer) {\r
+ msoLogger.debug("getJsonValue(): the raw value is an Integer Object=" + ((String) rawValue).toString());\r
+ return (Integer) rawValue;\r
+ } else {\r
+ msoLogger.debug("getJsonValue(): the raw value is NOT an Integer Object=" + rawValue.toString());\r
+ return 0;\r
+ }\r
+ }\r
+ } catch (Exception e) {\r
+ msoLogger.debug("getJsonValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString());\r
+ }\r
+ return 0;\r
+ }\r
+\r
+ /**\r
+ * Invokes the getJsonParamValue() method to obtain the JSONArray associated with\r
+ * the specified keys. The JSONArray is then walked to retrieve the first array\r
+ * value associated with the specified field name (index=0).\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."\r
+ * @param name field name for the param to be retrieved\r
+ * @return String param value associated with field name\r
+ */\r
+ public static String getJsonParamValue(String jsonStr, String keys, String name) {\r
+ return getJsonParamValue(jsonStr, keys, name, 0);\r
+ }\r
+\r
+ /**\r
+ * Invokes the getJsonRawValue() method to obtain the JSONArray associated with\r
+ * the specified keys. The JSONArray is then walked to retrieve the nth array\r
+ * value associated with the specified field name and index\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."\r
+ * @param name field name for the param to be retrieved\r
+ * @param index the nth param associated with name starting at 0\r
+ * @return String param value associated with field name\r
+ */\r
+ public static String getJsonParamValue(String jsonStr, String keys, String name, int index) {\r
+// String isDebugLogEnabled = "true";\r
+ try {\r
+ Object rawValue = getJsonRawValue(jsonStr, keys);\r
+ if (rawValue == null) {\r
+ return null;\r
+ } else {\r
+ if (rawValue instanceof JSONArray) {\r
+ msoLogger.debug("getJsonParamValue(): keys=" + keys + " points to JSONArray: " + ((JSONArray) rawValue).toString());\r
+ int arrayLen = ((JSONArray) rawValue).length();\r
+ if (index < 0 || arrayLen < index+1) {\r
+ msoLogger.debug("getJsonParamValue(): index: " + index + " is out of bounds for array size of " + arrayLen);\r
+ return null;\r
+ }\r
+ int foundCnt = 0;\r
+ for (int i = 0; i < arrayLen; i++) {\r
+ msoLogger.debug("getJsonParamValue(): index: " + i + ", value: " + ((JSONArray) rawValue).get(i).toString());\r
+ if (((JSONArray) rawValue).get(i) instanceof JSONObject) {\r
+ msoLogger.debug("getJsonParamValue(): index: " + i + " is a JSONObject");\r
+ JSONObject jsonObj = (JSONObject)((JSONArray) rawValue).get(i);\r
+ String parmValue = jsonObj.get(name).toString();\r
+ if (parmValue != null) {\r
+ msoLogger.debug("getJsonParamValue(): found value: " + parmValue + " for name: " + name + " and index: " + i);\r
+ if (foundCnt == index) {\r
+ return parmValue;\r
+ } else {\r
+ foundCnt++;\r
+ continue;\r
+ }\r
+ } else {\r
+ continue;\r
+ }\r
+ } else {\r
+ msoLogger.debug("getJsonParamValue(): the JSONArray element is NOT a JSONObject=" + rawValue.toString());\r
+ return null;\r
+ }\r
+ }\r
+ msoLogger.debug("getJsonParamValue(): content value NOT found for name: " + name);\r
+ return null;\r
+ } else {\r
+ msoLogger.debug("getJsonParamValue(): the raw value is NOT a JSONArray Object=" + rawValue.toString());\r
+ return null;\r
+ }\r
+ }\r
+ } catch (JSONException je) {\r
+ // JSONObject::get() throws this exception if one of the specified keys is not found\r
+ msoLogger.debug("getJsonParamValue(): caught JSONException attempting to retrieve param value for keys:" + keys + ", name=" + name);\r
+ } catch (Exception e) {\r
+ msoLogger.debug("getJsonParamValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString());\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * Wrapper to generate the JSONObject to pass to the getJsonValueForKey(JSONObject, String)\r
+ * method so that recursion over the subobjects can be supported there\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param key key to the target value\r
+ * @return String field value associated with key\r
+ */\r
+ public static String getJsonValueForKey(String jsonStr, String key) {\r
+// String isDebugLogEnabled = "true";\r
+ try {\r
+ JSONObject jsonObj = new JSONObject(jsonStr);\r
+ if (jsonObj != null) {\r
+ return getJsonValueForKey(jsonObj, key);\r
+ }\r
+ } catch (Exception e) {\r
+ msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString());\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the\r
+ * single key/field name specified. Returns the associated value if found or null if the key is not found\r
+ *\r
+ * @param jsonObj JSONObject representation of the the JSON doc\r
+ * @param key key to the target value\r
+ * @return String field value associated with key\r
+ */\r
+ public static String getJsonValueForKey(JSONObject jsonObj, String key) {\r
+// String isDebugLogEnabled = "true";\r
+ String keyValue = null;\r
+ try {\r
+ if (jsonObj.has(key)) {\r
+ msoLogger.debug("getJsonValueForKey(): found value for key=" + key);\r
+ return ((String) jsonObj.get(key));\r
+ } else {\r
+ msoLogger.debug("getJsonValueForKey(): iterating over the keys");\r
+ Iterator <String> itr = jsonObj.keys();\r
+ while (itr.hasNext()) {\r
+ String nextKey = (String) itr.next();\r
+ Object obj = jsonObj.get(nextKey);\r
+ if (obj instanceof JSONObject) {\r
+ msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");\r
+ keyValue = getJsonValueForKey((JSONObject) obj, key);\r
+ if (keyValue != null) {\r
+ msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key);\r
+ break;\r
+ }\r
+ } else {\r
+ msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");\r
+ }\r
+ }\r
+ }\r
+ } catch (JSONException je) {\r
+ // JSONObject::get() throws this exception if one of the specified keys is not found\r
+ msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key);\r
+ keyValue = null;\r
+ } catch (Exception e) {\r
+ msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString());\r
+ }\r
+ return keyValue;\r
+ }\r
+ \r
+ /**\r
+ * Walks the JSONObject (and sub-objects recursively), searching for the first value associated with the\r
+ * single key/field name specified. Returns the associated value if found or null if the key is not found\r
+ *\r
+ * @param jsonObj JSONObject representation of the the JSON doc\r
+ * @param key key to the target value\r
+ * @return String field value associated with key\r
+ */\r
+ public static Integer getJsonIntValueForKey(JSONObject jsonObj, String key) {\r
+// String isDebugLogEnabled = "true";\r
+ Integer keyValue = 0;\r
+ try {\r
+ if (jsonObj.has(key)) {\r
+ msoLogger.debug("getJsonValueForKey(): found value for key=" + key);\r
+ return ((Integer) jsonObj.get(key));\r
+ } else {\r
+ msoLogger.debug("getJsonValueForKey(): iterating over the keys");\r
+ Iterator <String> itr = jsonObj.keys();\r
+ while (itr.hasNext()) {\r
+ String nextKey = (String) itr.next();\r
+ Object obj = jsonObj.get(nextKey);\r
+ if (obj instanceof JSONObject) {\r
+ msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", points to JSONObject, recursive call");\r
+ keyValue = getJsonIntValueForKey((JSONObject) obj, key);\r
+ if (keyValue != null) {\r
+ msoLogger.debug("getJsonValueForKey(): found value=" + keyValue + ", for key=" + key);\r
+ break;\r
+ }\r
+ } else {\r
+ msoLogger.debug("getJsonValueForKey(): key=" + nextKey + ", does not point to a JSONObject, next key");\r
+ }\r
+ }\r
+ }\r
+ } catch (JSONException je) {\r
+ // JSONObject::get() throws this exception if one of the specified keys is not found\r
+ msoLogger.debug("getJsonValueForKey(): caught JSONException attempting to retrieve value for key=" + key);\r
+ keyValue = null;\r
+ } catch (Exception e) {\r
+ msoLogger.debug("getJsonValueForKey(): unable to parse json to retrieve value for field=" + key + ". Exception was: " + e.toString());\r
+ }\r
+ return keyValue;\r
+ }\r
+ \r
+ /**\r
+ * Boolean method to determine if a key path is valid for the JSON doc. Invokes\r
+ * getJsonValue().\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."\r
+ * @return Boolean true if keys points to value in the JSON doc\r
+ */\r
+ public static Boolean jsonValueExists(String jsonStr, String keys) {\r
+ if (getJsonRawValue(jsonStr, keys) == null) {\r
+ return false;\r
+ } else {\r
+ return true;\r
+ }\r
+ }\r
+ \r
+ /**\r
+ * Inserts the new key/value pair at the appropriate location in the JSON\r
+ * document after first determining if keyed field already exists. If\r
+ * it does exist, return the JSON unmodified, otherwise return the new JSON\r
+ * Note: this method currently only supports String value inserts.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the value to be added in the format of "key1.key2.key3..."\r
+ * @return String containing the updated JSON doc\r
+ */\r
+ public static String addJsonValue(String jsonStr, String keys, String value) {\r
+// String isDebugLogEnabled = "true";\r
+ // only attempt to insert the key/value pair if it does not exist\r
+ if (!jsonValueExists(jsonStr, keys)) {\r
+ return putJsonValue(jsonStr, keys, value);\r
+ } else {\r
+ msoLogger.debug("addJsonValue(): JSON add failed, key=" + keys + "/value=" + (String) value + " already exists");\r
+ return jsonStr;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Updates the value for the specified key in the JSON document\r
+ * after first determining if keyed field exists. If it does\r
+ * not exist, return the JSON unmodified, otherwise return the updated JSON.\r
+ * Note: this method currently only supports String value updates.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the value to be updated in the format of "key1.key2.key3..."\r
+ * @return String containing the updated JSON doc\r
+ */\r
+ public static String updJsonValue(String jsonStr, String keys, String newValue) {\r
+// String isDebugLogEnabled = "true";\r
+ // only attempt to modify the key/value pair if it exists\r
+ if (jsonValueExists(jsonStr, keys)) {\r
+ return putJsonValue(jsonStr, keys, newValue);\r
+ } else {\r
+ msoLogger.debug("updJsonValue(): JSON update failed, no value exists for key=" + keys);\r
+ return jsonStr;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Deletes the value for the specified key in the JSON document\r
+ * after first determining if keyed field exists. If it does\r
+ * not exist, return the JSON unmodified, otherwise return the updated JSON\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."\r
+ * @return String containing the updated JSON doc\r
+ */\r
+ public static String delJsonValue(String jsonStr, String keys) {\r
+// String isDebugLogEnabled = "true";\r
+ // only attempt to remove the key/value pair if it exists\r
+ if (jsonValueExists(jsonStr, keys)) {\r
+ // passing a null value results in a delete\r
+ return putJsonValue(jsonStr, keys, null);\r
+ } else {\r
+ msoLogger.debug("delJsonValue(): JSON delete failed, no value exists for key=" + keys);\r
+ return jsonStr;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Walks the JSON doc using the full key path to retrieve the associated\r
+ * value. All but the last key points to the 'parent' object name(s) in order\r
+ * in the JSON hierarchy with the last key pointing to the target value.\r
+ * The value returned is a Java object.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."\r
+ * @return Object field value associated with keys\r
+ */\r
+ private static Object getJsonRawValue(String jsonStr, String keys) {\r
+ return getJsonRawValue(jsonStr, keys, false);\r
+ } \r
+\r
+ /**\r
+ * Walks the JSON doc using the full key path to retrieve the associated\r
+ * value. All but the last key points to the 'parent' object name(s) in order\r
+ * in the JSON hierarchy with the last key pointing to the target value.\r
+ * The value returned is a Java object.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."\r
+ * * @param wrap Boolean which determines if returned JSONObjects sould be "wrapped"\r
+ * Note: wrap does not apply to returned scalar values \r
+ * @return Object field value associated with keys\r
+ */\r
+ private static Object getJsonRawValue(String jsonStr, String keys, Boolean wrap) {\r
+// String isDebugLogEnabled = "true";\r
+ String keyStr = "";\r
+ try {\r
+ JSONObject jsonObj = new JSONObject(jsonStr);\r
+ StringTokenizer keyTokens = new StringTokenizer(keys, ".");\r
+ while (keyTokens.hasMoreElements()) {\r
+ keyStr = keyTokens.nextToken();\r
+ Object keyValue = jsonObj.get(keyStr);\r
+ if (keyValue instanceof JSONObject) {\r
+ msoLogger.debug("getJsonRawValue(): key=" + keyStr + " points to json object");\r
+ jsonObj = (JSONObject) keyValue;\r
+ } else {\r
+ if (keyTokens.hasMoreElements()) {\r
+ msoLogger.debug("getJsonRawValue(): value found prior to last key for key=" + keyStr);\r
+ }\r
+ return keyValue;\r
+ }\r
+ }\r
+ // return the json 'node' that the key points to\r
+ // note: since this is a json object and not a scalar value,\r
+ // use the wrap flag to determine if the object should\r
+ // be wrapped with a root node value\r
+ // (the last key in the keys String)\r
+ if (wrap) {\r
+ JSONObject wrappedJsonObj = new JSONObject();\r
+ wrappedJsonObj.put(keyStr, jsonObj);\r
+ return wrappedJsonObj.toString();\r
+ } else {\r
+ return jsonObj.toString();\r
+ }\r
+\r
+ } catch (JSONException je) {\r
+ // JSONObject::get() throws this exception if one of the specified keys is not found\r
+ msoLogger.debug("getJsonRawValue(): caught JSONException attempting to retrieve raw value for key=" + keyStr);\r
+ } catch (Exception e) {\r
+ msoLogger.debug("getJsonRawValue(): unable to parse json to retrieve value for field=" + keys + ". Exception was: " + e.toString());\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * Private method invoked by the public add, update, and delete methods.\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the value to be deleted in the format of "key1.key2.key3..."\r
+ * @return String containing the updated JSON doc\r
+ */\r
+ private static String putJsonValue(String jsonStr, String keys, String value) { \r
+// String isDebugLogEnabled = "true";\r
+ String keyStr = "";\r
+ try {\r
+ JSONObject jsonObj = new JSONObject(jsonStr);\r
+ JSONObject jsonObjOut = jsonObj;\r
+ StringTokenizer keyTokens = new StringTokenizer(keys, ".");\r
+ while (keyTokens.hasMoreElements()) {\r
+ keyStr = keyTokens.nextToken();\r
+ if (keyTokens.hasMoreElements()) {\r
+ Object keyValue = jsonObj.get(keyStr);\r
+ if (keyValue instanceof JSONObject) {\r
+ msoLogger.debug("putJsonValue(): key=" + keyStr + " points to json object");\r
+ jsonObj = (JSONObject) keyValue;\r
+ } else {\r
+ msoLogger.debug("putJsonValue(): key=" + keyStr + " not the last key but points to non-json object: " + (String) keyValue);\r
+ return null;\r
+ }\r
+ } else { // at the last/new key value\r
+ jsonObj.put(keyStr, value);\r
+ return jsonObjOut.toString(3);\r
+ }\r
+ }\r
+ // should not hit this point if the key points to a valid key value\r
+ return null;\r
+ \r
+ } catch (JSONException je) {\r
+ // JSONObject::get() throws this exception if one of the specified keys is not found\r
+ msoLogger.debug("putJsonValue(): caught JSONException attempting to retrieve value for key=" + keyStr);\r
+ return null;\r
+ } catch (Exception e) {\r
+ msoLogger.debug("putJsonValue(): unable to parse json to put value for key=" + keys + ". Exception was: " + e.toString());\r
+ }\r
+ return null;\r
+ }\r
+\r
+ /**\r
+ * This json util method converts a json "Key" and "Value"\r
+ * entry Array to a Java map.\r
+ *\r
+ * @param execution\r
+ * @param entryArray - the json value of the entry Array\r
+ *\r
+ * @return map - a Map containing the entries\r
+ *\r
+ */\r
+ public Map<String, String> entryArrayToMap(Execution execution, String entryArray) {\r
+ msoLogger.debug("Started Entry Array To Map Util Method");\r
+\r
+ Map<String, String> map = new HashMap<String, String>();\r
+\r
+ //Populate Map\r
+ String entryListJson = "{ \"entry\":" + entryArray + "}";\r
+ JSONObject obj = new JSONObject(entryListJson);\r
+ JSONArray arr = obj.getJSONArray("entry");\r
+ for (int i = 0; i < arr.length(); i++){\r
+ JSONObject jo = arr.getJSONObject(i);\r
+ String key = jo.getString("key");\r
+ String value =jo.getString("value");\r
+ map.put(key, value);\r
+ }\r
+ msoLogger.debug("Outgoing Map is: " + map);\r
+ msoLogger.debug("Completed Entry Array To Map Util Method");\r
+ return map;\r
+ }\r
+\r
+\r
+ /**\r
+ * Invokes the getJsonRawValue() method to determine if the\r
+ * json element/variable exist. Returns true if the\r
+ * json element exist\r
+ *\r
+ * @param jsonStr String containing the JSON doc\r
+ * @param keys full key path to the target value in the format of "key1.key2.key3..."\r
+ * @return boolean field value associated with keys\r
+ */\r
+ public static boolean jsonElementExist(String jsonStr, String keys) {\r
+\r
+ try {\r
+ Object rawValue = getJsonRawValue(jsonStr, keys);\r
+ if (rawValue == null) {\r
+ return false;\r
+ } else {\r
+ return true;\r
+ }\r
+ } catch (Exception e) {\r
+ msoLogger.debug("jsonElementExist(): unable to determine if json element exist. Exception is: " + e.toString());\r
+ }\r
+ return true;\r
+ }\r
+\r
+}\r
+\r