package org.onap.dmaap.datarouter.provisioning.utils;
/*******************************************************************************
* ============LICENSE_START==================================================
* * org.onap.dmaap
* * ===========================================================================
* * Copyright © 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====================================================
* *
* * ECOMP is a trademark and service mark of AT&T Intellectual Property.
* *
******************************************************************************/
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONString;
import org.json.JSONTokener;
/**
* A JSONObject is an unordered collection of name/value pairs. Its external
* form is a string wrapped in curly braces with colons between the names and
* values, and commas between the values and names. The internal form is an
* object having get
and opt
methods for accessing the
* values by name, and put
methods for adding or replacing values
* by name. The values can be any of these types: Boolean
,
* JSONArray
, JSONObject
, Number
,
* String
, or the JSONObject.NULL
object. A JSONObject
* constructor can be used to convert an external form JSON text into an
* internal form whose values can be retrieved with the get
and
* opt
methods, or to convert values into a JSON text using the
* put
and toString
methods. A get
method
* returns a value if one can be found, and throws an exception if one cannot be
* found. An opt
method returns a default value instead of throwing
* an exception, and so is useful for obtaining optional values.
*
* The generic get()
and opt()
methods return an
* object, which you can cast or query for type. There are also typed
* get
and opt
methods that do type checking and type
* coercion for you. The opt methods differ from the get methods in that they do
* not throw. Instead, they return a specified value, such as null.
*
* The put
methods add or replace values in an object. For example,
*
*
* myString = new JSONObject().put("JSON", "Hello, World!").toString(); **
* produces the string {"JSON": "Hello, World"}
.
*
* The texts produced by the toString
methods strictly conform to
* the JSON syntax rules. The constructors are more forgiving in the texts they
* will accept:
*
,
(comma) may appear just
* before the closing brace.'
(single
* quote).{ } [ ] / \ : , = ; #
and if they do not look like numbers and
* if they are not the reserved words true
, false
, or
* null
.=
or =>
as well as by
* :
.;
(semicolon) as
* well as by ,
(comma).* The general contract of {@code hashCode} is: *
* As much as is reasonably practical, the hashCode method defined by
* class {@code Object} does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java™ programming language.)
*
* @return a hash code value for this object.
* @see Object#equals(Object)
* @see System#identityHashCode
*/
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Get the "null" string value.
*
* @return The string "null".
*/
public String toString() {
return "null";
}
}
/**
* The map where the JSONObject's properties are kept.
*/
private final Map
* The key is formed by removing the
* For example, if an object has a method named
* If only one value is accumulated that is not a JSONArray, then the
* result will be the same as using put. But if multiple values are
* accumulated, then the result will be like append.
*
* @param key A key string.
* @param value An object to be accumulated under the key.
* @return this.
* @throws JSONException If the value is an invalid number
* or if the key is null.
*/
public LOGJSONObject accumulate(
String key,
Object value
) {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key, value instanceof JSONArray
? new JSONArray().put(value)
: value);
} else if (object instanceof JSONArray) {
((JSONArray) object).put(value);
} else {
this.put(key, new JSONArray().put(object).put(value));
}
return this;
}
/**
* Append values to the array under a key. If the key does not exist in the
* JSONObject, then the key is put in the JSONObject with its value being a
* JSONArray containing the value parameter. If the key was already
* associated with a JSONArray, then the value parameter is appended to it.
*
* @param key A key string.
* @param value An object to be accumulated under the key.
* @return this.
* @throws JSONException If the key is null or if the current value
* associated with the key is not a JSONArray.
*/
public LOGJSONObject append(String key, Object value) {
testValidity(value);
Object object = this.opt(key);
if (object == null) {
this.put(key, new JSONArray().put(value));
} else if (object instanceof JSONArray) {
this.put(key, ((JSONArray) object).put(value));
} else {
throw new JSONException(JSON_OBJECT_CONST + key +
"] is not a JSONArray.");
}
return this;
}
/**
* Produce a string from a double. The string "null" will be returned if
* the number is not finite.
*
* @param d A double.
* @return A String.
*/
public static String doubleToString(double d) {
if (Double.isInfinite(d) || Double.isNaN(d)) {
return "null";
}
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
/**
* Get the value object associated with a key.
*
* @param key A key string.
* @return The object associated with the key.
* @throws JSONException if the key is not found.
*/
public Object get(String key) {
if (key == null) {
throw new JSONException("Null key.");
}
Object object = this.opt(key);
if (object == null) {
throw new JSONException(JSON_OBJECT_CONST + quote(key) +
"] not found.");
}
return object;
}
/**
* Get the boolean value associated with a key.
*
* @param key A key string.
* @return The truth.
* @throws JSONException if the value is not a Boolean or the String "true" or "false".
*/
public boolean getBoolean(String key) {
Object object = this.get(key);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
"false".equalsIgnoreCase((String) object))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
"true".equalsIgnoreCase((String) object))) {
return true;
}
throw new JSONException(JSON_OBJECT_CONST + quote(key) +
"] is not a Boolean.");
}
/**
* Get the double value associated with a key.
*
* @param key A key string.
* @return The numeric value.
* @throws JSONException if the key is not found or
* if the value is not a Number object and cannot be converted to a number.
*/
public double getDouble(String key) {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number) object).doubleValue()
: Double.parseDouble((String) object);
} catch (Exception e) {
intlogger.error(JSON_OBJECT_CONST + quote(key) + "] is not a number.", e);
throw new JSONException(JSON_OBJECT_CONST + quote(key) + "] is not a number.");
}
}
/**
* Get the int value associated with a key.
*
* @param key A key string.
* @return The integer value.
* @throws JSONException if the key is not found or if the value cannot
* be converted to an integer.
*/
public int getInt(String key) {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number) object).intValue()
: Integer.parseInt((String) object);
} catch (Exception e) {
intlogger.error(JSON_OBJECT_CONST + quote(key) + "] is not an int.", e);
throw new JSONException(JSON_OBJECT_CONST + quote(key) + "] is not an int.");
}
}
/**
* Get the JSONArray value associated with a key.
*
* @param key A key string.
* @return A JSONArray which is the value.
* @throws JSONException if the key is not found or
* if the value is not a JSONArray.
*/
public JSONArray getJSONArray(String key) {
Object object = this.get(key);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
throw new JSONException(JSON_OBJECT_CONST + quote(key) +
"] is not a JSONArray.");
}
/**
* Get the JSONObject value associated with a key.
*
* @param key A key string.
* @return A JSONObject which is the value.
* @throws JSONException if the key is not found or
* if the value is not a JSONObject.
*/
public LOGJSONObject getJSONObject(String key) {
Object object = this.get(key);
if (object instanceof LOGJSONObject) {
return (LOGJSONObject) object;
}
throw new JSONException(JSON_OBJECT_CONST + quote(key) +
"] is not a JSONObject.");
}
/**
* Get the long value associated with a key.
*
* @param key A key string.
* @return The long value.
* @throws JSONException if the key is not found or if the value cannot
* be converted to a long.
*/
public long getLong(String key) {
Object object = this.get(key);
try {
return object instanceof Number
? ((Number) object).longValue()
: Long.parseLong((String) object);
} catch (Exception e) {
intlogger.error(JSON_OBJECT_CONST + quote(key) + "] is not a long.", e);
throw new JSONException(JSON_OBJECT_CONST + quote(key) + "] is not a long.");
}
}
/**
* Get an array of field names from a JSONObject.
*
* @return An array of field names, or null if there are no names.
*/
public static String[] getNames(LOGJSONObject jo) {
int length = jo.length();
if (length == 0) {
return new String[]{};
}
Iterator
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, portable, transmittable
* representation of the object, beginning
* with
* Warning: This method assumes that the data structure is acyclical.
*
* @param indentFactor The number of spaces to add to each level of
* indentation.
* @return a printable, displayable, portable, transmittable
* representation of the object, beginning
* with
* Warning: This method assumes that the data structure is acyclical.
*
* @param value The value to be serialized.
* @return a printable, displayable, transmittable
* representation of the object, beginning
* with NULL
object than to use Java's null
value.
* JSONObject.NULL.equals(null)
returns true
.
* JSONObject.NULL.toString()
returns "null"
.
*/
private static final Object NULL = new Null();
/**
* Construct an empty JSONObject.
*/
public LOGJSONObject() {
this.map = new LinkedHashMap<>();
}
/**
* Construct a JSONObject from a subset of another JSONObject.
* An array of strings is used to identify the keys that should be copied.
* Missing keys are ignored.
*
* @param jo A JSONObject.
* @param names An array of strings.
*/
public LOGJSONObject(LOGJSONObject jo, String[] names) {
this();
for (int i = 0; i < names.length; i += 1) {
try {
this.putOnce(names[i], jo.opt(names[i]));
} catch (Exception ignore) {
intlogger.error("PROV0001 LOGJSONObject: " + ignore.getMessage(), ignore);
}
}
}
/**
* Construct a JSONObject from a JSONTokener.
*
* @param x A JSONTokener object containing the source string.
* @throws JSONException If there is a syntax error in the source string
* or a duplicated key.
*/
public LOGJSONObject(JSONTokener x) {
this();
char c;
String key;
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject text must begin with '{'");
}
for (; ; ) {
c = x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
default:
x.back();
key = x.nextValue().toString();
}
// The key is followed by ':'. We will also tolerate '=' or '=>'.
c = x.nextClean();
if (c == '=') {
if (x.next() != '>') {
x.back();
}
} else if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
this.putOnce(key, x.nextValue());
// Pairs are separated by ','. We will also tolerate ';'.
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == '}') {
return;
}
x.back();
break;
case '}':
return;
default:
throw x.syntaxError("Expected a ',' or '}'");
}
}
}
/**
* Construct a JSONObject from a Map.
*
* @param map A map object that can be used to initialize the contents of
* the JSONObject.
* @throws JSONException
*/
public LOGJSONObject(Map"get"
or "is"
followed by an uppercase letter,
* the method is invoked, and a key and the value returned from the getter method
* are put into the new JSONObject.
* "get"
or "is"
prefix.
* If the second remaining character is not upper case, then the first
* character is converted to lower case.
* "getName"
, and
* if the result of calling object.getName()
is "Larry Fine"
,
* then the JSONObject will contain "name": "Larry Fine"
.
*
* @param bean An object that has getter methods that should be used
* to make a JSONObject.
*/
public LOGJSONObject(Object bean) {
this();
this.populateMap(bean);
}
/**
* Accumulate values under a key. It is similar to the put method except
* that if there is already an object stored under the key then a
* JSONArray is stored under the key to hold all of the accumulated values.
* If there is already a JSONArray, then the new value is appended to it.
* In contrast, the put method replaces the previous value.
* {
(left brace) and ending
* with }
(right brace).
*/
public String toString() {
try {
return this.toString(0);
} catch (Exception e) {
intlogger.trace("Exception: ", e);
return "";
}
}
/**
* Make a prettyprinted JSON text of this JSONObject.
* {
(left brace) and ending
* with }
(right brace).
* @throws JSONException If the object contains an invalid number.
*/
public String toString(int indentFactor) {
StringWriter w = new StringWriter();
synchronized (w.getBuffer()) {
return this.write(w, indentFactor, 0).toString();
}
}
/**
* Make a JSON text of an Object value. If the object has an
* value.toJSONString() method, then that method will be used to produce
* the JSON text. The method is required to produce a strictly
* conforming text. If the object does not contain a toJSONString
* method (which is the most common case), then a text will be
* produced by other means. If the value is an array or Collection,
* then a JSONArray will be made from it and its toJSONString method
* will be called. If the value is a MAP, then a JSONObject will be made
* from it and its toJSONString method will be called. Otherwise, the
* value's toString method will be called, and the result will be quoted.
*
* {
(left brace) and ending
* with }
(right brace).
* @throws JSONException If the value is or contains an invalid number.
*/
@SuppressWarnings("unchecked")
public static String valueToString(Object value) {
if (value == null) {
return "null";
}
if (value instanceof JSONString) {
String object;
try {
object = ((JSONString) value).toJSONString();
} catch (Exception e) {
throw new JSONException(e);
}
if (object != null) {
return object;
}
throw new JSONException("Bad value from toJSONString: " + object);
}
if (value instanceof Number) {
return numberToString((Number) value);
}
if (value instanceof Boolean || value instanceof LOGJSONObject
|| value instanceof JSONArray) {
return value.toString();
}
if (value instanceof Map) {
return new LOGJSONObject((Map