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 java.io.IOException;
27 import java.io.StringWriter;
28 import java.io.Writer;
29 import java.lang.reflect.Field;
30 import java.lang.reflect.Method;
31 import java.lang.reflect.Modifier;
32 import java.util.Collection;
33 import java.util.Enumeration;
34 import java.util.LinkedHashMap;
35 import java.util.Iterator;
36 import java.util.Locale;
38 import java.util.ResourceBundle;
41 import org.json.JSONArray;
42 import org.json.JSONException;
43 import org.json.JSONString;
44 import org.json.JSONTokener;
47 * A JSONObject is an unordered collection of name/value pairs. Its external
48 * form is a string wrapped in curly braces with colons between the names and
49 * values, and commas between the values and names. The internal form is an
50 * object having <code>get</code> and <code>opt</code> methods for accessing the
51 * values by name, and <code>put</code> methods for adding or replacing values
52 * by name. The values can be any of these types: <code>Boolean</code>,
53 * <code>JSONArray</code>, <code>JSONObject</code>, <code>Number</code>,
54 * <code>String</code>, or the <code>JSONObject.NULL</code> object. A JSONObject
55 * constructor can be used to convert an external form JSON text into an
56 * internal form whose values can be retrieved with the <code>get</code> and
57 * <code>opt</code> methods, or to convert values into a JSON text using the
58 * <code>put</code> and <code>toString</code> methods. A <code>get</code> method
59 * returns a value if one can be found, and throws an exception if one cannot be
60 * found. An <code>opt</code> method returns a default value instead of throwing
61 * an exception, and so is useful for obtaining optional values.
63 * The generic <code>get()</code> and <code>opt()</code> methods return an
64 * object, which you can cast or query for type. There are also typed
65 * <code>get</code> and <code>opt</code> methods that do type checking and type
66 * coercion for you. The opt methods differ from the get methods in that they do
67 * not throw. Instead, they return a specified value, such as null.
69 * The <code>put</code> methods add or replace values in an object. For example,
72 * myString = new JSONObject().put("JSON", "Hello, World!").toString();
75 * produces the string <code>{"JSON": "Hello, World"}</code>.
77 * The texts produced by the <code>toString</code> methods strictly conform to
78 * the JSON syntax rules. The constructors are more forgiving in the texts they
81 * <li>An extra <code>,</code> <small>(comma)</small> may appear just
82 * before the closing brace.</li>
83 * <li>Strings may be quoted with <code>'</code> <small>(single
84 * quote)</small>.</li>
85 * <li>Strings do not need to be quoted at all if they do not begin with a quote
86 * or single quote, and if they do not contain leading or trailing spaces, and
87 * if they do not contain any of these characters:
88 * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers and
89 * if they are not the reserved words <code>true</code>, <code>false</code>, or
90 * <code>null</code>.</li>
91 * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as by
92 * <code>:</code>.</li>
93 * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as
94 * well as by <code>,</code> <small>(comma)</small>.</li>
100 public class LOGJSONObject {
102 * The maximum number of keys in the key pool.
104 private static final int keyPoolSize = 100;
107 * Key pooling is like string interning, but without permanently tying up
108 * memory. To help conserve memory, storage of duplicated key strings in
109 * JSONObjects will be avoided by using a key pool to manage unique key
110 * string objects. This is used by JSONObject.put(string, object).
112 private static Map<String, Object> keyPool = new LinkedHashMap<String, Object>(keyPoolSize);
115 * JSONObject.NULL is equivalent to the value that JavaScript calls null,
116 * whilst Java's null is equivalent to the value that JavaScript calls
119 private static final class Null {
122 * There is only intended to be a single instance of the NULL object,
123 * so the clone method returns itself.
127 protected final Object clone() {
132 * A Null object is equal to the null value and to itself.
134 * @param object An object to test for nullness.
135 * @return true if the object parameter is the JSONObject.NULL object
138 public boolean equals(Object object) {
139 return object == null || object == this;
143 * Get the "null" string value.
145 * @return The string "null".
147 public String toString() {
154 * The map where the JSONObject's properties are kept.
156 private final Map<String, Object> map;
160 * It is sometimes more convenient and less ambiguous to have a
161 * <code>NULL</code> object than to use Java's <code>null</code> value.
162 * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
163 * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
165 public static final Object NULL = new Null();
169 * Construct an empty JSONObject.
171 public LOGJSONObject() {
172 this.map = new LinkedHashMap<String, Object>();
177 * Construct a JSONObject from a subset of another JSONObject.
178 * An array of strings is used to identify the keys that should be copied.
179 * Missing keys are ignored.
181 * @param jo A JSONObject.
182 * @param names An array of strings.
183 * @throws JSONException
184 * @throws JSONException If a value is a non-finite number or if a name is duplicated.
186 public LOGJSONObject(LOGJSONObject jo, String[] names) {
188 for (int i = 0; i < names.length; i += 1) {
190 this.putOnce(names[i], jo.opt(names[i]));
191 } catch (Exception ignore) {
198 * Construct a JSONObject from a JSONTokener.
200 * @param x A JSONTokener object containing the source string.
201 * @throws JSONException If there is a syntax error in the source string
202 * or a duplicated key.
204 public LOGJSONObject(JSONTokener x) throws JSONException {
209 if (x.nextClean() != '{') {
210 throw x.syntaxError("A JSONObject text must begin with '{'");
216 throw x.syntaxError("A JSONObject text must end with '}'");
221 key = x.nextValue().toString();
224 // The key is followed by ':'. We will also tolerate '=' or '=>'.
228 if (x.next() != '>') {
231 } else if (c != ':') {
232 throw x.syntaxError("Expected a ':' after a key");
234 this.putOnce(key, x.nextValue());
236 // Pairs are separated by ','. We will also tolerate ';'.
238 switch (x.nextClean()) {
241 if (x.nextClean() == '}') {
249 throw x.syntaxError("Expected a ',' or '}'");
256 * Construct a JSONObject from a Map.
258 * @param map A map object that can be used to initialize the contents of
260 * @throws JSONException
262 public LOGJSONObject(Map<String, Object> map) {
263 this.map = new LinkedHashMap<String, Object>();
265 Iterator<Map.Entry<String, Object>> i = map.entrySet().iterator();
266 while (i.hasNext()) {
267 Map.Entry<String, Object> e = i.next();
268 Object value = e.getValue();
270 this.map.put(e.getKey(), wrap(value));
278 * Construct a JSONObject from an Object using bean getters.
279 * It reflects on all of the public methods of the object.
280 * For each of the methods with no parameters and a name starting
281 * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter,
282 * the method is invoked, and a key and the value returned from the getter method
283 * are put into the new JSONObject.
285 * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix.
286 * If the second remaining character is not upper case, then the first
287 * character is converted to lower case.
289 * For example, if an object has a method named <code>"getName"</code>, and
290 * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>,
291 * then the JSONObject will contain <code>"name": "Larry Fine"</code>.
293 * @param bean An object that has getter methods that should be used
294 * to make a JSONObject.
296 public LOGJSONObject(Object bean) {
298 this.populateMap(bean);
303 * Construct a JSONObject from an Object, using reflection to find the
304 * public members. The resulting JSONObject's keys will be the strings
305 * from the names array, and the values will be the field values associated
306 * with those keys in the object. If a key is not found or not visible,
307 * then it will not be copied into the new JSONObject.
309 * @param object An object that has fields that should be used to make a
311 * @param names An array of strings, the names of the fields to be obtained
314 public LOGJSONObject(Object object, String names[]) {
316 Class<? extends Object> c = object.getClass();
317 for (int i = 0; i < names.length; i += 1) {
318 String name = names[i];
320 this.putOpt(name, c.getField(name).get(object));
321 } catch (Exception ignore) {
328 * Construct a JSONObject from a source JSON text string.
329 * This is the most commonly used JSONObject constructor.
331 * @param source A string beginning
332 * with <code>{</code> <small>(left brace)</small> and ending
333 * with <code>}</code> <small>(right brace)</small>.
334 * @throws JSONException If there is a syntax error in the source
335 * string or a duplicated key.
337 public LOGJSONObject(String source) throws JSONException {
338 this(new JSONTokener(source));
343 * Construct a JSONObject from a ResourceBundle.
345 * @param baseName The ResourceBundle base name.
346 * @param locale The Locale to load the ResourceBundle for.
347 * @throws JSONException If any JSONExceptions are detected.
349 public LOGJSONObject(String baseName, Locale locale) throws JSONException {
351 ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,
352 Thread.currentThread().getContextClassLoader());
354 // Iterate through the keys in the bundle.
356 Enumeration<?> keys = bundle.getKeys();
357 while (keys.hasMoreElements()) {
358 Object key = keys.nextElement();
359 if (key instanceof String) {
361 // Go through the path, ensuring that there is a nested JSONObject for each
362 // segment except the last. Add the value using the last segment's name into
363 // the deepest nested JSONObject.
365 String[] path = ((String) key).split("\\.");
366 int last = path.length - 1;
367 LOGJSONObject target = this;
368 for (int i = 0; i < last; i += 1) {
369 String segment = path[i];
370 LOGJSONObject nextTarget = target.optJSONObject(segment);
371 if (nextTarget == null) {
372 nextTarget = new LOGJSONObject();
373 target.put(segment, nextTarget);
377 target.put(path[last], bundle.getString((String) key));
384 * Accumulate values under a key. It is similar to the put method except
385 * that if there is already an object stored under the key then a
386 * JSONArray is stored under the key to hold all of the accumulated values.
387 * If there is already a JSONArray, then the new value is appended to it.
388 * In contrast, the put method replaces the previous value.
390 * If only one value is accumulated that is not a JSONArray, then the
391 * result will be the same as using put. But if multiple values are
392 * accumulated, then the result will be like append.
394 * @param key A key string.
395 * @param value An object to be accumulated under the key.
397 * @throws JSONException If the value is an invalid number
398 * or if the key is null.
400 public LOGJSONObject accumulate(
403 ) throws JSONException {
405 Object object = this.opt(key);
406 if (object == null) {
407 this.put(key, value instanceof JSONArray
408 ? new JSONArray().put(value)
410 } else if (object instanceof JSONArray) {
411 ((JSONArray) object).put(value);
413 this.put(key, new JSONArray().put(object).put(value));
420 * Append values to the array under a key. If the key does not exist in the
421 * JSONObject, then the key is put in the JSONObject with its value being a
422 * JSONArray containing the value parameter. If the key was already
423 * associated with a JSONArray, then the value parameter is appended to it.
425 * @param key A key string.
426 * @param value An object to be accumulated under the key.
428 * @throws JSONException If the key is null or if the current value
429 * associated with the key is not a JSONArray.
431 public LOGJSONObject append(String key, Object value) throws JSONException {
433 Object object = this.opt(key);
434 if (object == null) {
435 this.put(key, new JSONArray().put(value));
436 } else if (object instanceof JSONArray) {
437 this.put(key, ((JSONArray) object).put(value));
439 throw new JSONException("JSONObject[" + key +
440 "] is not a JSONArray.");
447 * Produce a string from a double. The string "null" will be returned if
448 * the number is not finite.
453 public static String doubleToString(double d) {
454 if (Double.isInfinite(d) || Double.isNaN(d)) {
458 // Shave off trailing zeros and decimal point, if possible.
460 String string = Double.toString(d);
461 if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
462 string.indexOf('E') < 0) {
463 while (string.endsWith("0")) {
464 string = string.substring(0, string.length() - 1);
466 if (string.endsWith(".")) {
467 string = string.substring(0, string.length() - 1);
475 * Get the value object associated with a key.
477 * @param key A key string.
478 * @return The object associated with the key.
479 * @throws JSONException if the key is not found.
481 public Object get(String key) throws JSONException {
483 throw new JSONException("Null key.");
485 Object object = this.opt(key);
486 if (object == null) {
487 throw new JSONException("JSONObject[" + quote(key) +
495 * Get the boolean value associated with a key.
497 * @param key A key string.
499 * @throws JSONException if the value is not a Boolean or the String "true" or "false".
501 public boolean getBoolean(String key) throws JSONException {
502 Object object = this.get(key);
503 if (object.equals(Boolean.FALSE) ||
504 (object instanceof String &&
505 ((String) object).equalsIgnoreCase("false"))) {
507 } else if (object.equals(Boolean.TRUE) ||
508 (object instanceof String &&
509 ((String) object).equalsIgnoreCase("true"))) {
512 throw new JSONException("JSONObject[" + quote(key) +
513 "] is not a Boolean.");
518 * Get the double value associated with a key.
520 * @param key A key string.
521 * @return The numeric value.
522 * @throws JSONException if the key is not found or
523 * if the value is not a Number object and cannot be converted to a number.
525 public double getDouble(String key) throws JSONException {
526 Object object = this.get(key);
528 return object instanceof Number
529 ? ((Number) object).doubleValue()
530 : Double.parseDouble((String) object);
531 } catch (Exception e) {
532 throw new JSONException("JSONObject[" + quote(key) +
533 "] is not a number.");
539 * Get the int value associated with a key.
541 * @param key A key string.
542 * @return The integer value.
543 * @throws JSONException if the key is not found or if the value cannot
544 * be converted to an integer.
546 public int getInt(String key) throws JSONException {
547 Object object = this.get(key);
549 return object instanceof Number
550 ? ((Number) object).intValue()
551 : Integer.parseInt((String) object);
552 } catch (Exception e) {
553 throw new JSONException("JSONObject[" + quote(key) +
560 * Get the JSONArray value associated with a key.
562 * @param key A key string.
563 * @return A JSONArray which is the value.
564 * @throws JSONException if the key is not found or
565 * if the value is not a JSONArray.
567 public JSONArray getJSONArray(String key) throws JSONException {
568 Object object = this.get(key);
569 if (object instanceof JSONArray) {
570 return (JSONArray) object;
572 throw new JSONException("JSONObject[" + quote(key) +
573 "] is not a JSONArray.");
578 * Get the JSONObject value associated with a key.
580 * @param key A key string.
581 * @return A JSONObject which is the value.
582 * @throws JSONException if the key is not found or
583 * if the value is not a JSONObject.
585 public LOGJSONObject getJSONObject(String key) throws JSONException {
586 Object object = this.get(key);
587 if (object instanceof LOGJSONObject) {
588 return (LOGJSONObject) object;
590 throw new JSONException("JSONObject[" + quote(key) +
591 "] is not a JSONObject.");
596 * Get the long value associated with a key.
598 * @param key A key string.
599 * @return The long value.
600 * @throws JSONException if the key is not found or if the value cannot
601 * be converted to a long.
603 public long getLong(String key) throws JSONException {
604 Object object = this.get(key);
606 return object instanceof Number
607 ? ((Number) object).longValue()
608 : Long.parseLong((String) object);
609 } catch (Exception e) {
610 throw new JSONException("JSONObject[" + quote(key) +
617 * Get an array of field names from a JSONObject.
619 * @return An array of field names, or null if there are no names.
621 public static String[] getNames(LOGJSONObject jo) {
622 int length = jo.length();
626 Iterator<String> iterator = jo.keys();
627 String[] names = new String[length];
629 while (iterator.hasNext()) {
630 names[i] = iterator.next();
638 * Get an array of field names from an Object.
640 * @return An array of field names, or null if there are no names.
642 public static String[] getNames(Object object) {
643 if (object == null) {
646 Class<? extends Object> klass = object.getClass();
647 Field[] fields = klass.getFields();
648 int length = fields.length;
652 String[] names = new String[length];
653 for (int i = 0; i < length; i += 1) {
654 names[i] = fields[i].getName();
661 * Get the string associated with a key.
663 * @param key A key string.
664 * @return A string which is the value.
665 * @throws JSONException if there is no string value for the key.
667 public String getString(String key) throws JSONException {
668 Object object = this.get(key);
669 if (object instanceof String) {
670 return (String) object;
672 throw new JSONException("JSONObject[" + quote(key) +
678 * Determine if the JSONObject contains a specific key.
680 * @param key A key string.
681 * @return true if the key exists in the JSONObject.
683 public boolean has(String key) {
684 return this.map.containsKey(key);
689 * Increment a property of a JSONObject. If there is no such property,
690 * create one with a value of 1. If there is such a property, and if
691 * it is an Integer, Long, Double, or Float, then add one to it.
693 * @param key A key string.
695 * @throws JSONException If there is already a property with this name
696 * that is not an Integer, Long, Double, or Float.
698 public LOGJSONObject increment(String key) throws JSONException {
699 Object value = this.opt(key);
702 } else if (value instanceof Integer) {
703 this.put(key, ((Integer) value).intValue() + 1);
704 } else if (value instanceof Long) {
705 this.put(key, ((Long) value).longValue() + 1);
706 } else if (value instanceof Double) {
707 this.put(key, ((Double) value).doubleValue() + 1);
708 } else if (value instanceof Float) {
709 this.put(key, ((Float) value).floatValue() + 1);
711 throw new JSONException("Unable to increment [" + quote(key) + "].");
718 * Determine if the value associated with the key is null or if there is
721 * @param key A key string.
722 * @return true if there is no value associated with the key or if
723 * the value is the JSONObject.NULL object.
725 public boolean isNull(String key) {
726 return LOGJSONObject.NULL.equals(this.opt(key));
731 * Get an enumeration of the keys of the JSONObject.
733 * @return An iterator of the keys.
735 public Iterator<String> keys() {
736 return this.keySet().iterator();
741 * Get a set of keys of the JSONObject.
745 public Set<String> keySet() {
746 return this.map.keySet();
751 * Get the number of keys stored in the JSONObject.
753 * @return The number of keys in the JSONObject.
755 public int length() {
756 return this.map.size();
761 * Produce a JSONArray containing the names of the elements of this
764 * @return A JSONArray containing the key strings, or null if the JSONObject
767 public JSONArray names() {
768 JSONArray ja = new JSONArray();
769 Iterator<String> keys = this.keys();
770 while (keys.hasNext()) {
773 return ja.length() == 0 ? null : ja;
777 * Produce a string from a Number.
779 * @param number A Number
781 * @throws JSONException If n is a non-finite number.
783 public static String numberToString(Number number)
784 throws JSONException {
785 if (number == null) {
786 throw new JSONException("Null pointer");
788 testValidity(number);
790 // Shave off trailing zeros and decimal point, if possible.
792 String string = number.toString();
793 if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
794 string.indexOf('E') < 0) {
795 while (string.endsWith("0")) {
796 string = string.substring(0, string.length() - 1);
798 if (string.endsWith(".")) {
799 string = string.substring(0, string.length() - 1);
807 * Get an optional value associated with a key.
809 * @param key A key string.
810 * @return An object which is the value, or null if there is no value.
812 public Object opt(String key) {
813 return key == null ? null : this.map.get(key);
818 * Get an optional boolean associated with a key.
819 * It returns false if there is no such key, or if the value is not
820 * Boolean.TRUE or the String "true".
822 * @param key A key string.
825 public boolean optBoolean(String key) {
826 return this.optBoolean(key, false);
831 * Get an optional boolean associated with a key.
832 * It returns the defaultValue if there is no such key, or if it is not
833 * a Boolean or the String "true" or "false" (case insensitive).
835 * @param key A key string.
836 * @param defaultValue The default.
839 public boolean optBoolean(String key, boolean defaultValue) {
841 return this.getBoolean(key);
842 } catch (Exception e) {
849 * Get an optional double associated with a key,
850 * or NaN if there is no such key or if its value is not a number.
851 * If the value is a string, an attempt will be made to evaluate it as
854 * @param key A string which is the key.
855 * @return An object which is the value.
857 public double optDouble(String key) {
858 return this.optDouble(key, Double.NaN);
863 * Get an optional double associated with a key, or the
864 * defaultValue if there is no such key or if its value is not a number.
865 * If the value is a string, an attempt will be made to evaluate it as
868 * @param key A key string.
869 * @param defaultValue The default.
870 * @return An object which is the value.
872 public double optDouble(String key, double defaultValue) {
874 return this.getDouble(key);
875 } catch (Exception e) {
882 * Get an optional int value associated with a key,
883 * or zero if there is no such key or if the value is not a number.
884 * If the value is a string, an attempt will be made to evaluate it as
887 * @param key A key string.
888 * @return An object which is the value.
890 public int optInt(String key) {
891 return this.optInt(key, 0);
896 * Get an optional int value associated with a key,
897 * or the default if there is no such key or if the value is not a number.
898 * If the value is a string, an attempt will be made to evaluate it as
901 * @param key A key string.
902 * @param defaultValue The default.
903 * @return An object which is the value.
905 public int optInt(String key, int defaultValue) {
907 return this.getInt(key);
908 } catch (Exception e) {
915 * Get an optional JSONArray associated with a key.
916 * It returns null if there is no such key, or if its value is not a
919 * @param key A key string.
920 * @return A JSONArray which is the value.
922 public JSONArray optJSONArray(String key) {
923 Object o = this.opt(key);
924 return o instanceof JSONArray ? (JSONArray) o : null;
929 * Get an optional JSONObject associated with a key.
930 * It returns null if there is no such key, or if its value is not a
933 * @param key A key string.
934 * @return A JSONObject which is the value.
936 public LOGJSONObject optJSONObject(String key) {
937 Object object = this.opt(key);
938 return object instanceof LOGJSONObject ? (LOGJSONObject) object : null;
943 * Get an optional long value associated with a key,
944 * or zero if there is no such key or if the value is not a number.
945 * If the value is a string, an attempt will be made to evaluate it as
948 * @param key A key string.
949 * @return An object which is the value.
951 public long optLong(String key) {
952 return this.optLong(key, 0);
957 * Get an optional long value associated with a key,
958 * or the default if there is no such key or if the value is not a number.
959 * If the value is a string, an attempt will be made to evaluate it as
962 * @param key A key string.
963 * @param defaultValue The default.
964 * @return An object which is the value.
966 public long optLong(String key, long defaultValue) {
968 return this.getLong(key);
969 } catch (Exception e) {
976 * Get an optional string associated with a key.
977 * It returns an empty string if there is no such key. If the value is not
978 * a string and is not null, then it is converted to a string.
980 * @param key A key string.
981 * @return A string which is the value.
983 public String optString(String key) {
984 return this.optString(key, "");
989 * Get an optional string associated with a key.
990 * It returns the defaultValue if there is no such key.
992 * @param key A key string.
993 * @param defaultValue The default.
994 * @return A string which is the value.
996 public String optString(String key, String defaultValue) {
997 Object object = this.opt(key);
998 return NULL.equals(object) ? defaultValue : object.toString();
1002 private void populateMap(Object bean) {
1003 Class<? extends Object> klass = bean.getClass();
1005 // If klass is a System class then set includeSuperClass to false.
1007 boolean includeSuperClass = klass.getClassLoader() != null;
1009 Method[] methods = includeSuperClass
1010 ? klass.getMethods()
1011 : klass.getDeclaredMethods();
1012 for (int i = 0; i < methods.length; i += 1) {
1014 Method method = methods[i];
1015 if (Modifier.isPublic(method.getModifiers())) {
1016 String name = method.getName();
1018 if (name.startsWith("get")) {
1019 if ("getClass".equals(name) ||
1020 "getDeclaringClass".equals(name)) {
1023 key = name.substring(3);
1025 } else if (name.startsWith("is")) {
1026 key = name.substring(2);
1028 if (key.length() > 0 &&
1029 Character.isUpperCase(key.charAt(0)) &&
1030 method.getParameterTypes().length == 0) {
1031 if (key.length() == 1) {
1032 key = key.toLowerCase();
1033 } else if (!Character.isUpperCase(key.charAt(1))) {
1034 key = key.substring(0, 1).toLowerCase() +
1038 Object result = method.invoke(bean, (Object[]) null);
1039 if (result != null) {
1040 this.map.put(key, wrap(result));
1044 } catch (Exception ignore) {
1051 * Put a key/boolean pair in the JSONObject.
1053 * @param key A key string.
1054 * @param value A boolean which is the value.
1056 * @throws JSONException If the key is null.
1058 public LOGJSONObject put(String key, boolean value) throws JSONException {
1059 this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
1065 * Put a key/value pair in the JSONObject, where the value will be a
1066 * JSONArray which is produced from a Collection.
1068 * @param key A key string.
1069 * @param value A Collection value.
1071 * @throws JSONException
1073 public LOGJSONObject put(String key, Collection<Object> value) throws JSONException {
1074 this.put(key, new JSONArray(value));
1080 * Put a key/double pair in the JSONObject.
1082 * @param key A key string.
1083 * @param value A double which is the value.
1085 * @throws JSONException If the key is null or if the number is invalid.
1087 public LOGJSONObject put(String key, double value) throws JSONException {
1088 this.put(key, new Double(value));
1094 * Put a key/int pair in the JSONObject.
1096 * @param key A key string.
1097 * @param value An int which is the value.
1099 * @throws JSONException If the key is null.
1101 public LOGJSONObject put(String key, int value) throws JSONException {
1102 this.put(key, new Integer(value));
1108 * Put a key/long pair in the JSONObject.
1110 * @param key A key string.
1111 * @param value A long which is the value.
1113 * @throws JSONException If the key is null.
1115 public LOGJSONObject put(String key, long value) throws JSONException {
1116 this.put(key, new Long(value));
1122 * Put a key/value pair in the JSONObject, where the value will be a
1123 * JSONObject which is produced from a Map.
1125 * @param key A key string.
1126 * @param value A Map value.
1128 * @throws JSONException
1130 public LOGJSONObject put(String key, Map<String, Object> value) throws JSONException {
1131 this.put(key, new LOGJSONObject(value));
1137 * Put a key/value pair in the JSONObject. If the value is null,
1138 * then the key will be removed from the JSONObject if it is present.
1140 * @param key A key string.
1141 * @param value An object which is the value. It should be of one of these
1142 * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
1143 * or the JSONObject.NULL object.
1145 * @throws JSONException If the value is non-finite number
1146 * or if the key is null.
1148 public LOGJSONObject put(String key, Object value) throws JSONException {
1151 throw new JSONException("Null key.");
1153 if (value != null) {
1154 testValidity(value);
1155 pooled = (String) keyPool.get(key);
1156 if (pooled == null) {
1157 if (keyPool.size() >= keyPoolSize) {
1158 keyPool = new LinkedHashMap<String, Object>(keyPoolSize);
1160 keyPool.put(key, key);
1164 this.map.put(key, value);
1173 * Put a key/value pair in the JSONObject, but only if the key and the
1174 * value are both non-null, and only if there is not already a member
1180 * @throws JSONException if the key is a duplicate
1182 public LOGJSONObject putOnce(String key, Object value) throws JSONException {
1183 if (key != null && value != null) {
1184 if (this.opt(key) != null) {
1185 throw new JSONException("Duplicate key \"" + key + "\"");
1187 this.put(key, value);
1194 * Put a key/value pair in the JSONObject, but only if the
1195 * key and the value are both non-null.
1197 * @param key A key string.
1198 * @param value An object which is the value. It should be of one of these
1199 * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
1200 * or the JSONObject.NULL object.
1202 * @throws JSONException If the value is a non-finite number.
1204 public LOGJSONObject putOpt(String key, Object value) throws JSONException {
1205 if (key != null && value != null) {
1206 this.put(key, value);
1213 * Produce a string in double quotes with backslash sequences in all the
1214 * right places. A backslash will be inserted within </, producing <\/,
1215 * allowing JSON text to be delivered in HTML. In JSON text, a string
1216 * cannot contain a control character or an unescaped quote or backslash.
1218 * @param string A String
1219 * @return A String correctly formatted for insertion in a JSON text.
1221 public static String quote(String string) {
1222 StringWriter sw = new StringWriter();
1223 synchronized (sw.getBuffer()) {
1225 return quote(string, sw).toString();
1226 } catch (IOException ignored) {
1227 // will never happen - we are writing to a string writer
1233 public static Writer quote(String string, Writer w) throws IOException {
1234 if (string == null || string.length() == 0) {
1243 int len = string.length();
1246 for (i = 0; i < len; i += 1) {
1248 c = string.charAt(i);
1277 if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
1278 || (c >= '\u2000' && c < '\u2100')) {
1280 hhhh = Integer.toHexString(c);
1281 w.write("0000", 0, 4 - hhhh.length());
1293 * Remove a name and its value, if present.
1295 * @param key The name to be removed.
1296 * @return The value that was associated with the name,
1297 * or null if there was no value.
1299 public Object remove(String key) {
1300 return this.map.remove(key);
1304 * Try to convert a string into a number, boolean, or null. If the string
1305 * can't be converted, return the string.
1307 * @param string A String.
1308 * @return A simple JSON value.
1310 public static Object stringToValue(String string) {
1312 if (string.equals("")) {
1315 if (string.equalsIgnoreCase("true")) {
1316 return Boolean.TRUE;
1318 if (string.equalsIgnoreCase("false")) {
1319 return Boolean.FALSE;
1321 if (string.equalsIgnoreCase("null")) {
1322 return LOGJSONObject.NULL;
1326 * If it might be a number, try converting it.
1327 * If a number cannot be produced, then the value will just
1328 * be a string. Note that the plus and implied string
1329 * conventions are non-standard. A JSON parser may accept
1330 * non-JSON forms as long as it accepts all correct JSON forms.
1333 char b = string.charAt(0);
1334 if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
1336 if (string.indexOf('.') > -1 ||
1337 string.indexOf('e') > -1 || string.indexOf('E') > -1) {
1338 d = Double.valueOf(string);
1339 if (!d.isInfinite() && !d.isNaN()) {
1343 Long myLong = new Long(string);
1344 if (myLong.longValue() == myLong.intValue()) {
1345 return new Integer(myLong.intValue());
1350 } catch (Exception ignore) {
1358 * Throw an exception if the object is a NaN or infinite number.
1360 * @param o The object to test.
1361 * @throws JSONException If o is a non-finite number.
1363 public static void testValidity(Object o) throws JSONException {
1365 if (o instanceof Double) {
1366 if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
1367 throw new JSONException(
1368 "JSON does not allow non-finite numbers.");
1370 } else if (o instanceof Float) {
1371 if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
1372 throw new JSONException(
1373 "JSON does not allow non-finite numbers.");
1381 * Produce a JSONArray containing the values of the members of this
1384 * @param names A JSONArray containing a list of key strings. This
1385 * determines the sequence of the values in the result.
1386 * @return A JSONArray of values.
1387 * @throws JSONException If any of the values are non-finite numbers.
1389 public JSONArray toJSONArray(JSONArray names) throws JSONException {
1390 if (names == null || names.length() == 0) {
1393 JSONArray ja = new JSONArray();
1394 for (int i = 0; i < names.length(); i += 1) {
1395 ja.put(this.opt(names.getString(i)));
1401 * Make a JSON text of this JSONObject. For compactness, no whitespace
1402 * is added. If this would not result in a syntactically correct JSON text,
1403 * then null will be returned instead.
1405 * Warning: This method assumes that the data structure is acyclical.
1407 * @return a printable, displayable, portable, transmittable
1408 * representation of the object, beginning
1409 * with <code>{</code> <small>(left brace)</small> and ending
1410 * with <code>}</code> <small>(right brace)</small>.
1412 public String toString() {
1414 return this.toString(0);
1415 } catch (Exception e) {
1422 * Make a prettyprinted JSON text of this JSONObject.
1424 * Warning: This method assumes that the data structure is acyclical.
1426 * @param indentFactor The number of spaces to add to each level of
1428 * @return a printable, displayable, portable, transmittable
1429 * representation of the object, beginning
1430 * with <code>{</code> <small>(left brace)</small> and ending
1431 * with <code>}</code> <small>(right brace)</small>.
1432 * @throws JSONException If the object contains an invalid number.
1434 public String toString(int indentFactor) throws JSONException {
1435 StringWriter w = new StringWriter();
1436 synchronized (w.getBuffer()) {
1437 return this.write(w, indentFactor, 0).toString();
1442 * Make a JSON text of an Object value. If the object has an
1443 * value.toJSONString() method, then that method will be used to produce
1444 * the JSON text. The method is required to produce a strictly
1445 * conforming text. If the object does not contain a toJSONString
1446 * method (which is the most common case), then a text will be
1447 * produced by other means. If the value is an array or Collection,
1448 * then a JSONArray will be made from it and its toJSONString method
1449 * will be called. If the value is a MAP, then a JSONObject will be made
1450 * from it and its toJSONString method will be called. Otherwise, the
1451 * value's toString method will be called, and the result will be quoted.
1454 * Warning: This method assumes that the data structure is acyclical.
1456 * @param value The value to be serialized.
1457 * @return a printable, displayable, transmittable
1458 * representation of the object, beginning
1459 * with <code>{</code> <small>(left brace)</small> and ending
1460 * with <code>}</code> <small>(right brace)</small>.
1461 * @throws JSONException If the value is or contains an invalid number.
1463 @SuppressWarnings("unchecked")
1464 public static String valueToString(Object value) throws JSONException {
1465 if (value == null || value.equals(null)) {
1468 if (value instanceof JSONString) {
1471 object = ((JSONString) value).toJSONString();
1472 } catch (Exception e) {
1473 throw new JSONException(e);
1475 if (object instanceof String) {
1476 return (String) object;
1478 throw new JSONException("Bad value from toJSONString: " + object);
1480 if (value instanceof Number) {
1481 return numberToString((Number) value);
1483 if (value instanceof Boolean || value instanceof LOGJSONObject ||
1484 value instanceof JSONArray) {
1485 return value.toString();
1487 if (value instanceof Map) {
1488 return new LOGJSONObject((Map<String, Object>) value).toString();
1490 if (value instanceof Collection) {
1491 return new JSONArray((Collection<Object>) value).toString();
1493 if (value.getClass().isArray()) {
1494 return new JSONArray(value).toString();
1496 return quote(value.toString());
1500 * Wrap an object, if necessary. If the object is null, return the NULL
1501 * object. If it is an array or collection, wrap it in a JSONArray. If
1502 * it is a map, wrap it in a JSONObject. If it is a standard property
1503 * (Double, String, et al) then it is already wrapped. Otherwise, if it
1504 * comes from one of the java packages, turn it into a string. And if
1505 * it doesn't, try to wrap it in a JSONObject. If the wrapping fails,
1506 * then null is returned.
1508 * @param object The object to wrap
1509 * @return The wrapped value
1511 @SuppressWarnings("unchecked")
1512 public static Object wrap(Object object) {
1514 if (object == null) {
1517 if (object instanceof LOGJSONObject || object instanceof JSONArray ||
1518 NULL.equals(object) || object instanceof JSONString ||
1519 object instanceof Byte || object instanceof Character ||
1520 object instanceof Short || object instanceof Integer ||
1521 object instanceof Long || object instanceof Boolean ||
1522 object instanceof Float || object instanceof Double ||
1523 object instanceof String) {
1527 if (object instanceof Collection) {
1528 return new JSONArray((Collection<Object>) object);
1530 if (object.getClass().isArray()) {
1531 return new JSONArray(object);
1533 if (object instanceof Map) {
1534 return new LOGJSONObject((Map<String, Object>) object);
1536 Package objectPackage = object.getClass().getPackage();
1537 String objectPackageName = objectPackage != null
1538 ? objectPackage.getName()
1541 objectPackageName.startsWith("java.") ||
1542 objectPackageName.startsWith("javax.") ||
1543 object.getClass().getClassLoader() == null
1545 return object.toString();
1547 return new LOGJSONObject(object);
1548 } catch (Exception exception) {
1555 * Write the contents of the JSONObject as JSON text to a writer.
1556 * For compactness, no whitespace is added.
1558 * Warning: This method assumes that the data structure is acyclical.
1560 * @return The writer.
1561 * @throws JSONException
1563 public Writer write(Writer writer) throws JSONException {
1564 return this.write(writer, 0, 0);
1568 @SuppressWarnings("unchecked")
1569 static final Writer writeValue(Writer writer, Object value,
1570 int indentFactor, int indent) throws JSONException, IOException {
1571 if (value == null || value.equals(null)) {
1572 writer.write("null");
1573 } else if (value instanceof LOGJSONObject) {
1574 ((LOGJSONObject) value).write(writer, indentFactor, indent);
1575 } else if (value instanceof JSONArray) {
1576 ((JSONArray) value).write(writer, indentFactor, indent);
1577 } else if (value instanceof Map) {
1578 new LOGJSONObject((Map<String, Object>) value).write(writer, indentFactor, indent);
1579 } else if (value instanceof Collection) {
1580 new JSONArray((Collection<Object>) value).write(writer, indentFactor,
1582 } else if (value.getClass().isArray()) {
1583 new JSONArray(value).write(writer, indentFactor, indent);
1584 } else if (value instanceof Number) {
1585 writer.write(numberToString((Number) value));
1586 } else if (value instanceof Boolean) {
1587 writer.write(value.toString());
1588 } else if (value instanceof JSONString) {
1591 o = ((JSONString) value).toJSONString();
1592 } catch (Exception e) {
1593 throw new JSONException(e);
1595 writer.write(o != null ? o.toString() : quote(value.toString()));
1597 quote(value.toString(), writer);
1602 static final void indent(Writer writer, int indent) throws IOException {
1603 for (int i = 0; i < indent; i += 1) {
1609 * Write the contents of the JSONObject as JSON text to a writer. For
1610 * compactness, no whitespace is added.
1612 * Warning: This method assumes that the data structure is acyclical.
1614 * @return The writer.
1615 * @throws JSONException
1617 Writer write(Writer writer, int indentFactor, int indent)
1618 throws JSONException {
1620 boolean commanate = false;
1621 final int length = this.length();
1622 Iterator<String> keys = this.keys();
1626 Object key = keys.next();
1627 writer.write(quote(key.toString()));
1629 if (indentFactor > 0) {
1632 writeValue(writer, this.map.get(key), indentFactor, indent);
1633 } else if (length != 0) {
1634 final int newindent = indent + indentFactor;
1635 while (keys.hasNext()) {
1636 Object key = keys.next();
1640 if (indentFactor > 0) {
1643 indent(writer, newindent);
1644 writer.write(quote(key.toString()));
1646 if (indentFactor > 0) {
1649 writeValue(writer, this.map.get(key), indentFactor,
1653 if (indentFactor > 0) {
1656 indent(writer, indent);
1660 } catch (IOException exception) {
1661 throw new JSONException(exception);