1 package org.onap.dmaap.datarouter.provisioning.utils;
3 /*******************************************************************************
4 * ============LICENSE_START==================================================
6 * * ===========================================================================
7 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
8 * * ===========================================================================
9 * * Licensed under the Apache License, Version 2.0 (the "License");
10 * * you may not use this file except in compliance with the License.
11 * * You may obtain a copy of the License at
13 * * http://www.apache.org/licenses/LICENSE-2.0
15 * * Unless required by applicable law or agreed to in writing, software
16 * * distributed under the License is distributed on an "AS IS" BASIS,
17 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * * See the License for the specific language governing permissions and
19 * * limitations under the License.
20 * * ============LICENSE_END====================================================
22 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
24 ******************************************************************************/
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import java.io.IOException;
29 import java.io.StringWriter;
30 import java.io.Writer;
31 import java.lang.reflect.Field;
32 import java.lang.reflect.Method;
33 import java.lang.reflect.Modifier;
36 import org.json.JSONArray;
37 import org.json.JSONException;
38 import org.json.JSONString;
39 import org.json.JSONTokener;
42 * A JSONObject is an unordered collection of name/value pairs. Its external
43 * form is a string wrapped in curly braces with colons between the names and
44 * values, and commas between the values and names. The internal form is an
45 * object having <code>get</code> and <code>opt</code> methods for accessing the
46 * values by name, and <code>put</code> methods for adding or replacing values
47 * by name. The values can be any of these types: <code>Boolean</code>,
48 * <code>JSONArray</code>, <code>JSONObject</code>, <code>Number</code>,
49 * <code>String</code>, or the <code>JSONObject.NULL</code> object. A JSONObject
50 * constructor can be used to convert an external form JSON text into an
51 * internal form whose values can be retrieved with the <code>get</code> and
52 * <code>opt</code> methods, or to convert values into a JSON text using the
53 * <code>put</code> and <code>toString</code> methods. A <code>get</code> method
54 * returns a value if one can be found, and throws an exception if one cannot be
55 * found. An <code>opt</code> method returns a default value instead of throwing
56 * an exception, and so is useful for obtaining optional values.
58 * The generic <code>get()</code> and <code>opt()</code> methods return an
59 * object, which you can cast or query for type. There are also typed
60 * <code>get</code> and <code>opt</code> methods that do type checking and type
61 * coercion for you. The opt methods differ from the get methods in that they do
62 * not throw. Instead, they return a specified value, such as null.
64 * The <code>put</code> methods add or replace values in an object. For example,
67 * myString = new JSONObject().put("JSON", "Hello, World!").toString();
70 * produces the string <code>{"JSON": "Hello, World"}</code>.
72 * The texts produced by the <code>toString</code> methods strictly conform to
73 * the JSON syntax rules. The constructors are more forgiving in the texts they
76 * <li>An extra <code>,</code> <small>(comma)</small> may appear just
77 * before the closing brace.</li>
78 * <li>Strings may be quoted with <code>'</code> <small>(single
79 * quote)</small>.</li>
80 * <li>Strings do not need to be quoted at all if they do not begin with a quote
81 * or single quote, and if they do not contain leading or trailing spaces, and
82 * if they do not contain any of these characters:
83 * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers and
84 * if they are not the reserved words <code>true</code>, <code>false</code>, or
85 * <code>null</code>.</li>
86 * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as by
87 * <code>:</code>.</li>
88 * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as
89 * well as by <code>,</code> <small>(comma)</small>.</li>
95 public class LOGJSONObject {
97 * The maximum number of keys in the key pool.
99 private static final int keyPoolSize = 100;
102 * Key pooling is like string interning, but without permanently tying up
103 * memory. To help conserve memory, storage of duplicated key strings in
104 * JSONObjects will be avoided by using a key pool to manage unique key
105 * string objects. This is used by JSONObject.put(string, object).
107 private static Map<String, Object> keyPool = new LinkedHashMap<String, Object>(keyPoolSize);
109 private static final EELFLogger intlogger = EELFManager.getInstance().getLogger("InternalLog");
112 * JSONObject.NULL is equivalent to the value that JavaScript calls null,
113 * whilst Java's null is equivalent to the value that JavaScript calls
116 private static final class Null {
119 * There is only intended to be a single instance of the NULL object,
120 * so the clone method returns itself.
124 protected final Object clone() {
129 * A Null object is equal to the null value and to itself.
131 * @param object An object to test for nullness.
132 * @return true if the object parameter is the JSONObject.NULL object
135 public boolean equals(Object object) {
136 return object == null || object == this;
140 * Returns a hash code value for the object. This method is
141 * supported for the benefit of hash tables such as those provided by
144 * The general contract of {@code hashCode} is:
146 * <li>Whenever it is invoked on the same object more than once during
147 * an execution of a Java application, the {@code hashCode} method
148 * must consistently return the same integer, provided no information
149 * used in {@code equals} comparisons on the object is modified.
150 * This integer need not remain consistent from one execution of an
151 * application to another execution of the same application.
152 * <li>If two objects are equal according to the {@code equals(Object)}
153 * method, then calling the {@code hashCode} method on each of
154 * the two objects must produce the same integer result.
155 * <li>It is <em>not</em> required that if two objects are unequal
156 * according to the {@link Object#equals(Object)}
157 * method, then calling the {@code hashCode} method on each of the
158 * two objects must produce distinct integer results. However, the
159 * programmer should be aware that producing distinct integer results
160 * for unequal objects may improve the performance of hash tables.
163 * As much as is reasonably practical, the hashCode method defined by
164 * class {@code Object} does return distinct integers for distinct
165 * objects. (This is typically implemented by converting the internal
166 * address of the object into an integer, but this implementation
167 * technique is not required by the
168 * Java™ programming language.)
170 * @return a hash code value for this object.
171 * @see Object#equals(Object)
172 * @see System#identityHashCode
175 public int hashCode() {
176 return super.hashCode();
180 * Get the "null" string value.
182 * @return The string "null".
184 public String toString() {
191 * The map where the JSONObject's properties are kept.
193 private final Map<String, Object> map;
197 * It is sometimes more convenient and less ambiguous to have a
198 * <code>NULL</code> object than to use Java's <code>null</code> value.
199 * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
200 * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
202 public static final Object NULL = new Null();
206 * Construct an empty JSONObject.
208 public LOGJSONObject() {
209 this.map = new LinkedHashMap<>();
214 * Construct a JSONObject from a subset of another JSONObject.
215 * An array of strings is used to identify the keys that should be copied.
216 * Missing keys are ignored.
218 * @param jo A JSONObject.
219 * @param names An array of strings.
221 public LOGJSONObject(LOGJSONObject jo, String[] names) {
223 for (int i = 0; i < names.length; i += 1) {
225 this.putOnce(names[i], jo.opt(names[i]));
226 } catch (Exception ignore) {
227 intlogger.error("PROV0001 LOGJSONObject: " + ignore.getMessage(), ignore);
234 * Construct a JSONObject from a JSONTokener.
236 * @param x A JSONTokener object containing the source string.
237 * @throws JSONException If there is a syntax error in the source string
238 * or a duplicated key.
240 public LOGJSONObject(JSONTokener x) {
245 if (x.nextClean() != '{') {
246 throw x.syntaxError("A JSONObject text must begin with '{'");
252 throw x.syntaxError("A JSONObject text must end with '}'");
257 key = x.nextValue().toString();
260 // The key is followed by ':'. We will also tolerate '=' or '=>'.
264 if (x.next() != '>') {
267 } else if (c != ':') {
268 throw x.syntaxError("Expected a ':' after a key");
270 this.putOnce(key, x.nextValue());
272 // Pairs are separated by ','. We will also tolerate ';'.
274 switch (x.nextClean()) {
277 if (x.nextClean() == '}') {
285 throw x.syntaxError("Expected a ',' or '}'");
292 * Construct a JSONObject from a Map.
294 * @param map A map object that can be used to initialize the contents of
296 * @throws JSONException
298 public LOGJSONObject(Map<String, Object> map) {
299 this.map = new LinkedHashMap<String, Object>();
301 Iterator<Map.Entry<String, Object>> i = map.entrySet().iterator();
302 while (i.hasNext()) {
303 Map.Entry<String, Object> e = i.next();
304 Object value = e.getValue();
306 this.map.put(e.getKey(), wrap(value));
314 * Construct a JSONObject from an Object using bean getters.
315 * It reflects on all of the public methods of the object.
316 * For each of the methods with no parameters and a name starting
317 * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter,
318 * the method is invoked, and a key and the value returned from the getter method
319 * are put into the new JSONObject.
321 * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix.
322 * If the second remaining character is not upper case, then the first
323 * character is converted to lower case.
325 * For example, if an object has a method named <code>"getName"</code>, and
326 * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>,
327 * then the JSONObject will contain <code>"name": "Larry Fine"</code>.
329 * @param bean An object that has getter methods that should be used
330 * to make a JSONObject.
332 public LOGJSONObject(Object bean) {
334 this.populateMap(bean);
339 * Construct a JSONObject from an Object, using reflection to find the
340 * public members. The resulting JSONObject's keys will be the strings
341 * from the names array, and the values will be the field values associated
342 * with those keys in the object. If a key is not found or not visible,
343 * then it will not be copied into the new JSONObject.
345 * @param object An object that has fields that should be used to make a
347 * @param names An array of strings, the names of the fields to be obtained
350 public LOGJSONObject(Object object, String names[]) {
352 Class<? extends Object> c = object.getClass();
353 for (int i = 0; i < names.length; i += 1) {
354 String name = names[i];
356 this.putOpt(name, c.getField(name).get(object));
357 } catch (Exception ignore) {
364 * Construct a JSONObject from a source JSON text string.
365 * This is the most commonly used JSONObject constructor.
367 * @param source A string beginning
368 * with <code>{</code> <small>(left brace)</small> and ending
369 * with <code>}</code> <small>(right brace)</small>.
370 * @throws JSONException If there is a syntax error in the source
371 * string or a duplicated key.
373 public LOGJSONObject(String source) throws JSONException {
374 this(new JSONTokener(source));
379 * Construct a JSONObject from a ResourceBundle.
381 * @param baseName The ResourceBundle base name.
382 * @param locale The Locale to load the ResourceBundle for.
383 * @throws JSONException If any JSONExceptions are detected.
385 public LOGJSONObject(String baseName, Locale locale) throws JSONException {
387 ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
388 Thread.currentThread().getContextClassLoader());
390 // Iterate through the keys in the bundle.
392 Enumeration<?> keys = bundle.getKeys();
393 while (keys.hasMoreElements()) {
394 Object key = keys.nextElement();
395 if (key instanceof String) {
397 // Go through the path, ensuring that there is a nested JSONObject for each
398 // segment except the last. Add the value using the last segment's name into
399 // the deepest nested JSONObject.
401 String[] path = ((String) key).split("\\.");
402 int last = path.length - 1;
403 LOGJSONObject target = this;
404 for (int i = 0; i < last; i += 1) {
405 String segment = path[i];
406 LOGJSONObject nextTarget = target.optJSONObject(segment);
407 if (nextTarget == null) {
408 nextTarget = new LOGJSONObject();
409 target.put(segment, nextTarget);
413 target.put(path[last], bundle.getString((String) key));
420 * Accumulate values under a key. It is similar to the put method except
421 * that if there is already an object stored under the key then a
422 * JSONArray is stored under the key to hold all of the accumulated values.
423 * If there is already a JSONArray, then the new value is appended to it.
424 * In contrast, the put method replaces the previous value.
426 * If only one value is accumulated that is not a JSONArray, then the
427 * result will be the same as using put. But if multiple values are
428 * accumulated, then the result will be like append.
430 * @param key A key string.
431 * @param value An object to be accumulated under the key.
433 * @throws JSONException If the value is an invalid number
434 * or if the key is null.
436 public LOGJSONObject accumulate(
439 ) throws JSONException {
441 Object object = this.opt(key);
442 if (object == null) {
443 this.put(key, value instanceof JSONArray
444 ? new JSONArray().put(value)
446 } else if (object instanceof JSONArray) {
447 ((JSONArray) object).put(value);
449 this.put(key, new JSONArray().put(object).put(value));
456 * Append values to the array under a key. If the key does not exist in the
457 * JSONObject, then the key is put in the JSONObject with its value being a
458 * JSONArray containing the value parameter. If the key was already
459 * associated with a JSONArray, then the value parameter is appended to it.
461 * @param key A key string.
462 * @param value An object to be accumulated under the key.
464 * @throws JSONException If the key is null or if the current value
465 * associated with the key is not a JSONArray.
467 public LOGJSONObject append(String key, Object value) throws JSONException {
469 Object object = this.opt(key);
470 if (object == null) {
471 this.put(key, new JSONArray().put(value));
472 } else if (object instanceof JSONArray) {
473 this.put(key, ((JSONArray) object).put(value));
475 throw new JSONException("JSONObject[" + key +
476 "] is not a JSONArray.");
483 * Produce a string from a double. The string "null" will be returned if
484 * the number is not finite.
489 public static String doubleToString(double d) {
490 if (Double.isInfinite(d) || Double.isNaN(d)) {
494 // Shave off trailing zeros and decimal point, if possible.
496 String string = Double.toString(d);
497 if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
498 string.indexOf('E') < 0) {
499 while (string.endsWith("0")) {
500 string = string.substring(0, string.length() - 1);
502 if (string.endsWith(".")) {
503 string = string.substring(0, string.length() - 1);
511 * Get the value object associated with a key.
513 * @param key A key string.
514 * @return The object associated with the key.
515 * @throws JSONException if the key is not found.
517 public Object get(String key) throws JSONException {
519 throw new JSONException("Null key.");
521 Object object = this.opt(key);
522 if (object == null) {
523 throw new JSONException("JSONObject[" + quote(key) +
531 * Get the boolean value associated with a key.
533 * @param key A key string.
535 * @throws JSONException if the value is not a Boolean or the String "true" or "false".
537 public boolean getBoolean(String key) throws JSONException {
538 Object object = this.get(key);
539 if (object.equals(Boolean.FALSE) ||
540 (object instanceof String &&
541 ((String) object).equalsIgnoreCase("false"))) {
543 } else if (object.equals(Boolean.TRUE) ||
544 (object instanceof String &&
545 ((String) object).equalsIgnoreCase("true"))) {
548 throw new JSONException("JSONObject[" + quote(key) +
549 "] is not a Boolean.");
554 * Get the double value associated with a key.
556 * @param key A key string.
557 * @return The numeric value.
558 * @throws JSONException if the key is not found or
559 * if the value is not a Number object and cannot be converted to a number.
561 public double getDouble(String key) {
562 Object object = this.get(key);
564 return object instanceof Number
565 ? ((Number) object).doubleValue()
566 : Double.parseDouble((String) object);
567 } catch (Exception e) {
568 intlogger.error("JSONObject[" + quote(key) + "] is not a number.", e);
569 throw new JSONException("JSONObject[" + quote(key) + "] is not a number.");
575 * Get the int value associated with a key.
577 * @param key A key string.
578 * @return The integer value.
579 * @throws JSONException if the key is not found or if the value cannot
580 * be converted to an integer.
582 public int getInt(String key) {
583 Object object = this.get(key);
585 return object instanceof Number
586 ? ((Number) object).intValue()
587 : Integer.parseInt((String) object);
588 } catch (Exception e) {
589 intlogger.error("JSONObject[" + quote(key) + "] is not an int.", e);
590 throw new JSONException("JSONObject[" + quote(key) + "] is not an int.");
596 * Get the JSONArray value associated with a key.
598 * @param key A key string.
599 * @return A JSONArray which is the value.
600 * @throws JSONException if the key is not found or
601 * if the value is not a JSONArray.
603 public JSONArray getJSONArray(String key) throws JSONException {
604 Object object = this.get(key);
605 if (object instanceof JSONArray) {
606 return (JSONArray) object;
608 throw new JSONException("JSONObject[" + quote(key) +
609 "] is not a JSONArray.");
614 * Get the JSONObject value associated with a key.
616 * @param key A key string.
617 * @return A JSONObject which is the value.
618 * @throws JSONException if the key is not found or
619 * if the value is not a JSONObject.
621 public LOGJSONObject getJSONObject(String key) throws JSONException {
622 Object object = this.get(key);
623 if (object instanceof LOGJSONObject) {
624 return (LOGJSONObject) object;
626 throw new JSONException("JSONObject[" + quote(key) +
627 "] is not a JSONObject.");
632 * Get the long value associated with a key.
634 * @param key A key string.
635 * @return The long value.
636 * @throws JSONException if the key is not found or if the value cannot
637 * be converted to a long.
639 public long getLong(String key) throws JSONException {
640 Object object = this.get(key);
642 return object instanceof Number
643 ? ((Number) object).longValue()
644 : Long.parseLong((String) object);
645 } catch (Exception e) {
646 intlogger.error("JSONObject[" + quote(key) + "] is not a long.", e);
647 throw new JSONException("JSONObject[" + quote(key) + "] is not a long.");
653 * Get an array of field names from a JSONObject.
655 * @return An array of field names, or null if there are no names.
657 public static String[] getNames(LOGJSONObject jo) {
658 int length = jo.length();
662 Iterator<String> iterator = jo.keys();
663 String[] names = new String[length];
665 while (iterator.hasNext()) {
666 names[i] = iterator.next();
674 * Get an array of field names from an Object.
676 * @return An array of field names, or null if there are no names.
678 public static String[] getNames(Object object) {
679 if (object == null) {
682 Class<? extends Object> klass = object.getClass();
683 Field[] fields = klass.getFields();
684 int length = fields.length;
688 String[] names = new String[length];
689 for (int i = 0; i < length; i += 1) {
690 names[i] = fields[i].getName();
697 * Get the string associated with a key.
699 * @param key A key string.
700 * @return A string which is the value.
701 * @throws JSONException if there is no string value for the key.
703 public String getString(String key) {
704 Object object = this.get(key);
705 if (object instanceof String) {
706 return (String) object;
708 throw new JSONException("JSONObject[" + quote(key) +
714 * Determine if the JSONObject contains a specific key.
716 * @param key A key string.
717 * @return true if the key exists in the JSONObject.
719 public boolean has(String key) {
720 return this.map.containsKey(key);
725 * Increment a property of a JSONObject. If there is no such property,
726 * create one with a value of 1. If there is such a property, and if
727 * it is an Integer, Long, Double, or Float, then add one to it.
729 * @param key A key string.
731 * @throws JSONException If there is already a property with this name
732 * that is not an Integer, Long, Double, or Float.
734 public LOGJSONObject increment(String key) {
735 Object value = this.opt(key);
738 } else if (value instanceof Integer) {
739 this.put(key, ((Integer) value).intValue() + 1);
740 } else if (value instanceof Long) {
741 this.put(key, ((Long) value).longValue() + 1);
742 } else if (value instanceof Double) {
743 this.put(key, ((Double) value).doubleValue() + 1);
744 } else if (value instanceof Float) {
745 this.put(key, ((Float) value).floatValue() + 1);
747 throw new JSONException("Unable to increment [" + quote(key) + "].");
754 * Determine if the value associated with the key is null or if there is
757 * @param key A key string.
758 * @return true if there is no value associated with the key or if
759 * the value is the JSONObject.NULL object.
761 public boolean isNull(String key) {
762 return LOGJSONObject.NULL.equals(this.opt(key));
767 * Get an enumeration of the keys of the JSONObject.
769 * @return An iterator of the keys.
771 public Iterator<String> keys() {
772 return this.keySet().iterator();
777 * Get a set of keys of the JSONObject.
781 public Set<String> keySet() {
782 return this.map.keySet();
787 * Get the number of keys stored in the JSONObject.
789 * @return The number of keys in the JSONObject.
791 public int length() {
792 return this.map.size();
797 * Produce a JSONArray containing the names of the elements of this
800 * @return A JSONArray containing the key strings, or null if the JSONObject
803 public JSONArray names() {
804 JSONArray ja = new JSONArray();
805 Iterator<String> keys = this.keys();
806 while (keys.hasNext()) {
809 return ja.length() == 0 ? null : ja;
813 * Produce a string from a Number.
815 * @param number A Number
817 * @throws JSONException If n is a non-finite number.
819 public static String numberToString(Number number)
820 throws JSONException {
821 if (number == null) {
822 throw new JSONException("Null pointer");
824 testValidity(number);
826 // Shave off trailing zeros and decimal point, if possible.
828 String string = number.toString();
829 if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
830 string.indexOf('E') < 0) {
831 while (string.endsWith("0")) {
832 string = string.substring(0, string.length() - 1);
834 if (string.endsWith(".")) {
835 string = string.substring(0, string.length() - 1);
843 * Get an optional value associated with a key.
845 * @param key A key string.
846 * @return An object which is the value, or null if there is no value.
848 public Object opt(String key) {
849 return key == null ? null : this.map.get(key);
854 * Get an optional boolean associated with a key.
855 * It returns false if there is no such key, or if the value is not
856 * Boolean.TRUE or the String "true".
858 * @param key A key string.
861 public boolean optBoolean(String key) {
862 return this.optBoolean(key, false);
867 * Get an optional boolean associated with a key.
868 * It returns the defaultValue if there is no such key, or if it is not
869 * a Boolean or the String "true" or "false" (case insensitive).
871 * @param key A key string.
872 * @param defaultValue The default.
875 public boolean optBoolean(String key, boolean defaultValue) {
877 return this.getBoolean(key);
878 } catch (Exception e) {
879 intlogger.trace("Using defaultValue: " + defaultValue, e);
886 * Get an optional double associated with a key,
887 * or NaN if there is no such key or if its value is not a number.
888 * If the value is a string, an attempt will be made to evaluate it as
891 * @param key A string which is the key.
892 * @return An object which is the value.
894 public double optDouble(String key) {
895 return this.optDouble(key, Double.NaN);
900 * Get an optional double associated with a key, or the
901 * defaultValue if there is no such key or if its value is not a number.
902 * If the value is a string, an attempt will be made to evaluate it as
905 * @param key A key string.
906 * @param defaultValue The default.
907 * @return An object which is the value.
909 public double optDouble(String key, double defaultValue) {
911 return this.getDouble(key);
912 } catch (Exception e) {
913 intlogger.trace("Using defaultValue: " + defaultValue, e);
920 * Get an optional int value associated with a key,
921 * or zero if there is no such key or if the value is not a number.
922 * If the value is a string, an attempt will be made to evaluate it as
925 * @param key A key string.
926 * @return An object which is the value.
928 public int optInt(String key) {
929 return this.optInt(key, 0);
934 * Get an optional int value associated with a key,
935 * or the default if there is no such key or if the value is not a number.
936 * If the value is a string, an attempt will be made to evaluate it as
939 * @param key A key string.
940 * @param defaultValue The default.
941 * @return An object which is the value.
943 public int optInt(String key, int defaultValue) {
945 return this.getInt(key);
946 } catch (Exception e) {
947 intlogger.trace("Using defaultValue: " + defaultValue, e);
954 * Get an optional JSONArray associated with a key.
955 * It returns null if there is no such key, or if its value is not a
958 * @param key A key string.
959 * @return A JSONArray which is the value.
961 public JSONArray optJSONArray(String key) {
962 Object o = this.opt(key);
963 return o instanceof JSONArray ? (JSONArray) o : null;
968 * Get an optional JSONObject associated with a key.
969 * It returns null if there is no such key, or if its value is not a
972 * @param key A key string.
973 * @return A JSONObject which is the value.
975 public LOGJSONObject optJSONObject(String key) {
976 Object object = this.opt(key);
977 return object instanceof LOGJSONObject ? (LOGJSONObject) object : null;
982 * Get an optional long value associated with a key,
983 * or zero if there is no such key or if the value is not a number.
984 * If the value is a string, an attempt will be made to evaluate it as
987 * @param key A key string.
988 * @return An object which is the value.
990 public long optLong(String key) {
991 return this.optLong(key, 0);
996 * Get an optional long value associated with a key,
997 * or the default if there is no such key or if the value is not a number.
998 * If the value is a string, an attempt will be made to evaluate it as
1001 * @param key A key string.
1002 * @param defaultValue The default.
1003 * @return An object which is the value.
1005 public long optLong(String key, long defaultValue) {
1007 return this.getLong(key);
1008 } catch (Exception e) {
1009 return defaultValue;
1015 * Get an optional string associated with a key.
1016 * It returns an empty string if there is no such key. If the value is not
1017 * a string and is not null, then it is converted to a string.
1019 * @param key A key string.
1020 * @return A string which is the value.
1022 public String optString(String key) {
1023 return this.optString(key, "");
1028 * Get an optional string associated with a key.
1029 * It returns the defaultValue if there is no such key.
1031 * @param key A key string.
1032 * @param defaultValue The default.
1033 * @return A string which is the value.
1035 public String optString(String key, String defaultValue) {
1036 Object object = this.opt(key);
1037 return NULL.equals(object) ? defaultValue : object.toString();
1041 private void populateMap(Object bean) {
1042 Class<? extends Object> klass = bean.getClass();
1044 // If klass is a System class then set includeSuperClass to false.
1046 boolean includeSuperClass = klass.getClassLoader() != null;
1048 Method[] methods = includeSuperClass
1049 ? klass.getMethods()
1050 : klass.getDeclaredMethods();
1051 for (int i = 0; i < methods.length; i += 1) {
1053 Method method = methods[i];
1054 if (Modifier.isPublic(method.getModifiers())) {
1055 String name = method.getName();
1057 if (name.startsWith("get")) {
1058 if ("getClass".equals(name) ||
1059 "getDeclaringClass".equals(name)) {
1062 key = name.substring(3);
1064 } else if (name.startsWith("is")) {
1065 key = name.substring(2);
1067 if (key.length() > 0 &&
1068 Character.isUpperCase(key.charAt(0)) &&
1069 method.getParameterTypes().length == 0) {
1070 if (key.length() == 1) {
1071 key = key.toLowerCase();
1072 } else if (!Character.isUpperCase(key.charAt(1))) {
1073 key = key.substring(0, 1).toLowerCase() +
1077 Object result = method.invoke(bean, (Object[]) null);
1078 if (result != null) {
1079 this.map.put(key, wrap(result));
1083 } catch (Exception ignore) {
1084 intlogger.trace("populateMap: " + ignore.getMessage(), ignore);
1091 * Put a key/boolean pair in the JSONObject.
1093 * @param key A key string.
1094 * @param value A boolean which is the value.
1096 * @throws JSONException If the key is null.
1098 public LOGJSONObject put(String key, boolean value) throws JSONException {
1099 this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
1105 * Put a key/value pair in the JSONObject, where the value will be a
1106 * JSONArray which is produced from a Collection.
1108 * @param key A key string.
1109 * @param value A Collection value.
1111 * @throws JSONException
1113 public LOGJSONObject put(String key, Collection<Object> value) throws JSONException {
1114 this.put(key, new JSONArray(value));
1120 * Put a key/double pair in the JSONObject.
1122 * @param key A key string.
1123 * @param value A double which is the value.
1125 * @throws JSONException If the key is null or if the number is invalid.
1127 public LOGJSONObject put(String key, double value) throws JSONException {
1128 this.put(key, new Double(value));
1134 * Put a key/int pair in the JSONObject.
1136 * @param key A key string.
1137 * @param value An int which is the value.
1139 * @throws JSONException If the key is null.
1141 public LOGJSONObject put(String key, int value) throws JSONException {
1142 this.put(key, new Integer(value));
1148 * Put a key/long pair in the JSONObject.
1150 * @param key A key string.
1151 * @param value A long which is the value.
1153 * @throws JSONException If the key is null.
1155 public LOGJSONObject put(String key, long value) throws JSONException {
1156 this.put(key, new Long(value));
1162 * Put a key/value pair in the JSONObject, where the value will be a
1163 * JSONObject which is produced from a Map.
1165 * @param key A key string.
1166 * @param value A Map value.
1168 * @throws JSONException
1170 public LOGJSONObject put(String key, Map<String, Object> value) throws JSONException {
1171 this.put(key, new LOGJSONObject(value));
1177 * Put a key/value pair in the JSONObject. If the value is null,
1178 * then the key will be removed from the JSONObject if it is present.
1180 * @param key A key string.
1181 * @param value An object which is the value. It should be of one of these
1182 * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
1183 * or the JSONObject.NULL object.
1185 * @throws JSONException If the value is non-finite number
1186 * or if the key is null.
1188 public LOGJSONObject put(String key, Object value) throws JSONException {
1191 throw new JSONException("Null key.");
1193 if (value != null) {
1194 testValidity(value);
1195 pooled = (String) keyPool.get(key);
1196 if (pooled == null) {
1197 if (keyPool.size() >= keyPoolSize) {
1198 keyPool = new LinkedHashMap<String, Object>(keyPoolSize);
1200 keyPool.put(key, key);
1204 this.map.put(key, value);
1213 * Put a key/value pair in the JSONObject, but only if the key and the
1214 * value are both non-null, and only if there is not already a member
1220 * @throws JSONException if the key is a duplicate
1222 public LOGJSONObject putOnce(String key, Object value) throws JSONException {
1223 if (key != null && value != null) {
1224 if (this.opt(key) != null) {
1225 throw new JSONException("Duplicate key \"" + key + "\"");
1227 this.put(key, value);
1234 * Put a key/value pair in the JSONObject, but only if the
1235 * key and the value are both non-null.
1237 * @param key A key string.
1238 * @param value An object which is the value. It should be of one of these
1239 * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
1240 * or the JSONObject.NULL object.
1242 * @throws JSONException If the value is a non-finite number.
1244 public LOGJSONObject putOpt(String key, Object value) throws JSONException {
1245 if (key != null && value != null) {
1246 this.put(key, value);
1253 * Produce a string in double quotes with backslash sequences in all the
1254 * right places. A backslash will be inserted within </, producing <\/,
1255 * allowing JSON text to be delivered in HTML. In JSON text, a string
1256 * cannot contain a control character or an unescaped quote or backslash.
1258 * @param string A String
1259 * @return A String correctly formatted for insertion in a JSON text.
1261 public static String quote(String string) {
1262 StringWriter sw = new StringWriter();
1263 synchronized (sw.getBuffer()) {
1265 return quote(string, sw).toString();
1266 } catch (IOException e) {
1267 intlogger.trace("Ignore Exception message: ", e);
1273 public static Writer quote(String string, Writer w) throws IOException {
1274 if (string == null || string.length() == 0) {
1283 int len = string.length();
1286 for (i = 0; i < len; i += 1) {
1288 c = string.charAt(i);
1317 if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
1318 || (c >= '\u2000' && c < '\u2100')) {
1320 hhhh = Integer.toHexString(c);
1321 w.write("0000", 0, 4 - hhhh.length());
1333 * Remove a name and its value, if present.
1335 * @param key The name to be removed.
1336 * @return The value that was associated with the name,
1337 * or null if there was no value.
1339 public Object remove(String key) {
1340 return this.map.remove(key);
1344 * Try to convert a string into a number, boolean, or null. If the string
1345 * can't be converted, return the string.
1347 * @param string A String.
1348 * @return A simple JSON value.
1350 public static Object stringToValue(String string) {
1352 if (string.equals("")) {
1355 if (string.equalsIgnoreCase("true")) {
1356 return Boolean.TRUE;
1358 if (string.equalsIgnoreCase("false")) {
1359 return Boolean.FALSE;
1361 if (string.equalsIgnoreCase("null")) {
1362 return LOGJSONObject.NULL;
1366 * If it might be a number, try converting it.
1367 * If a number cannot be produced, then the value will just
1368 * be a string. Note that the plus and implied string
1369 * conventions are non-standard. A JSON parser may accept
1370 * non-JSON forms as long as it accepts all correct JSON forms.
1373 char b = string.charAt(0);
1374 if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
1376 if (string.indexOf('.') > -1 ||
1377 string.indexOf('e') > -1 || string.indexOf('E') > -1) {
1378 d = Double.valueOf(string);
1379 if (!d.isInfinite() && !d.isNaN()) {
1383 Long myLong = new Long(string);
1384 if (myLong.longValue() == myLong.intValue()) {
1385 return new Integer(myLong.intValue());
1390 } catch (Exception e) {
1391 intlogger.trace("Ignore Exception message: ", e);
1399 * Throw an exception if the object is a NaN or infinite number.
1401 * @param o The object to test.
1402 * @throws JSONException If o is a non-finite number.
1404 public static void testValidity(Object o) {
1406 if (o instanceof Double) {
1407 if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
1408 throw new JSONException(
1409 "JSON does not allow non-finite numbers.");
1411 } else if (o instanceof Float) {
1412 if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
1413 throw new JSONException(
1414 "JSON does not allow non-finite numbers.");
1422 * Produce a JSONArray containing the values of the members of this
1425 * @param names A JSONArray containing a list of key strings. This
1426 * determines the sequence of the values in the result.
1427 * @return A JSONArray of values.
1428 * @throws JSONException If any of the values are non-finite numbers.
1430 public JSONArray toJSONArray(JSONArray names) throws JSONException {
1431 if (names == null || names.length() == 0) {
1434 JSONArray ja = new JSONArray();
1435 for (int i = 0; i < names.length(); i += 1) {
1436 ja.put(this.opt(names.getString(i)));
1442 * Make a JSON text of this JSONObject. For compactness, no whitespace
1443 * is added. If this would not result in a syntactically correct JSON text,
1444 * then null will be returned instead.
1446 * Warning: This method assumes that the data structure is acyclical.
1448 * @return a printable, displayable, portable, transmittable
1449 * representation of the object, beginning
1450 * with <code>{</code> <small>(left brace)</small> and ending
1451 * with <code>}</code> <small>(right brace)</small>.
1453 public String toString() {
1455 return this.toString(0);
1456 } catch (Exception e) {
1457 intlogger.trace("Exception: ", e);
1464 * Make a prettyprinted JSON text of this JSONObject.
1466 * Warning: This method assumes that the data structure is acyclical.
1468 * @param indentFactor The number of spaces to add to each level of
1470 * @return a printable, displayable, portable, transmittable
1471 * representation of the object, beginning
1472 * with <code>{</code> <small>(left brace)</small> and ending
1473 * with <code>}</code> <small>(right brace)</small>.
1474 * @throws JSONException If the object contains an invalid number.
1476 public String toString(int indentFactor) throws JSONException {
1477 StringWriter w = new StringWriter();
1478 synchronized (w.getBuffer()) {
1479 return this.write(w, indentFactor, 0).toString();
1484 * Make a JSON text of an Object value. If the object has an
1485 * value.toJSONString() method, then that method will be used to produce
1486 * the JSON text. The method is required to produce a strictly
1487 * conforming text. If the object does not contain a toJSONString
1488 * method (which is the most common case), then a text will be
1489 * produced by other means. If the value is an array or Collection,
1490 * then a JSONArray will be made from it and its toJSONString method
1491 * will be called. If the value is a MAP, then a JSONObject will be made
1492 * from it and its toJSONString method will be called. Otherwise, the
1493 * value's toString method will be called, and the result will be quoted.
1496 * Warning: This method assumes that the data structure is acyclical.
1498 * @param value The value to be serialized.
1499 * @return a printable, displayable, transmittable
1500 * representation of the object, beginning
1501 * with <code>{</code> <small>(left brace)</small> and ending
1502 * with <code>}</code> <small>(right brace)</small>.
1503 * @throws JSONException If the value is or contains an invalid number.
1505 @SuppressWarnings("unchecked")
1506 public static String valueToString(Object value) throws JSONException {
1507 if (value == null) {
1510 if (value instanceof JSONString) {
1513 object = ((JSONString) value).toJSONString();
1514 } catch (Exception e) {
1515 throw new JSONException(e);
1517 if (object instanceof String) {
1518 return (String) object;
1520 throw new JSONException("Bad value from toJSONString: " + object);
1522 if (value instanceof Number) {
1523 return numberToString((Number) value);
1525 if (value instanceof Boolean || value instanceof LOGJSONObject ||
1526 value instanceof JSONArray) {
1527 return value.toString();
1529 if (value instanceof Map) {
1530 return new LOGJSONObject((Map<String, Object>) value).toString();
1532 if (value instanceof Collection) {
1533 return new JSONArray((Collection<Object>) value).toString();
1535 if (value.getClass().isArray()) {
1536 return new JSONArray(value).toString();
1538 return quote(value.toString());
1542 * Wrap an object, if necessary. If the object is null, return the NULL
1543 * object. If it is an array or collection, wrap it in a JSONArray. If
1544 * it is a map, wrap it in a JSONObject. If it is a standard property
1545 * (Double, String, et al) then it is already wrapped. Otherwise, if it
1546 * comes from one of the java packages, turn it into a string. And if
1547 * it doesn't, try to wrap it in a JSONObject. If the wrapping fails,
1548 * then null is returned.
1550 * @param object The object to wrap
1551 * @return The wrapped value
1553 @SuppressWarnings("unchecked")
1554 public static Object wrap(Object object) {
1556 if (object == null) {
1559 if (object instanceof LOGJSONObject || object instanceof JSONArray ||
1560 NULL.equals(object) || object instanceof JSONString ||
1561 object instanceof Byte || object instanceof Character ||
1562 object instanceof Short || object instanceof Integer ||
1563 object instanceof Long || object instanceof Boolean ||
1564 object instanceof Float || object instanceof Double ||
1565 object instanceof String) {
1569 if (object instanceof Collection) {
1570 return new JSONArray((Collection<Object>) object);
1572 if (object.getClass().isArray()) {
1573 return new JSONArray(object);
1575 if (object instanceof Map) {
1576 return new LOGJSONObject((Map<String, Object>) object);
1578 Package objectPackage = object.getClass().getPackage();
1579 String objectPackageName = objectPackage != null
1580 ? objectPackage.getName()
1583 objectPackageName.startsWith("java.") ||
1584 objectPackageName.startsWith("javax.") ||
1585 object.getClass().getClassLoader() == null
1587 return object.toString();
1589 return new LOGJSONObject(object);
1590 } catch (Exception exception) {
1591 intlogger.trace("Exception: ", exception);
1598 * Write the contents of the JSONObject as JSON text to a writer.
1599 * For compactness, no whitespace is added.
1601 * Warning: This method assumes that the data structure is acyclical.
1603 * @return The writer.
1604 * @throws JSONException
1606 public Writer write(Writer writer) throws JSONException {
1607 return this.write(writer, 0, 0);
1611 @SuppressWarnings("unchecked")
1612 static final Writer writeValue(Writer writer, Object value,
1613 int indentFactor, int indent) throws JSONException, IOException {
1614 if (value == null) {
1615 writer.write("null");
1616 } else if (value instanceof LOGJSONObject) {
1617 ((LOGJSONObject) value).write(writer, indentFactor, indent);
1618 } else if (value instanceof JSONArray) {
1619 ((JSONArray) value).write(writer, indentFactor, indent);
1620 } else if (value instanceof Map) {
1621 new LOGJSONObject((Map<String, Object>) value).write(writer, indentFactor, indent);
1622 } else if (value instanceof Collection) {
1623 new JSONArray((Collection<Object>) value).write(writer, indentFactor,
1625 } else if (value.getClass().isArray()) {
1626 new JSONArray(value).write(writer, indentFactor, indent);
1627 } else if (value instanceof Number) {
1628 writer.write(numberToString((Number) value));
1629 } else if (value instanceof Boolean) {
1630 writer.write(value.toString());
1631 } else if (value instanceof JSONString) {
1634 o = ((JSONString) value).toJSONString();
1635 } catch (Exception e) {
1636 throw new JSONException(e);
1638 writer.write(o != null ? o.toString() : quote(value.toString()));
1640 quote(value.toString(), writer);
1645 static final void indent(Writer writer, int indent) throws IOException {
1646 for (int i = 0; i < indent; i += 1) {
1652 * Write the contents of the JSONObject as JSON text to a writer. For
1653 * compactness, no whitespace is added.
1655 * Warning: This method assumes that the data structure is acyclical.
1657 * @return The writer.
1658 * @throws JSONException
1660 Writer write(Writer writer, int indentFactor, int indent)
1661 throws JSONException {
1663 boolean commanate = false;
1664 final int length = this.length();
1665 Iterator<String> keys = this.keys();
1669 Object key = keys.next();
1670 writer.write(quote(key.toString()));
1672 if (indentFactor > 0) {
1675 writeValue(writer, this.map.get(key), indentFactor, indent);
1676 } else if (length != 0) {
1677 final int newindent = indent + indentFactor;
1678 while (keys.hasNext()) {
1679 Object key = keys.next();
1683 if (indentFactor > 0) {
1686 indent(writer, newindent);
1687 writer.write(quote(key.toString()));
1689 if (indentFactor > 0) {
1692 writeValue(writer, this.map.get(key), indentFactor,
1696 if (indentFactor > 0) {
1699 indent(writer, indent);
1703 } catch (IOException exception) {
1704 throw new JSONException(exception);