From 03bb6d08be4707e49a4c993526973563f527fc24 Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 16 Mar 2015 12:00:24 -0500 Subject: [PATCH 001/451] Create README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..727f33a --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# JSON-Java-unit-test +Junit test harness to validate the JSON-Java GitHub project code. +See https://github.com/douglascrockford/JSON-java + From 7559b574dd6c0b9918a06a31335921d66a0b4330 Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 16 Mar 2015 12:06:41 -0500 Subject: [PATCH 002/451] Add LICENSE file via addalicense.com --- LICENSE.txt | 176 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 LICENSE.txt diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..2bb9ad2 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file From 03192b01624e2e65145e4fd9803d48b962c0a2fd Mon Sep 17 00:00:00 2001 From: stleary Date: Tue, 17 Mar 2015 00:38:08 -0500 Subject: [PATCH 003/451] adding this file --- CDLTest.java | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 CDLTest.java diff --git a/CDLTest.java b/CDLTest.java new file mode 100644 index 0000000..a12a911 --- /dev/null +++ b/CDLTest.java @@ -0,0 +1,76 @@ +package org.json.junit; + +import static org.junit.Assert.*; + +import java.io.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.json.JSONObject; +import org.json.JSONArray; +import org.json.CDL; + +/** + * Tests for {@link CDL}. + * CDL provides an application level API, it is not actually used by the + * reference app. To test it, strings will be converted to JSON-Java classes + * and then converted back. But each row will be an unordered JSONObject, + * so can't use a simple string compare. + * @author JSON.org + * @version 2015-03-16 + * + */ +public class CDLTest { + + /** + * Compares a JSON array to the original string. The top row of the + * string contains the JSONObject keys and the remaining rows contain + * the values. The JSONObject rows are unordered and may differ between + * rows. + * @param jsonArray the JSONArray which was created from the string + * @param str the string which was used to create the JSONArray + * @return true if equal, otherwise false + */ + public boolean compareJSONArrayToString(JSONArray jsonArray, String str) { + boolean result = true; + int rows = jsonArray.length(); + StringReader sr = new StringReader(str); + BufferedReader reader = new BufferedReader(sr); + try { + String columnNames = reader.readLine(); + String[] keys = columnNames.split(","); + for (int i = 0; i < rows; ++i) { + String row = reader.readLine(); + String[] values = row.split(","); + JSONObject jsonObject = jsonArray.getJSONObject(i); + if (keys.length != jsonObject.length()) { + break; + } + int colIndex = 0; + for (String key: keys) { + + Object obj = jsonObject.get(key); + + } + } + } catch (IOException ignore) {} + return result; + } + + @Test + public void shouldConvertCDLToJSONArray() { + /** + * simple array where the first row of the string consists of the + * column names and there are 2 value rows + */ + String lines = new String( + "Col 1, Col 2, Col 3, Col 4, Col 5, Col 6, Col 7\n" + + "val1, val2, val3, val4, val5, val6, val7\n" + + "1, 2, 3, 4, 5, 6, 7\n"); + JSONArray jsonArray = CDL.toJSONArray(lines); + assertTrue("CDL should convert string to JSONArray correctly", + compareJSONArrayToString(jsonArray, lines)); + } + +} \ No newline at end of file From 5b56b5707418f7003260a0cf83475414beb7cda1 Mon Sep 17 00:00:00 2001 From: stleary Date: Tue, 17 Mar 2015 21:47:53 -0500 Subject: [PATCH 004/451] updating cdltest --- CDLTest.java | 69 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 52 insertions(+), 17 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index a12a911..28320dd 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -3,14 +3,23 @@ package org.json.junit; import static org.junit.Assert.*; import java.io.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import org.json.JSONException; import org.json.JSONObject; import org.json.JSONArray; import org.json.CDL; + /** * Tests for {@link CDL}. * CDL provides an application level API, it is not actually used by the @@ -26,36 +35,59 @@ public class CDLTest { /** * Compares a JSON array to the original string. The top row of the * string contains the JSONObject keys and the remaining rows contain - * the values. The JSONObject rows are unordered and may differ between - * rows. + * the values. The JSONObject in each JSONArray row is expected to have + * an entry corresponding to each key/value pair in the string. + * Each JSONObject row is unordered in its own way. * @param jsonArray the JSONArray which was created from the string * @param str the string which was used to create the JSONArray - * @return true if equal, otherwise false + * @return null if equal, otherwise error description */ - public boolean compareJSONArrayToString(JSONArray jsonArray, String str) { - boolean result = true; + public String compareJSONArrayToString(JSONArray jsonArray, String str) { int rows = jsonArray.length(); StringReader sr = new StringReader(str); BufferedReader reader = new BufferedReader(sr); try { + // first line contains the keys to the JSONObject array entries String columnNames = reader.readLine(); String[] keys = columnNames.split(","); + /** + * Each line contains the values for the corresponding + * JSONObject array entry + */ for (int i = 0; i < rows; ++i) { String row = reader.readLine(); String[] values = row.split(","); - JSONObject jsonObject = jsonArray.getJSONObject(i); - if (keys.length != jsonObject.length()) { - break; + // need a value for every key to proceed + if (keys.length != values.length) { + return("row: " +i+ " key and value counts do not match"); } - int colIndex = 0; - for (String key: keys) { - - Object obj = jsonObject.get(key); - + JSONObject jsonObject = jsonArray.getJSONObject(i); + // need a key for every JSONObject entry to proceed + if (keys.length != jsonObject.length()) { + return("row: " +i+ " key and jsonObject counts do not match"); + } + /** + * convert string entries into a natural order map. Trim the + * keys and values for tokener compatibility + */ + Map strMap = new TreeMap(); + for (int j = 0; j < keys.length; ++j) { + strMap.put(keys[j].trim(), values[j].trim()); + } + // put the JSONObjet key/value pairs in natural key order + Iterator keyIt = jsonObject.keys(); + Map jsonObjectMap = new TreeMap(); + while (keyIt.hasNext()) { + String key = keyIt.next(); + jsonObjectMap.put(key, jsonObject.get(key).toString()); + } + if (!strMap.equals(jsonObjectMap)) { + return("row: " +i+ "string does not match jsonObject"); } } - } catch (IOException ignore) {} - return result; + } catch (IOException ignore) { + } catch (JSONException ignore) {} + return null; } @Test @@ -69,8 +101,11 @@ public class CDLTest { "val1, val2, val3, val4, val5, val6, val7\n" + "1, 2, 3, 4, 5, 6, 7\n"); JSONArray jsonArray = CDL.toJSONArray(lines); - assertTrue("CDL should convert string to JSONArray correctly", - compareJSONArrayToString(jsonArray, lines)); + String resultStr = compareJSONArrayToString(jsonArray, lines); + if (resultStr != null) { + assertTrue("CDL should convert string to JSONArray correctly: " + + resultStr, false); + } } } \ No newline at end of file From 6c5e25dcb95ff1ac7bfc04ecb664656bd6bd3048 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 18 Mar 2015 10:13:13 -0500 Subject: [PATCH 005/451] added embedded quotes and escapes --- CDLTest.java | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index 28320dd..fb51514 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -59,20 +59,27 @@ public class CDLTest { String[] values = row.split(","); // need a value for every key to proceed if (keys.length != values.length) { + System.out.println("keys: " + Arrays.toString(keys)); + System.out.println("values: " + Arrays.toString(values)); return("row: " +i+ " key and value counts do not match"); } JSONObject jsonObject = jsonArray.getJSONObject(i); // need a key for every JSONObject entry to proceed if (keys.length != jsonObject.length()) { + System.out.println("keys: " + Arrays.toString(keys)); + System.out.println("jsonObject: " + jsonObject.toString()); return("row: " +i+ " key and jsonObject counts do not match"); } /** * convert string entries into a natural order map. Trim the - * keys and values for tokener compatibility + * keys and values for tokener compatibility. */ Map strMap = new TreeMap(); for (int j = 0; j < keys.length; ++j) { - strMap.put(keys[j].trim(), values[j].trim()); + values[j] = values[j].trim(); + // strip optional surrounding quotes + values[j] = values[j].replaceAll("^\"|\"$", ""); + strMap.put(keys[j].trim(), values[j]); } // put the JSONObjet key/value pairs in natural key order Iterator keyIt = jsonObject.keys(); @@ -82,6 +89,8 @@ public class CDLTest { jsonObjectMap.put(key, jsonObject.get(key).toString()); } if (!strMap.equals(jsonObjectMap)) { + System.out.println("strMap: " +strMap.toString()); + System.out.println("jsonObjectMap: " +jsonObjectMap.toString()); return("row: " +i+ "string does not match jsonObject"); } } @@ -99,7 +108,11 @@ public class CDLTest { String lines = new String( "Col 1, Col 2, Col 3, Col 4, Col 5, Col 6, Col 7\n" + "val1, val2, val3, val4, val5, val6, val7\n" + - "1, 2, 3, 4, 5, 6, 7\n"); + "1, 2, 3, 4, 5, 6, 7\n" + + "true, false, true, true, false, false, false\n" + + "0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" + + "\"va\tl1\", \"val2\", \"val\\b3\", \"val4\\n\", \"va\\rl5\", val6, val7\n" + ); JSONArray jsonArray = CDL.toJSONArray(lines); String resultStr = compareJSONArrayToString(jsonArray, lines); if (resultStr != null) { From 5fc0c4e1df60ea5565733bbde53707bb2ac95522 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 18 Mar 2015 12:40:20 -0500 Subject: [PATCH 006/451] 72% coverage! --- CDLTest.java | 122 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 98 insertions(+), 24 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index fb51514..f5ef9d0 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.*; import java.io.*; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -32,6 +33,19 @@ import org.json.CDL; */ public class CDLTest { + /** + * String of lines where the column names are in the first row, + * and all subsequent rows are values + */ + String lines = new String( + "Col 1, Col 2, Col 3, Col 4, Col 5, Col 6, Col 7\n" + + "val1, val2, val3, val4, val5, val6, val7\n" + + "1, 2, 3, 4, 5, 6, 7\n" + + "true, false, true, true, false, false, false\n" + + "0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" + + "\"va\tl1\", \"val2\", \"val\\b3\", \"val4\\n\", \"va\\rl5\", val6, val7\n" + ); + /** * Compares a JSON array to the original string. The top row of the * string contains the JSONObject keys and the remaining rows contain @@ -49,14 +63,16 @@ public class CDLTest { try { // first line contains the keys to the JSONObject array entries String columnNames = reader.readLine(); + columnNames = normalizeString(columnNames); String[] keys = columnNames.split(","); /** * Each line contains the values for the corresponding * JSONObject array entry */ for (int i = 0; i < rows; ++i) { - String row = reader.readLine(); - String[] values = row.split(","); + String line = reader.readLine(); + line = normalizeString(line); + String[] values = line.split(","); // need a value for every key to proceed if (keys.length != values.length) { System.out.println("keys: " + Arrays.toString(keys)); @@ -70,16 +86,10 @@ public class CDLTest { System.out.println("jsonObject: " + jsonObject.toString()); return("row: " +i+ " key and jsonObject counts do not match"); } - /** - * convert string entries into a natural order map. Trim the - * keys and values for tokener compatibility. - */ + // convert string entries into a natural order map. Map strMap = new TreeMap(); for (int j = 0; j < keys.length; ++j) { - values[j] = values[j].trim(); - // strip optional surrounding quotes - values[j] = values[j].replaceAll("^\"|\"$", ""); - strMap.put(keys[j].trim(), values[j]); + strMap.put(keys[j], values[j]); } // put the JSONObjet key/value pairs in natural key order Iterator keyIt = jsonObject.keys(); @@ -98,27 +108,91 @@ public class CDLTest { } catch (JSONException ignore) {} return null; } - + @Test public void shouldConvertCDLToJSONArray() { - /** - * simple array where the first row of the string consists of the - * column names and there are 2 value rows - */ - String lines = new String( - "Col 1, Col 2, Col 3, Col 4, Col 5, Col 6, Col 7\n" + - "val1, val2, val3, val4, val5, val6, val7\n" + - "1, 2, 3, 4, 5, 6, 7\n" + - "true, false, true, true, false, false, false\n" + - "0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" + - "\"va\tl1\", \"val2\", \"val\\b3\", \"val4\\n\", \"va\\rl5\", val6, val7\n" - ); JSONArray jsonArray = CDL.toJSONArray(lines); String resultStr = compareJSONArrayToString(jsonArray, lines); if (resultStr != null) { - assertTrue("CDL should convert string to JSONArray correctly: " + + assertTrue("CDL should convert string to JSONArray: " + resultStr, false); } } + @Test + public void shouldConvertJSONArrayToCDLString() { + final boolean normalize = true; + final boolean doNotNormalize = false; + JSONArray jsonArray = CDL.toJSONArray(lines); + String jsonStr = CDL.toString(jsonArray); + // normal sorted + List> sortedLines = sortColumnsInLines(lines, normalize); + // sorted, should already be normalized + List> sortedJsonStr = sortColumnsInLines(jsonStr, doNotNormalize); + boolean result = sortedLines.equals(sortedJsonStr); + if (!result) { + System.out.println("lines: " +sortedLines); + System.out.println("jsonStr: " +sortedJsonStr); + assertTrue("CDL should convert JSONArray back to original string: " + + lines.equals(jsonStr), false); + } + } + + /** + * Utility to trim and remove internal quotes from comma delimited strings. + * Need to do this because JSONObject does the same thing + * @param line the line to be normalized + * @return the normalized line + */ + private String normalizeString(String line) { + StringBuilder builder = new StringBuilder(); + boolean comma = false; + String[] values = line.split(","); + for (int i = 0; i < values.length; ++i) { + if (comma) { + builder.append(","); + } + comma = true; + values[i] = values[i].trim(); + // strip optional surrounding quotes + values[i] = values[i].replaceAll("^\"|\"$", ""); + builder.append(values[i]); + } + return builder.toString(); + } + + /** + * Utility to sort the columns in a (possibly) multi-lined string. + * The columns are column separated. Need to do this because + * JSONObects are not ordered + * @param string the string to be sorted + * @param normalize flag, true if line should be normalized + * @return a list of sorted lines, where each line is a list sorted + * in natural key order + */ + private List> sortColumnsInLines(String string, + boolean normalizeFlag) { + List> lineList = new ArrayList>(); + StringReader sr = new StringReader(string); + BufferedReader reader = new BufferedReader(sr); + try { + while (true) { + String line = reader.readLine(); + if (line == null) { + break; + } + if (normalizeFlag) { + line = normalizeString(line); + } + List columnList = new ArrayList(); + String[] values = line.split(","); + for (int i = 0; i < values.length; ++i) { + columnList.add(values[i]); + } + Collections.sort(columnList); + lineList.add(columnList); + } + } catch (IOException ignore) {} + return lineList; + } } \ No newline at end of file From a859e4f547588d214361776ce556bb41eacc5759 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 18 Mar 2015 18:16:19 -0500 Subject: [PATCH 007/451] few more tests --- CDLTest.java | 125 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 94 insertions(+), 31 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index f5ef9d0..0395045 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -35,7 +35,7 @@ public class CDLTest { /** * String of lines where the column names are in the first row, - * and all subsequent rows are values + * and all subsequent rows are values. All keys and values should be legal. */ String lines = new String( "Col 1, Col 2, Col 3, Col 4, Col 5, Col 6, Col 7\n" + @@ -46,6 +46,98 @@ public class CDLTest { "\"va\tl1\", \"val2\", \"val\\b3\", \"val4\\n\", \"va\\rl5\", val6, val7\n" ); + @Test(expected=NullPointerException.class) + public void shouldThrowExceptionOnNullString() { + String nullStr = null; + CDL.toJSONArray(nullStr); + } + + @Test + /** + * Note: This test reveals a bug in the method JavaDoc. It should + * mention it might return null, or it should return an empty JSONArray. + */ + public void shouldHandleOnlyColumnNames() { + String columnNameStr = "col1, col2, col3"; + JSONArray jsonArray = CDL.toJSONArray(columnNameStr); + assertTrue("CDL should return null when only 1 row is given", + jsonArray == null); + } + + @Test + /** + * Note: This test reveals a bug in the method JavaDoc. It should + * mention it might return null, or it should return an empty JSONArray. + */ + public void shouldHandleEmptyString() { + String emptyStr = ""; + JSONArray jsonArray = CDL.toJSONArray(emptyStr); + assertTrue("CDL should return null when the input string is empty", + jsonArray == null); + } + + @Test + public void toStringShouldCheckSpecialChars() { + /** + * This is pretty clumsy, there should be a better way + * to perform this test. Needs more debugging. The problem + * may be that these chars are sanitized out by CDL when constructing + * a JSONArray from a string. + */ + String singleStr = "\"Col 1\"\n1"; + JSONArray jsonArray = CDL.toJSONArray(singleStr); + JSONObject jsonObject = (JSONObject)(jsonArray.get(0)); + jsonObject.put("Col \r4", "V4"); + jsonObject.put("Col \0 a", "V5"); + boolean doNotNormalize = false; + List> expectedLines = + sortColumnsInLines("Col ,2\",Col 1,\"Col 4\",\"Col a\"\nV2,1,V4,V5,V3", + doNotNormalize); + List> jsonArrayLines = + sortColumnsInLines(CDL.toString(jsonArray), doNotNormalize); + System.out.println("expected: " +expectedLines); + System.out.println("jsonArray: " +jsonArrayLines); + } + + @Test + public void shouldConvertJSONArrayToCDLString() { + /** + * This is the first test of normal functionality. + * The string contains a typical variety of values + * that might be found in a real CDL. + */ + final boolean normalize = true; + final boolean doNotNormalize = false; + JSONArray jsonArray = CDL.toJSONArray(lines); + String jsonStr = CDL.toString(jsonArray); + // normal sorted + List> sortedLines = sortColumnsInLines(lines, normalize); + // sorted, should already be normalized + List> sortedJsonStr = sortColumnsInLines(jsonStr, doNotNormalize); + boolean result = sortedLines.equals(sortedJsonStr); + if (!result) { + System.out.println("lines: " +sortedLines); + System.out.println("jsonStr: " +sortedJsonStr); + assertTrue("CDL should convert JSONArray back to original string: " + + lines.equals(jsonStr), false); + } + } + + @Test + public void shouldConvertCDLToJSONArray() { + JSONArray jsonArray = CDL.toJSONArray(lines); + String resultStr = compareJSONArrayToString(jsonArray, lines); + if (resultStr != null) { + assertTrue("CDL should convert string to JSONArray: " + + resultStr, false); + } + } + + + /******************************************************************\ + * SUPPORT AND UTILITY + \******************************************************************/ + /** * Compares a JSON array to the original string. The top row of the * string contains the JSONObject keys and the remaining rows contain @@ -56,7 +148,7 @@ public class CDLTest { * @param str the string which was used to create the JSONArray * @return null if equal, otherwise error description */ - public String compareJSONArrayToString(JSONArray jsonArray, String str) { + private String compareJSONArrayToString(JSONArray jsonArray, String str) { int rows = jsonArray.length(); StringReader sr = new StringReader(str); BufferedReader reader = new BufferedReader(sr); @@ -109,35 +201,6 @@ public class CDLTest { return null; } - @Test - public void shouldConvertCDLToJSONArray() { - JSONArray jsonArray = CDL.toJSONArray(lines); - String resultStr = compareJSONArrayToString(jsonArray, lines); - if (resultStr != null) { - assertTrue("CDL should convert string to JSONArray: " + - resultStr, false); - } - } - - @Test - public void shouldConvertJSONArrayToCDLString() { - final boolean normalize = true; - final boolean doNotNormalize = false; - JSONArray jsonArray = CDL.toJSONArray(lines); - String jsonStr = CDL.toString(jsonArray); - // normal sorted - List> sortedLines = sortColumnsInLines(lines, normalize); - // sorted, should already be normalized - List> sortedJsonStr = sortColumnsInLines(jsonStr, doNotNormalize); - boolean result = sortedLines.equals(sortedJsonStr); - if (!result) { - System.out.println("lines: " +sortedLines); - System.out.println("jsonStr: " +sortedJsonStr); - assertTrue("CDL should convert JSONArray back to original string: " + - lines.equals(jsonStr), false); - } - } - /** * Utility to trim and remove internal quotes from comma delimited strings. * Need to do this because JSONObject does the same thing From 4a5809910bc7a2bbe5892f9336eae0a609af9912 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 18 Mar 2015 20:54:46 -0500 Subject: [PATCH 008/451] final, for now, 94.8% coverage --- CDLTest.java | 101 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 67 insertions(+), 34 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index 0395045..d5ead3c 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -1,5 +1,4 @@ package org.json.junit; - import static org.junit.Assert.*; import java.io.*; @@ -9,12 +8,9 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.TreeMap; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONArray; @@ -23,12 +19,12 @@ import org.json.CDL; /** * Tests for {@link CDL}. - * CDL provides an application level API, it is not actually used by the + * CDL provides an application level API, but it is not used by the * reference app. To test it, strings will be converted to JSON-Java classes - * and then converted back. But each row will be an unordered JSONObject, - * so can't use a simple string compare. + * and then converted back. Since each row is an unordered JSONObject, + * can't use a simple string compare to check for equality. * @author JSON.org - * @version 2015-03-16 + * @version 2015-03-18 * */ public class CDLTest { @@ -43,7 +39,7 @@ public class CDLTest { "1, 2, 3, 4, 5, 6, 7\n" + "true, false, true, true, false, false, false\n" + "0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" + - "\"va\tl1\", \"val2\", \"val\\b3\", \"val4\\n\", \"va\\rl5\", val6, val7\n" + "\"va\tl1\", \"v\bal2\", \"val3\", \"val\f4\", \"val5\", va\'l6, val7\n" ); @Test(expected=NullPointerException.class) @@ -79,28 +75,74 @@ public class CDLTest { @Test public void toStringShouldCheckSpecialChars() { /** - * This is pretty clumsy, there should be a better way - * to perform this test. Needs more debugging. The problem - * may be that these chars are sanitized out by CDL when constructing - * a JSONArray from a string. + * Given a JSONArray that was not built by CDL, some chars may be + * found that would otherwise be filtered out by CDL. */ - String singleStr = "\"Col 1\"\n1"; - JSONArray jsonArray = CDL.toJSONArray(singleStr); - JSONObject jsonObject = (JSONObject)(jsonArray.get(0)); - jsonObject.put("Col \r4", "V4"); - jsonObject.put("Col \0 a", "V5"); - boolean doNotNormalize = false; + JSONArray jsonArray = new JSONArray(); + JSONObject jsonObject = new JSONObject(); + jsonArray.put(jsonObject); + // \r will be filtered from name + jsonObject.put("Col \r1", "V1"); + // \r will be filtered from value + jsonObject.put("Col 2", "V2\r"); + boolean normalize = true; List> expectedLines = - sortColumnsInLines("Col ,2\",Col 1,\"Col 4\",\"Col a\"\nV2,1,V4,V5,V3", - doNotNormalize); + sortColumnsInLines("Col 1, Col 2,\nV1, V2", normalize); List> jsonArrayLines = - sortColumnsInLines(CDL.toString(jsonArray), doNotNormalize); - System.out.println("expected: " +expectedLines); - System.out.println("jsonArray: " +jsonArrayLines); + sortColumnsInLines(CDL.toString(jsonArray), normalize); + if (!expectedLines.equals(jsonArrayLines)) { + System.out.println("expected: " +expectedLines); + System.out.println("jsonArray: " +jsonArrayLines); + assertTrue("Should filter out certain chars", + false); + } + } + + @Test(expected=JSONException.class) + public void shouldHandleUnbalancedQuoteInName() { + String badLine = "Col1, \"Col2\nVal1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test(expected=JSONException.class) + public void shouldHandleUnbalancedQuoteInValue() { + String badLine = "Col1, Col2\n\"Val1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test(expected=JSONException.class) + public void shouldHandleNullInName() { + String badLine = "C\0ol1, Col2\nVal1, Val2"; + CDL.toJSONArray(badLine); } @Test - public void shouldConvertJSONArrayToCDLString() { + public void shouldConvertCDLToJSONArray() { + JSONArray jsonArray = CDL.toJSONArray(lines); + String resultStr = compareJSONArrayToString(jsonArray, lines); + if (resultStr != null) { + assertTrue("CDL should convert string to JSONArray: " + + resultStr, false); + } + } + + @Test + public void shouldCreateJSONArrayUsingJSONArray() { + String names = "Col1, Col2"; + String nameArrayStr = "[" +names+ "]"; + String values = "V1, V2"; + JSONArray nameJSONArray = new JSONArray(nameArrayStr); + JSONArray jsonArray = CDL.toJSONArray(nameJSONArray, values); + String combinedStr = names+ "\n" +values; + String resultStr = compareJSONArrayToString(jsonArray, combinedStr); + if (resultStr != null) { + assertTrue("CDL should convert JSONArray and string to JSONArray: " + + resultStr, false); + } + } + + @Test + public void shouldConvertCDLToJSONArrayAndBackToString() { /** * This is the first test of normal functionality. * The string contains a typical variety of values @@ -123,15 +165,6 @@ public class CDLTest { } } - @Test - public void shouldConvertCDLToJSONArray() { - JSONArray jsonArray = CDL.toJSONArray(lines); - String resultStr = compareJSONArrayToString(jsonArray, lines); - if (resultStr != null) { - assertTrue("CDL should convert string to JSONArray: " + - resultStr, false); - } - } /******************************************************************\ From d613203eecf1e8707955df2cc6e3db5ba8d6c0ad Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 18 Mar 2015 21:51:08 -0500 Subject: [PATCH 009/451] Update README.md --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 727f33a..8fdb6ec 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,10 @@ # JSON-Java-unit-test -Junit test harness to validate the JSON-Java GitHub project code. -See https://github.com/douglascrockford/JSON-java +Unit tests to validate the JSON-Java GitHub project code (https://github.com/douglascrockford/JSON-java). +Test harness: http://junit.org +Coverage: http://www.eclemma.org/ +Completed tests: +CDLTest.java +In progress: +CookieTest.java + From 3d3325aaca7cf7e450ce87e2b42e104a7319cc4c Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 18 Mar 2015 21:51:43 -0500 Subject: [PATCH 010/451] Update README.md --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 8fdb6ec..bef6696 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,16 @@ # JSON-Java-unit-test Unit tests to validate the JSON-Java GitHub project code (https://github.com/douglascrockford/JSON-java). + Test harness: http://junit.org + Coverage: http://www.eclemma.org/ + Completed tests: + CDLTest.java + In progress: + CookieTest.java From df68a7b593a9fad6b5cc0dec27226b1c5deaa6cc Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 18 Mar 2015 22:39:54 -0500 Subject: [PATCH 011/451] test suite and cookie test --- CookieTest.java | 26 ++++++++++++++++++++++++++ JunitTestSuite.java | 11 +++++++++++ TestRunner.java | 15 +++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 CookieTest.java create mode 100644 JunitTestSuite.java create mode 100644 TestRunner.java diff --git a/CookieTest.java b/CookieTest.java new file mode 100644 index 0000000..f77cdf7 --- /dev/null +++ b/CookieTest.java @@ -0,0 +1,26 @@ +package org.json.junit; + +import java.io.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import static org.junit.Assert.*; +import org.junit.Test; + + +/** + * Tests for JSON-Java Cookie.java + */ +public class CookieTest { + + @Test + public void test() { + + } + +} diff --git a/JunitTestSuite.java b/JunitTestSuite.java new file mode 100644 index 0000000..20b69f9 --- /dev/null +++ b/JunitTestSuite.java @@ -0,0 +1,11 @@ +package org.json.junit; + +import org.junit.runner.RunWith; +import org.junit.runners.Suite; +@RunWith(Suite.class) +@Suite.SuiteClasses({ + CDLTest.class, + CookieTest.class +}) +public class JunitTestSuite { +} \ No newline at end of file diff --git a/TestRunner.java b/TestRunner.java new file mode 100644 index 0000000..8f9dd89 --- /dev/null +++ b/TestRunner.java @@ -0,0 +1,15 @@ +package org.json.junit; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +public class TestRunner { + public static void main(String[] args) { + Result result = JUnitCore.runClasses(JunitTestSuite.class); + for (Failure failure : result.getFailures()) { + System.out.println(failure.toString()); + } + System.out.println(result.wasSuccessful()); + } +} \ No newline at end of file From b557180bcaf2a66eab5a4ae55db6893623f25ab5 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 19 Mar 2015 11:27:45 -0500 Subject: [PATCH 012/451] more cookie code, in progress --- CookieTest.java | 56 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 48 insertions(+), 8 deletions(-) diff --git a/CookieTest.java b/CookieTest.java index f77cdf7..8f4cf14 100644 --- a/CookieTest.java +++ b/CookieTest.java @@ -1,15 +1,11 @@ package org.json.junit; import java.io.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; import static org.junit.Assert.*; + +import org.json.*; import org.junit.Test; @@ -18,8 +14,52 @@ import org.junit.Test; */ public class CookieTest { + String realWorldCookie = + "hpc=d=I.aZLE4l.8DeqRynle2fTnKxdAycw3CvCrzMNofhR9a5vYaU.XnHk6n3ZenMs6Xqq"+ + "3Mc5kMw.M1c.vR6zdxVMsfAQn75WNaFp8mY3UQgEw8lvIAbZvT_PiJofv7OMCbabUOe1Efd"+ + "i2M5.aVTX2bHB3EJPhNQNe0B5PL6mGbz7KYYyujkcn6hVS7U5d5OYv7L0GSAiKY-&v=2; y"+ + "wadp115488662=3370273056; AO=u=1&o=1; ywandp=10001806365479:1024785001;"+ + "10001576721379:3531995934; fpc=10001806365479:ZblWsSPj||;10001576721379"+ + ":ZY1jZhRq||; V=v=0.7&m=0&ccOptions={\"show\":false,\"lang\":\"en\",\"fo"+ + "ntSize\":24,\"fontName\":\"Helvetica Neue,Helvetica,Arial,_sans\",\"fon"+ + "tColor\":\"#ffffff\",\"fontOpacity\":1,\"fontEffect\":\"none\",\"bgColo"+ + "r\":\"#000000\",\"bgOpacity\":0.75}; yvap=193@yvap=193@cc=1@al=1@vl=0@r"+ + "vl=0@ac=1@rvl_NFL=0@session_NFL=0@lmsID=@rcc=0; YLS=v=1&p=1&n=1; ucs=tr"+ + "=1424831973913&sfcTs=1425971131&sfc=1; B=26tgei1adfl2v&b=4&d=j7.bbChrYH"+ + "1Ww.22z25N3S2YRsiX.e8VKSZpZdjeYXeN.w--&s=lr; F=a=MVvM8WsMvSxoU9K4FcyMxZ"+ + ".lwmw1yLWpNLOZbMVqjDB8d.bZm1C1JJVJFfCXcy3YfSZy47VAvKKSGZBmM1HQdIUWJA--&"+ + "b=PW8Y; YP=v=AwAAY&d=AEcAMEQCIHHEk.ugtA0iqWk_ctLMBWKG_gJfDzKX.tlKIIGBVH"+ + "cTAiBgmZUHV73V2i80FgqcVjQnvNTyor0rYBXsjhXBul2PzwA-; ypcdb=096e88ca6ff13"+ + "fee954ee414bb7b9362; Y=v=1&n=edbmi9njnt2h1&p=; CRZY={\"33935700511_2015"+ + "0317\":{\"expires\":1426808579870,\"data\":{\"nv\":1,\"bn\":1,\"collaps"+ + "ed\":0}},\"33726925511_20150318\":{\"expires\":1426859124988,\"data\":{"+ + "\"nv\":7,\"bn\":0,\"collapsed\":0}},\"33748770511_20150318\":{\"expires"+ + "\":1426911961098,\"data\":{\"nv\":2,\"bn\":0,\"collapsed\":0}}}; apeaf="+ + "td-applet-stream={\"tmpl\":\"items\",\"po\":{\"2409678.20150318\":{\"c"+ + "\":0,\"v\":2,\"ts\":1426719393315}}}"; + + @Test(expected=NullPointerException.class) + public void shouldHandleNullCookie() { + String cookieStr = null; + Cookie.toJSONObject(cookieStr); + } + + @Test(expected=JSONException.class) + public void shouldHandleEmptyStringCookie() { + String cookieStr = ""; + Cookie.toJSONObject(cookieStr); + } + @Test - public void test() { + public void shouldHandleSimpleCookie() { + String cookieStr = "abc=def"; + JSONObject jsonObject = Cookie.toJSONObject(cookieStr); + Set keySet = jsonObject.keySet(); + assertTrue("Keyset should have exactly 2 keys", keySet.size() == 2); + assertTrue("name should have expected value", + jsonObject.getString("name").equals("abc")); + assertTrue("Value should have expected value", + jsonObject.getString("value").equals("def")); } From ab08db4ad666fa1cca7ed8e701a0ea7bff382fb8 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 19 Mar 2015 16:09:29 -0500 Subject: [PATCH 013/451] CookieTest 97.5% coverage --- CookieTest.java | 218 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 186 insertions(+), 32 deletions(-) diff --git a/CookieTest.java b/CookieTest.java index 8f4cf14..d8453e9 100644 --- a/CookieTest.java +++ b/CookieTest.java @@ -1,6 +1,5 @@ package org.json.junit; -import java.io.*; import java.util.*; import static org.junit.Assert.*; @@ -11,33 +10,57 @@ import org.junit.Test; /** * Tests for JSON-Java Cookie.java + * Paraphrased from: + * http://www.nczonline.net/blog/2009/05/05/http-cookies-explained/ + * + * A web server specifies a cookie to be stored by sending an HTTP header + * called Set-Cookie. The format of the Set-Cookie header is a string as + * follows (parts in square brackets are optional): + * Set-Cookie: value[; expires=date][; domain=domain][; path=path][; secure] + * Where value is usually, but not always, a key/value pair: name=value + * Separators between the optional segments (e.g. expires=date) consist of a + * semicolon followed by a space. + * + * Although cookies are typically url-encoded, they don't have to be. + * + * expires date example: + * Set-Cookie: name=Nicholas; expires=Sat, 02 May 2009 23:38:25 GMT + * + * domain option example: + * Set-Cookie: name=Nicholas; domain=nczonline.net + * + * Path option example: + * Set-Cookie: name=Nicholas; path=/blog + * + * Secure option example (it is just a flag): + * Set-Cookie: name=Nicholas; secure + * + * Subcookies. There is a hard limit of size (4k) that can't be finessed. + * But many browsers (not Chrome) have a max cookies per domain limit + * (usually 50). To get around this, subcookies are encoded in the initial + * name/value pair as follows: + * name=a=b&c=d&e=f&g=h */ public class CookieTest { - String realWorldCookie = - "hpc=d=I.aZLE4l.8DeqRynle2fTnKxdAycw3CvCrzMNofhR9a5vYaU.XnHk6n3ZenMs6Xqq"+ - "3Mc5kMw.M1c.vR6zdxVMsfAQn75WNaFp8mY3UQgEw8lvIAbZvT_PiJofv7OMCbabUOe1Efd"+ - "i2M5.aVTX2bHB3EJPhNQNe0B5PL6mGbz7KYYyujkcn6hVS7U5d5OYv7L0GSAiKY-&v=2; y"+ - "wadp115488662=3370273056; AO=u=1&o=1; ywandp=10001806365479:1024785001;"+ - "10001576721379:3531995934; fpc=10001806365479:ZblWsSPj||;10001576721379"+ - ":ZY1jZhRq||; V=v=0.7&m=0&ccOptions={\"show\":false,\"lang\":\"en\",\"fo"+ - "ntSize\":24,\"fontName\":\"Helvetica Neue,Helvetica,Arial,_sans\",\"fon"+ - "tColor\":\"#ffffff\",\"fontOpacity\":1,\"fontEffect\":\"none\",\"bgColo"+ - "r\":\"#000000\",\"bgOpacity\":0.75}; yvap=193@yvap=193@cc=1@al=1@vl=0@r"+ - "vl=0@ac=1@rvl_NFL=0@session_NFL=0@lmsID=@rcc=0; YLS=v=1&p=1&n=1; ucs=tr"+ - "=1424831973913&sfcTs=1425971131&sfc=1; B=26tgei1adfl2v&b=4&d=j7.bbChrYH"+ - "1Ww.22z25N3S2YRsiX.e8VKSZpZdjeYXeN.w--&s=lr; F=a=MVvM8WsMvSxoU9K4FcyMxZ"+ - ".lwmw1yLWpNLOZbMVqjDB8d.bZm1C1JJVJFfCXcy3YfSZy47VAvKKSGZBmM1HQdIUWJA--&"+ - "b=PW8Y; YP=v=AwAAY&d=AEcAMEQCIHHEk.ugtA0iqWk_ctLMBWKG_gJfDzKX.tlKIIGBVH"+ - "cTAiBgmZUHV73V2i80FgqcVjQnvNTyor0rYBXsjhXBul2PzwA-; ypcdb=096e88ca6ff13"+ - "fee954ee414bb7b9362; Y=v=1&n=edbmi9njnt2h1&p=; CRZY={\"33935700511_2015"+ - "0317\":{\"expires\":1426808579870,\"data\":{\"nv\":1,\"bn\":1,\"collaps"+ - "ed\":0}},\"33726925511_20150318\":{\"expires\":1426859124988,\"data\":{"+ - "\"nv\":7,\"bn\":0,\"collapsed\":0}},\"33748770511_20150318\":{\"expires"+ - "\":1426911961098,\"data\":{\"nv\":2,\"bn\":0,\"collapsed\":0}}}; apeaf="+ - "td-applet-stream={\"tmpl\":\"items\",\"po\":{\"2409678.20150318\":{\"c"+ - "\":0,\"v\":2,\"ts\":1426719393315}}}"; - + String simpleCookieStr = + "PH=deleted"+ + "; expires=Wed, 19-Mar-2014 17:53:53 GMT"+ + ";path=/"+ + "; domain=.yahoo.com"+ + ";secure"+ + ";not=included"; + + String encodedCookieStr = + "PH=contains+some+chars"+ + ";expires=Wed, 19-Mar-2014 17:53:53 GMT"+ + "; path=/"+ + ";domain=.yahoo.com?some+escape+chars"+ + "; secure"+ + "; CRZY=%7B%2233748770511_20150319%22%3A%7B%22expires%22%3A142696041"+ + "3419%2C%22data%22%3A%7B%22nv%22%3A3%2C%22bn%22%3A0%2C%22collapsed%2"+ + "2%3A0%7D%7D%7D"; + @Test(expected=NullPointerException.class) public void shouldHandleNullCookie() { String cookieStr = null; @@ -51,16 +74,147 @@ public class CookieTest { } @Test - public void shouldHandleSimpleCookie() { - String cookieStr = "abc=def"; - JSONObject jsonObject = Cookie.toJSONObject(cookieStr); + public void shouldHandleNonEncodedCookie() { + JSONObject jsonObject = Cookie.toJSONObject(simpleCookieStr); Set keySet = jsonObject.keySet(); - assertTrue("Keyset should have exactly 2 keys", keySet.size() == 2); + assertTrue("Keyset should have exactly 7 keys", keySet.size() == 7); assertTrue("name should have expected value", - jsonObject.getString("name").equals("abc")); + "PH".equals(jsonObject.getString("name"))); assertTrue("Value should have expected value", - jsonObject.getString("value").equals("def")); - + "deleted".equals(jsonObject.getString("value"))); + assertTrue("expires should have expected value", + "Wed, 19-Mar-2014 17:53:53 GMT".equals( + jsonObject.getString("expires"))); + assertTrue("domain should have expected value", + ".yahoo.com".equals( + jsonObject.getString("domain"))); + assertTrue("path should have expected value", + "/".equals( + jsonObject.getString("path"))); + assertTrue("not should have expected value", + "included".equals( + jsonObject.getString("not"))); + Boolean secureBool = jsonObject.getBoolean("secure"); + assertTrue("secure should be found in jsonObject", secureBool != null); + assertTrue("secure should have expected value", + secureBool.equals(true)); } + @Test + public void shouldConvertNonEncodedCookieToString() { + int idx; + String expectedStr; + JSONObject jsonObject = Cookie.toJSONObject(simpleCookieStr); + String cookieStr = Cookie.toString(jsonObject); + + // check for unordered expected output + expectedStr = "path=/"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("path should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + expectedStr = "expires=Wed, 19-Mar-2014 17:53:53 GMT"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("expires should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + expectedStr = "domain=.yahoo.com"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("domain should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + expectedStr = "PH=deleted"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("name/value should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + expectedStr = "secure"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("secure should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + // after semicolons, nothing should be left + cookieStr = cookieStr.replaceAll(";", ""); + assertTrue("nothing else should remain in cookie toString()", + cookieStr.length() == 0); + } + + @Test + public void shouldHandleEncodedCookie() { + JSONObject jsonObject = Cookie.toJSONObject(encodedCookieStr); + Set keySet = jsonObject.keySet(); + // Note: the 7th key/value is not used by Cookie.java + assertTrue("Keyset should have exactly 7 keys", keySet.size() == 7); + assertTrue("name should have expected value", + "PH".equals(jsonObject.getString("name"))); + assertTrue("Value should have expected value", + "contains+some+chars".equals(jsonObject.getString("value"))); + assertTrue("expires should have expected value", + "Wed, 19-Mar-2014 17:53:53 GMT".equals( + jsonObject.getString("expires"))); + assertTrue("domain should have expected value", + ".yahoo.com?some escape chars".equals( + jsonObject.getString("domain"))); + assertTrue("path should have expected value", + "/".equals( + jsonObject.getString("path"))); + Boolean secureBool = jsonObject.getBoolean("secure"); + assertTrue("secure should be found in jsonObject", secureBool != null); + assertTrue("secure should have expected value", + secureBool.equals(true)); + String expectedStr = "{\"33748770511_20150319\":{\"expires\":14269604134"+ + "19,\"data\":{\"nv\":3,\"bn\":0,\"collapsed\":0}}}"; + assertTrue("CRZY should have expected value", + expectedStr.equals(jsonObject.getString("CRZY"))); + } + + @Test + public void shouldConvertEncodedCookieToString() { + int idx; + String expectedStr; + JSONObject jsonObject = Cookie.toJSONObject(encodedCookieStr); + String cookieStr = Cookie.toString(jsonObject); + + // check for unordered expected output + expectedStr = "path=/"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("path should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + expectedStr = "expires=Wed, 19-Mar-2014 17:53:53 GMT"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("expires should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + expectedStr = "domain=.yahoo.com?some escape chars"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("domain should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + expectedStr = "PH=contains%2bsome%2bchars"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("name/value should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + expectedStr = "secure"; + idx = cookieStr.indexOf(expectedStr); + assertTrue("secure should be included in string output", idx != -1); + cookieStr = cookieStr.substring(0, idx)+ + cookieStr.substring(idx+expectedStr.length()); + + // after semicolons, nothing should be left + cookieStr = cookieStr.replaceAll(";", ""); + assertTrue("nothing else should remain in cookie toString()", + cookieStr.length() == 0); + } + } From fac377fc134dc2b45d0d8d0b6c45fe310cc14161 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 19 Mar 2015 16:12:47 -0500 Subject: [PATCH 014/451] Update README.md --- README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bef6696..0d3489c 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,17 @@ Test harness: http://junit.org Coverage: http://www.eclemma.org/ +Run individual tests using eclemma or the entire test suite using TestRunner + Completed tests: CDLTest.java -In progress: - CookieTest.java +In progress: + +PropertyTest.java + + From e899a2970d1fc5df19008f96537740c7e45cceb1 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 19 Mar 2015 17:30:44 -0500 Subject: [PATCH 015/451] PropertTest.java coverage 94.8% --- JunitTestSuite.java | 3 +- PropertyTest.java | 81 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 PropertyTest.java diff --git a/JunitTestSuite.java b/JunitTestSuite.java index 20b69f9..b9abad1 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -5,7 +5,8 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ CDLTest.class, - CookieTest.class + CookieTest.class, + PropertyTest.class }) public class JunitTestSuite { } \ No newline at end of file diff --git a/PropertyTest.java b/PropertyTest.java new file mode 100644 index 0000000..4354488 --- /dev/null +++ b/PropertyTest.java @@ -0,0 +1,81 @@ +package org.json.junit; + +import java.util.*; + +import static org.junit.Assert.*; + +import org.json.*; +import org.junit.Test; + + +/** + * Tests for JSON-Java Property.java + */ +public class PropertyTest { + + @Test + public void shouldHandleNullProperties() { + + Properties properties = null; + JSONObject jsonObject = Property.toJSONObject(properties); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + @Test + public void shouldHandleEmptyProperties() { + + Properties properties = new Properties(); + JSONObject jsonObject = Property.toJSONObject(properties); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + @Test + public void shouldHandleProperties() { + Properties properties = new Properties(); + + properties.put("Illinois", "Springfield"); + properties.put("Missouri", "Jefferson City"); + properties.put("Washington", "Olympia"); + properties.put("California", "Sacramento"); + properties.put("Indiana", "Indianapolis"); + + JSONObject jsonObject = Property.toJSONObject(properties); + + assertTrue("jsonObject should contain 5 items", jsonObject.length() == 5); + assertTrue("jsonObject should contain Illinois property", + "Springfield".equals(jsonObject.get("Illinois"))); + assertTrue("jsonObject should contain Missouri property", + "Jefferson City".equals(jsonObject.get("Missouri"))); + assertTrue("jsonObject should contain Washington property", + "Olympia".equals(jsonObject.get("Washington"))); + assertTrue("jsonObject should contain California property", + "Sacramento".equals(jsonObject.get("California"))); + assertTrue("jsonObject should contain Indiana property", + "Indianapolis".equals(jsonObject.get("Indiana"))); + } + + @Test + public void shouldHandleNullJSONProperty() { + JSONObject jsonObject= null; + Properties properties = Property.toProperties(jsonObject); + assertTrue("properties should be empty", + properties.size() == 0); + } + + @Test + public void shouldHandleJSONProperty() { + Properties properties = new Properties(); + + properties.put("Illinois", "Springfield"); + properties.put("Missouri", "Jefferson City"); + properties.put("Washington", "Olympia"); + properties.put("California", "Sacramento"); + properties.put("Indiana", "Indianapolis"); + + JSONObject jsonObject = Property.toJSONObject(properties); + Properties jsonProperties = Property.toProperties(jsonObject); + + assertTrue("property objects should match", + properties.equals(jsonProperties)); + } +} \ No newline at end of file From fd56452f6ba8941e786316f4d7229df6cf8ce7a5 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 19 Mar 2015 17:35:16 -0500 Subject: [PATCH 016/451] Update README.md --- README.md | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 0d3489c..e750b72 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,13 @@ # JSON-Java-unit-test -Unit tests to validate the JSON-Java GitHub project code (https://github.com/douglascrockford/JSON-java). - -Test harness: http://junit.org - -Coverage: http://www.eclemma.org/ - -Run individual tests using eclemma or the entire test suite using TestRunner - -Completed tests: - -CDLTest.java - -CookieTest.java - -In progress: - -PropertyTest.java - +Unit tests to validate the JSON-Java GitHub project code (https://github.com/douglascrockford/JSON-java).
+Test harness: http://junit.org
+Coverage: http://www.eclemma.org/
+Run individual tests using eclemma or the entire test suite using TestRunner
+Completed tests:
+CDLTest.java
+CookieTest.java
+PropertyTest.java
+In progress:
+XMLTest.java
From b5b4961a9dfd8b9077866dd54504697b5425d7c2 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 20 Mar 2015 07:34:03 -0500 Subject: [PATCH 017/451] cdltest refactor, in progress --- CDLTest.java | 70 ++++++++++++++++++++++++++-------------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index d5ead3c..78e4fa2 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -41,6 +41,12 @@ public class CDLTest { "0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" + "\"va\tl1\", \"v\bal2\", \"val3\", \"val\f4\", \"val5\", va\'l6, val7\n" ); + String jsonArrayLines = new String( + "[{Col 1:val1, Col 2:val2, Col 3:val3, Col 4:val4, Col 5:val5, Col 6:val6, Col 7:val7}, "+ + "{Col 1:1, Col 2:2, Col 3:3, Col 4:4, Col 5:5, Col 6:6, Col 7:7}, "+ + "{Col 1:true, Col 2:false, Col 3:true, Col 4:true, Col 5:false, Col 6:false, Col 7:false}, "+ + "{Col 1:0.23, Col 2:57.42, Col 3:-234.879, Col 4:2.34e5, Col 5:2.34e5, Col 6:0.0, Col 7:9e-3}, "+ + "{Col 1:\"val1\", Col 2:\"val2\", Col 3:val3, Col 4\"val4\", Col 5:val5, Col 6:val6, Col 7:val7}]"); @Test(expected=NullPointerException.class) public void shouldThrowExceptionOnNullString() { @@ -48,6 +54,24 @@ public class CDLTest { CDL.toJSONArray(nullStr); } + @Test(expected=JSONException.class) + public void shouldHandleUnbalancedQuoteInName() { + String badLine = "Col1, \"Col2\nVal1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test(expected=JSONException.class) + public void shouldHandleUnbalancedQuoteInValue() { + String badLine = "Col1, Col2\n\"Val1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test(expected=JSONException.class) + public void shouldHandleNullInName() { + String badLine = "C\0ol1, Col2\nVal1, Val2"; + CDL.toJSONArray(badLine); + } + @Test /** * Note: This test reveals a bug in the method JavaDoc. It should @@ -74,6 +98,7 @@ public class CDLTest { @Test public void toStringShouldCheckSpecialChars() { + String method = "toStringShouldCheckSpecialChars():"; /** * Given a JSONArray that was not built by CDL, some chars may be * found that would otherwise be filtered out by CDL. @@ -81,49 +106,24 @@ public class CDLTest { JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); jsonArray.put(jsonObject); - // \r will be filtered from name + // \r should be filtered from name jsonObject.put("Col \r1", "V1"); - // \r will be filtered from value + // \r should be filtered from value jsonObject.put("Col 2", "V2\r"); - boolean normalize = true; - List> expectedLines = - sortColumnsInLines("Col 1, Col 2,\nV1, V2", normalize); - List> jsonArrayLines = - sortColumnsInLines(CDL.toString(jsonArray), normalize); - if (!expectedLines.equals(jsonArrayLines)) { - System.out.println("expected: " +expectedLines); - System.out.println("jsonArray: " +jsonArrayLines); - assertTrue("Should filter out certain chars", - false); - } - } + String jsonStr = CDL.toString(jsonArray); - @Test(expected=JSONException.class) - public void shouldHandleUnbalancedQuoteInName() { - String badLine = "Col1, \"Col2\nVal1, Val2"; - CDL.toJSONArray(badLine); - } - - @Test(expected=JSONException.class) - public void shouldHandleUnbalancedQuoteInValue() { - String badLine = "Col1, Col2\n\"Val1, Val2"; - CDL.toJSONArray(badLine); - } - - @Test(expected=JSONException.class) - public void shouldHandleNullInName() { - String badLine = "C\0ol1, Col2\nVal1, Val2"; - CDL.toJSONArray(badLine); + String[] expectedStr = {"\"Col 1\"","Col 2","V1","\"V2\""}; + Util.checkAndRemoveStrings(jsonStr, expectedStr, "[,\n\"]", method); } @Test public void shouldConvertCDLToJSONArray() { + String method = "shouldConvertCDLToJSONArray(): "; JSONArray jsonArray = CDL.toJSONArray(lines); - String resultStr = compareJSONArrayToString(jsonArray, lines); - if (resultStr != null) { - assertTrue("CDL should convert string to JSONArray: " + - resultStr, false); - } + String jsonStr = CDL.toString(jsonArray); + JSONArray expectedJsonArray = new JSONArray(jsonArrayLines); + assertTrue("CDL should convert string to JSONArray", + jsonArray.equals(expectedJsonArray)); } @Test From 441a00afc92ec9655f512f40f9b05ce83c634267 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 20 Mar 2015 15:34:47 -0500 Subject: [PATCH 018/451] CDLTest still in progress --- CDLTest.java | 75 +++++++++++++++++++++++----------------------------- 1 file changed, 33 insertions(+), 42 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index 78e4fa2..f79f2f0 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -41,6 +41,11 @@ public class CDLTest { "0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" + "\"va\tl1\", \"v\bal2\", \"val3\", \"val\f4\", \"val5\", va\'l6, val7\n" ); + + /** + * If lines were to be converted to a JSONArray without the benefit of CDL, + * this would be the input string + */ String jsonArrayLines = new String( "[{Col 1:val1, Col 2:val2, Col 3:val3, Col 4:val4, Col 5:val5, Col 6:val6, Col 7:val7}, "+ "{Col 1:1, Col 2:2, Col 3:3, Col 4:4, Col 5:5, Col 6:6, Col 7:7}, "+ @@ -55,19 +60,19 @@ public class CDLTest { } @Test(expected=JSONException.class) - public void shouldHandleUnbalancedQuoteInName() { + public void shouldThrowExceptionOnUnbalancedQuoteInName() { String badLine = "Col1, \"Col2\nVal1, Val2"; CDL.toJSONArray(badLine); } @Test(expected=JSONException.class) - public void shouldHandleUnbalancedQuoteInValue() { + public void shouldThrowExceptionOnUnbalancedQuoteInValue() { String badLine = "Col1, Col2\n\"Val1, Val2"; CDL.toJSONArray(badLine); } @Test(expected=JSONException.class) - public void shouldHandleNullInName() { + public void shouldThrowExceptionOnNullInName() { String badLine = "C\0ol1, Col2\nVal1, Val2"; CDL.toJSONArray(badLine); } @@ -77,7 +82,7 @@ public class CDLTest { * Note: This test reveals a bug in the method JavaDoc. It should * mention it might return null, or it should return an empty JSONArray. */ - public void shouldHandleOnlyColumnNames() { + public void shouldReturnNullOnOnlyColumnNames() { String columnNameStr = "col1, col2, col3"; JSONArray jsonArray = CDL.toJSONArray(columnNameStr); assertTrue("CDL should return null when only 1 row is given", @@ -89,13 +94,33 @@ public class CDLTest { * Note: This test reveals a bug in the method JavaDoc. It should * mention it might return null, or it should return an empty JSONArray. */ - public void shouldHandleEmptyString() { + public void shouldReturnNullOnEmptyString() { String emptyStr = ""; JSONArray jsonArray = CDL.toJSONArray(emptyStr); assertTrue("CDL should return null when the input string is empty", jsonArray == null); } + @Test + public void shouldConvertCDLToJSONArray() { + JSONArray jsonArray = CDL.toJSONArray(lines); + JSONArray expectedJsonArray = new JSONArray(jsonArrayLines); + assertTrue("CDL should convert string to JSONArray", + jsonArray.equals(expectedJsonArray)); + } + + @Test + public void shouldCreateJSONArrayUsingJSONArray() { + String names = "[Col1, Col2]"; + String values = "V1, V2"; + JSONArray nameJSONArray = new JSONArray(names); + JSONArray jsonArray = CDL.toJSONArray(nameJSONArray, values); + + JSONArray expectedJsonArray = new JSONArray("[{Col1:V1},{Col2:V2}]"); + assertTrue("CDL should create JSONArray from a names JSONArray and a "+ + "string of values", jsonArray.equals(expectedJsonArray)); + } + @Test public void toStringShouldCheckSpecialChars() { String method = "toStringShouldCheckSpecialChars():"; @@ -112,33 +137,8 @@ public class CDLTest { jsonObject.put("Col 2", "V2\r"); String jsonStr = CDL.toString(jsonArray); - String[] expectedStr = {"\"Col 1\"","Col 2","V1","\"V2\""}; - Util.checkAndRemoveStrings(jsonStr, expectedStr, "[,\n\"]", method); - } - - @Test - public void shouldConvertCDLToJSONArray() { - String method = "shouldConvertCDLToJSONArray(): "; - JSONArray jsonArray = CDL.toJSONArray(lines); - String jsonStr = CDL.toString(jsonArray); - JSONArray expectedJsonArray = new JSONArray(jsonArrayLines); - assertTrue("CDL should convert string to JSONArray", - jsonArray.equals(expectedJsonArray)); - } - - @Test - public void shouldCreateJSONArrayUsingJSONArray() { - String names = "Col1, Col2"; - String nameArrayStr = "[" +names+ "]"; - String values = "V1, V2"; - JSONArray nameJSONArray = new JSONArray(nameArrayStr); - JSONArray jsonArray = CDL.toJSONArray(nameJSONArray, values); - String combinedStr = names+ "\n" +values; - String resultStr = compareJSONArrayToString(jsonArray, combinedStr); - if (resultStr != null) { - assertTrue("CDL should convert JSONArray and string to JSONArray: " + - resultStr, false); - } + String expectedStr = {"Col 1, Col 2","V1","\"V2\""}; + // Util.checkAndRemoveStrings(jsonStr, expectedStr, "[,\n\"]", method); } @Test @@ -152,16 +152,7 @@ public class CDLTest { final boolean doNotNormalize = false; JSONArray jsonArray = CDL.toJSONArray(lines); String jsonStr = CDL.toString(jsonArray); - // normal sorted - List> sortedLines = sortColumnsInLines(lines, normalize); - // sorted, should already be normalized - List> sortedJsonStr = sortColumnsInLines(jsonStr, doNotNormalize); - boolean result = sortedLines.equals(sortedJsonStr); - if (!result) { - System.out.println("lines: " +sortedLines); - System.out.println("jsonStr: " +sortedJsonStr); - assertTrue("CDL should convert JSONArray back to original string: " + - lines.equals(jsonStr), false); + assertTrue("CDL should convert string to JSONArray to string", } } From 68e01afd7ea94a66432637c864fda2c032d0c8d2 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 20 Mar 2015 18:01:27 -0500 Subject: [PATCH 019/451] first checkin --- Util.java | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Util.java diff --git a/Util.java b/Util.java new file mode 100644 index 0000000..89743c0 --- /dev/null +++ b/Util.java @@ -0,0 +1,56 @@ +package org.json.junit; + +import static org.junit.Assert.*; + +public class Util { + + /** + * Utility method to check for a target string, then remove it from + * the string to be searched. + * @param jsonStr the string to be searched + * @param expectedStr the target string to search for + * @param assertStr the error message for the assert + * @return new string with target substring removed + */ + public static String checkAndRemoveString( + String jsonStr, String expectedStr, String assertStr) { + int idx = jsonStr.indexOf(expectedStr); + assertTrue(assertStr, idx != -1); + String newStr = jsonStr.substring(0, idx)+ + jsonStr.substring(idx+expectedStr.length()); + return newStr; + } + + /** + * Utility method to strip out selected punctuation chars and confirm + * that jsonStr is now empty + * @param jsonStr the string to be verified + * @param regexStr regex string of the chars to remove + * @param assertStr the error message for the assert + */ + public static void verifyEmptyJsonStr(String jsonStr, String regexStr, + String assertStr) { + jsonStr = jsonStr.replaceAll(regexStr, ""); + assertTrue(assertStr, jsonStr.length() == 0); + } + + /** + * Utility method to check for a set of target strings, + * then remove them from the string to be searched. + * When completed, punctuation marks are stripped out and + * the string to be searched is confirmed as empty + * @param jsonStr the string to be searched + * @param expectedStrArray the target strings to search for + * @param regexStr regex string of the chars to remove + * @param methodStr the method name + */ + public static void checkAndRemoveStrings(String jsonStr, + String[] expectedStr, String regexStr, String methodStr) { + for (int i = 0; i < expectedStr.length; ++i) { + jsonStr = Util.checkAndRemoveString(jsonStr, expectedStr[i], + methodStr+expectedStr+" should be included in string output"); + } + Util.verifyEmptyJsonStr(jsonStr, regexStr, + methodStr+" jsonStr should be empty"); + } +} From dca3726bf17c3b80a9b56567dc30661d0a9fa25f Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:13:44 -0500 Subject: [PATCH 020/451] Update README.md --- README.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e750b72..bfe1619 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,32 @@ # JSON-Java-unit-test Unit tests to validate the JSON-Java GitHub project code (https://github.com/douglascrockford/JSON-java).
+ Test harness: http://junit.org
Coverage: http://www.eclemma.org/
-Run individual tests using eclemma or the entire test suite using TestRunner
+ +Eclipse is the recommended development environment. +Run individual tests or *JunitTestSuite* using ~~EclEmma Coverage~~, or execute the *TestRunner* application directly.
+ +Test filenames should consist of the name of the module being tested, with the suffix "Test". +For example, *Cookie.java* is tested by *CookieTest.java*. +When adding a new unit test, don't forget to update *JunitTestSuite.java*. + +The fundamental issues with JSON-Java testing are: +* *JSONObjects* are unordered, making simple string comparison ineffective. +* Comparisons via equals() is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. +* Access to the JSONArray and JSONObject internal containers for comparison is not currently available. +* JSONObject sometimes wraps entries in quotes, other times does not, complicating comparisons. + +When you start working on a test, add the empty file to the repository, so that others will know that test is taken. + +A unit test is considered complete when the coverage is >= 90% as measured by EclEmma. + +| Test file name | Coverage | Comments | +| ------------- | ------------- | +| CookieTest.java | 97.5% | Completed | +| PropertyTest.java | 94.8% | Completed | +| CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked | + Completed tests:
CDLTest.java
CookieTest.java
From 1bde00ed4c6b42add6702f82a06f80c8262f00d3 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:14:23 -0500 Subject: [PATCH 021/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bfe1619..ee72386 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Test harness: http://junit.org
Coverage: http://www.eclemma.org/
Eclipse is the recommended development environment. -Run individual tests or *JunitTestSuite* using ~~EclEmma Coverage~~, or execute the *TestRunner* application directly.
+Run individual tests or *JunitTestSuite* using *EclEmma Coverage*, or execute the _TestRunner_ application directly.
Test filenames should consist of the name of the module being tested, with the suffix "Test". For example, *Cookie.java* is tested by *CookieTest.java*. From b0ce7f3bd94ae52c1efa5a797bf473201edd3ef6 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:15:46 -0500 Subject: [PATCH 022/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ee72386..0e03195 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Test harness: http://junit.org
Coverage: http://www.eclemma.org/
Eclipse is the recommended development environment. -Run individual tests or *JunitTestSuite* using *EclEmma Coverage*, or execute the _TestRunner_ application directly.
+Run individual tests or JunitTestSuite using *EclEmma Coverage*, or execute the TestRunner application directly.
Test filenames should consist of the name of the module being tested, with the suffix "Test". For example, *Cookie.java* is tested by *CookieTest.java*. From 09b5562ad9b699db72d92400ec16e4f03f563012 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:18:56 -0500 Subject: [PATCH 023/451] Update README.md --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 0e03195..1837be9 100644 --- a/README.md +++ b/README.md @@ -8,24 +8,24 @@ Eclipse is the recommended development environment. Run individual tests or JunitTestSuite using *EclEmma Coverage*, or execute the TestRunner application directly.
Test filenames should consist of the name of the module being tested, with the suffix "Test". -For example, *Cookie.java* is tested by *CookieTest.java*. -When adding a new unit test, don't forget to update *JunitTestSuite.java*. +For example, Cookie.java is tested by CookieTest.java. +When adding a new unit test, don't forget to update JunitTestSuite.java. The fundamental issues with JSON-Java testing are: -* *JSONObjects* are unordered, making simple string comparison ineffective. -* Comparisons via equals() is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. -* Access to the JSONArray and JSONObject internal containers for comparison is not currently available. -* JSONObject sometimes wraps entries in quotes, other times does not, complicating comparisons. +* JSONObjects are unordered, making simple string comparison ineffective. +* Comparisons via equals() is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. +* Access to the JSONArray and JSONObject internal containers for comparison is not currently available. +* JSONObject sometimes wraps entries in quotes, other times does not, complicating comparisons. When you start working on a test, add the empty file to the repository, so that others will know that test is taken. A unit test is considered complete when the coverage is >= 90% as measured by EclEmma. -| Test file name | Coverage | Comments | +| Test file name | Coverage | Comments | ------------- | ------------- | -| CookieTest.java | 97.5% | Completed | -| PropertyTest.java | 94.8% | Completed | -| CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked | +| CookieTest.java | 97.5% | Completed +| PropertyTest.java | 94.8% | Completed +| CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked Completed tests:
CDLTest.java
From 42ad66b032cf27d1ae13878ac9f7473c0e20605f Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:19:32 -0500 Subject: [PATCH 024/451] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1837be9..0dd42ba 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,10 @@ When you start working on a test, add the empty file to the repository, so that A unit test is considered complete when the coverage is >= 90% as measured by EclEmma. -| Test file name | Coverage | Comments +| Test file name | Coverage | Comments | | ------------- | ------------- | -| CookieTest.java | 97.5% | Completed -| PropertyTest.java | 94.8% | Completed +| CookieTest.java | 97.5% | Completed | +| PropertyTest.java | 94.8% | Completed | | CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked Completed tests:
From 2b0a9cc7c82c766348131530d6e9a4224b085951 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:19:58 -0500 Subject: [PATCH 025/451] Update README.md --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0dd42ba..4c9de4a 100644 --- a/README.md +++ b/README.md @@ -22,10 +22,15 @@ When you start working on a test, add the empty file to the repository, so that A unit test is considered complete when the coverage is >= 90% as measured by EclEmma. | Test file name | Coverage | Comments | + | ------------- | ------------- | + | CookieTest.java | 97.5% | Completed | + | PropertyTest.java | 94.8% | Completed | -| CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked + +| CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked | + Completed tests:
CDLTest.java
From 8374382947a12c388be9979fa0502cc526849c2e Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:22:54 -0500 Subject: [PATCH 026/451] Update README.md --- README.md | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 4c9de4a..d41135b 100644 --- a/README.md +++ b/README.md @@ -17,18 +17,14 @@ The fundamental issues with JSON-Java testing are: * Access to the JSONArray and JSONObject internal containers for comparison is not currently available. * JSONObject sometimes wraps entries in quotes, other times does not, complicating comparisons. -When you start working on a test, add the empty file to the repository, so that others will know that test is taken. +When you start working on a test, add the empty file to the repository and update the readme, so that others will know that test is taken. A unit test is considered complete when the coverage is >= 90% as measured by EclEmma. -| Test file name | Coverage | Comments | - -| ------------- | ------------- | - +| Test-file-name | Coverage | Comments | +| ------------- | ------------- | ---- | | CookieTest.java | 97.5% | Completed | - | PropertyTest.java | 94.8% | Completed | - | CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked | From e150039261f5dbba8b7ca1948457487033501192 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:23:49 -0500 Subject: [PATCH 027/451] Update README.md --- README.md | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index d41135b..ecb61f6 100644 --- a/README.md +++ b/README.md @@ -21,18 +21,10 @@ When you start working on a test, add the empty file to the repository and updat A unit test is considered complete when the coverage is >= 90% as measured by EclEmma. -| Test-file-name | Coverage | Comments | +| Test file name | Coverage | Comments | | ------------- | ------------- | ---- | | CookieTest.java | 97.5% | Completed | | PropertyTest.java | 94.8% | Completed | | CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked | - - -Completed tests:
-CDLTest.java
-CookieTest.java
-PropertyTest.java
-In progress:
-XMLTest.java
- +| XMLTest.java | 0% | Just started - stleary | From f8c37b1e05cf07f4ec26ce2d6304f62c526a4472 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:27:38 -0500 Subject: [PATCH 028/451] Update README.md --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index ecb61f6..0e9ef5a 100644 --- a/README.md +++ b/README.md @@ -27,4 +27,18 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | PropertyTest.java | 94.8% | Completed | | CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked | | XMLTest.java | 0% | Just started - stleary | +| | | | +| CookieList.java | | | +| HTTP.java | | | +| HTTPTokener.java | | | +| JSONArray.java | | | +|JSONException.java | | | +| JSONML.java | | | +| JSONObject.java | | | +| JSONString.java | | | +| JSONStringer.java | | | +| JSONTokener.java | | | +| JSONWriter.java | | | +| XMLTokener.java| | | + From e4ebd8c44325805a0f272a7fd898b669fb04929b Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:32:47 -0500 Subject: [PATCH 029/451] Update README.md --- README.md | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 0e9ef5a..f6140e5 100644 --- a/README.md +++ b/README.md @@ -23,22 +23,25 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | +| Total coverage | 26.5% | | | +| | | | | CookieTest.java | 97.5% | Completed | | PropertyTest.java | 94.8% | Completed | | CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked | | XMLTest.java | 0% | Just started - stleary | | | | | -| CookieList.java | | | -| HTTP.java | | | -| HTTPTokener.java | | | -| JSONArray.java | | | -|JSONException.java | | | -| JSONML.java | | | -| JSONObject.java | | | +| CookieList.java |0% | | +| HTTP.java | 0%| | +| HTTPTokener.java |0% | | +| JSONArray.java |25.3% | | +|JSONException.java | 26.7% | | +| JSONML.java | 0%| | +| JSONObject.java | 27.6% | | +| JSONObject.Null | 18.8% | | | | JSONString.java | | | -| JSONStringer.java | | | -| JSONTokener.java | | | -| JSONWriter.java | | | -| XMLTokener.java| | | +| JSONStringer.java | 0%| | +| JSONTokener.java |65.4% | | +| JSONWriter.java | 0% | | +| XMLTokener.java| 0%| | From e4ef254d8f08ae7e40220a043b1a9407797d3b5a Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:33:12 -0500 Subject: [PATCH 030/451] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index f6140e5..4bd1e98 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,6 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | JSONML.java | 0%| | | JSONObject.java | 27.6% | | | JSONObject.Null | 18.8% | | | -| JSONString.java | | | | JSONStringer.java | 0%| | | JSONTokener.java |65.4% | | | JSONWriter.java | 0% | | From 25596c9578b78c2fa84bf6629878f7b803d50b34 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:34:04 -0500 Subject: [PATCH 031/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4bd1e98..2993938 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ When adding a new unit test, don't forget to update JunitTestSuite.java. The fundamental issues with JSON-Java testing are: * JSONObjects are unordered, making simple string comparison ineffective. -* Comparisons via equals() is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. +* Comparisons via **equals()** is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. * Access to the JSONArray and JSONObject internal containers for comparison is not currently available. * JSONObject sometimes wraps entries in quotes, other times does not, complicating comparisons. From d0223c2d08a9e188f841e4dbce0c3e1a72b64c55 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:35:24 -0500 Subject: [PATCH 032/451] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2993938..c447eba 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # JSON-Java-unit-test + Unit tests to validate the JSON-Java GitHub project code (https://github.com/douglascrockford/JSON-java).
Test harness: http://junit.org
From 231c3de79ec9de45a80be147bb41a5e85bd972e8 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:41:25 -0500 Subject: [PATCH 033/451] Update README.md --- README.md | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index c447eba..9227a0e 100644 --- a/README.md +++ b/README.md @@ -24,24 +24,22 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 26.5% | | | +| Total coverage | 19% | | | | | | | -| CookieTest.java | 97.5% | Completed | -| PropertyTest.java | 94.8% | Completed | | CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked | -| XMLTest.java | 0% | Just started - stleary | -| | | | +| CookieTest.java | 97.5% | Completed | | CookieList.java |0% | | | HTTP.java | 0%| | | HTTPTokener.java |0% | | -| JSONArray.java |25.3% | | +| JSONArray.java |15.3% | | |JSONException.java | 26.7% | | | JSONML.java | 0%| | -| JSONObject.java | 27.6% | | -| JSONObject.Null | 18.8% | | | +| JSONObject.Null | 8.9% | | | | JSONStringer.java | 0%| | -| JSONTokener.java |65.4% | | +| JSONTokener.java |59.8% | | | JSONWriter.java | 0% | | +| PropertyTest.java | 94.8% | Completed | +| XMLTest.java | 0% | Just started - stleary | | XMLTokener.java| 0%| | From 30c31db095a2f5d4515ec971f7c736fe4c204dc4 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 21 Mar 2015 13:44:29 -0500 Subject: [PATCH 034/451] Reverting to https://github.com/stleary/JSON-Java-unit-test/commit/4a5809910bc7a2bbe5892f9336eae0a609af9912 until I have figured out the best way to refactor the code --- CDLTest.java | 125 +++++++++++++++++++++++++++------------------------ 1 file changed, 67 insertions(+), 58 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index f79f2f0..d5ead3c 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -42,47 +42,18 @@ public class CDLTest { "\"va\tl1\", \"v\bal2\", \"val3\", \"val\f4\", \"val5\", va\'l6, val7\n" ); - /** - * If lines were to be converted to a JSONArray without the benefit of CDL, - * this would be the input string - */ - String jsonArrayLines = new String( - "[{Col 1:val1, Col 2:val2, Col 3:val3, Col 4:val4, Col 5:val5, Col 6:val6, Col 7:val7}, "+ - "{Col 1:1, Col 2:2, Col 3:3, Col 4:4, Col 5:5, Col 6:6, Col 7:7}, "+ - "{Col 1:true, Col 2:false, Col 3:true, Col 4:true, Col 5:false, Col 6:false, Col 7:false}, "+ - "{Col 1:0.23, Col 2:57.42, Col 3:-234.879, Col 4:2.34e5, Col 5:2.34e5, Col 6:0.0, Col 7:9e-3}, "+ - "{Col 1:\"val1\", Col 2:\"val2\", Col 3:val3, Col 4\"val4\", Col 5:val5, Col 6:val6, Col 7:val7}]"); - @Test(expected=NullPointerException.class) public void shouldThrowExceptionOnNullString() { String nullStr = null; CDL.toJSONArray(nullStr); } - @Test(expected=JSONException.class) - public void shouldThrowExceptionOnUnbalancedQuoteInName() { - String badLine = "Col1, \"Col2\nVal1, Val2"; - CDL.toJSONArray(badLine); - } - - @Test(expected=JSONException.class) - public void shouldThrowExceptionOnUnbalancedQuoteInValue() { - String badLine = "Col1, Col2\n\"Val1, Val2"; - CDL.toJSONArray(badLine); - } - - @Test(expected=JSONException.class) - public void shouldThrowExceptionOnNullInName() { - String badLine = "C\0ol1, Col2\nVal1, Val2"; - CDL.toJSONArray(badLine); - } - @Test /** * Note: This test reveals a bug in the method JavaDoc. It should * mention it might return null, or it should return an empty JSONArray. */ - public void shouldReturnNullOnOnlyColumnNames() { + public void shouldHandleOnlyColumnNames() { String columnNameStr = "col1, col2, col3"; JSONArray jsonArray = CDL.toJSONArray(columnNameStr); assertTrue("CDL should return null when only 1 row is given", @@ -94,36 +65,15 @@ public class CDLTest { * Note: This test reveals a bug in the method JavaDoc. It should * mention it might return null, or it should return an empty JSONArray. */ - public void shouldReturnNullOnEmptyString() { + public void shouldHandleEmptyString() { String emptyStr = ""; JSONArray jsonArray = CDL.toJSONArray(emptyStr); assertTrue("CDL should return null when the input string is empty", jsonArray == null); } - @Test - public void shouldConvertCDLToJSONArray() { - JSONArray jsonArray = CDL.toJSONArray(lines); - JSONArray expectedJsonArray = new JSONArray(jsonArrayLines); - assertTrue("CDL should convert string to JSONArray", - jsonArray.equals(expectedJsonArray)); - } - - @Test - public void shouldCreateJSONArrayUsingJSONArray() { - String names = "[Col1, Col2]"; - String values = "V1, V2"; - JSONArray nameJSONArray = new JSONArray(names); - JSONArray jsonArray = CDL.toJSONArray(nameJSONArray, values); - - JSONArray expectedJsonArray = new JSONArray("[{Col1:V1},{Col2:V2}]"); - assertTrue("CDL should create JSONArray from a names JSONArray and a "+ - "string of values", jsonArray.equals(expectedJsonArray)); - } - @Test public void toStringShouldCheckSpecialChars() { - String method = "toStringShouldCheckSpecialChars():"; /** * Given a JSONArray that was not built by CDL, some chars may be * found that would otherwise be filtered out by CDL. @@ -131,14 +81,64 @@ public class CDLTest { JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); jsonArray.put(jsonObject); - // \r should be filtered from name + // \r will be filtered from name jsonObject.put("Col \r1", "V1"); - // \r should be filtered from value + // \r will be filtered from value jsonObject.put("Col 2", "V2\r"); - String jsonStr = CDL.toString(jsonArray); + boolean normalize = true; + List> expectedLines = + sortColumnsInLines("Col 1, Col 2,\nV1, V2", normalize); + List> jsonArrayLines = + sortColumnsInLines(CDL.toString(jsonArray), normalize); + if (!expectedLines.equals(jsonArrayLines)) { + System.out.println("expected: " +expectedLines); + System.out.println("jsonArray: " +jsonArrayLines); + assertTrue("Should filter out certain chars", + false); + } + } - String expectedStr = {"Col 1, Col 2","V1","\"V2\""}; - // Util.checkAndRemoveStrings(jsonStr, expectedStr, "[,\n\"]", method); + @Test(expected=JSONException.class) + public void shouldHandleUnbalancedQuoteInName() { + String badLine = "Col1, \"Col2\nVal1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test(expected=JSONException.class) + public void shouldHandleUnbalancedQuoteInValue() { + String badLine = "Col1, Col2\n\"Val1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test(expected=JSONException.class) + public void shouldHandleNullInName() { + String badLine = "C\0ol1, Col2\nVal1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test + public void shouldConvertCDLToJSONArray() { + JSONArray jsonArray = CDL.toJSONArray(lines); + String resultStr = compareJSONArrayToString(jsonArray, lines); + if (resultStr != null) { + assertTrue("CDL should convert string to JSONArray: " + + resultStr, false); + } + } + + @Test + public void shouldCreateJSONArrayUsingJSONArray() { + String names = "Col1, Col2"; + String nameArrayStr = "[" +names+ "]"; + String values = "V1, V2"; + JSONArray nameJSONArray = new JSONArray(nameArrayStr); + JSONArray jsonArray = CDL.toJSONArray(nameJSONArray, values); + String combinedStr = names+ "\n" +values; + String resultStr = compareJSONArrayToString(jsonArray, combinedStr); + if (resultStr != null) { + assertTrue("CDL should convert JSONArray and string to JSONArray: " + + resultStr, false); + } } @Test @@ -152,7 +152,16 @@ public class CDLTest { final boolean doNotNormalize = false; JSONArray jsonArray = CDL.toJSONArray(lines); String jsonStr = CDL.toString(jsonArray); - assertTrue("CDL should convert string to JSONArray to string", + // normal sorted + List> sortedLines = sortColumnsInLines(lines, normalize); + // sorted, should already be normalized + List> sortedJsonStr = sortColumnsInLines(jsonStr, doNotNormalize); + boolean result = sortedLines.equals(sortedJsonStr); + if (!result) { + System.out.println("lines: " +sortedLines); + System.out.println("jsonStr: " +sortedJsonStr); + assertTrue("CDL should convert JSONArray back to original string: " + + lines.equals(jsonStr), false); } } From 2876b27ec56603de6627c7ef6d555ba021579c71 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sun, 22 Mar 2015 17:48:21 -0500 Subject: [PATCH 035/451] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9227a0e..1cef7e3 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,9 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 19% | | | +| Total coverage | 20.8% | | | | | | | -| CDLTest.java | 94.8% | Relies too much on string tests, needs to be reworked | +| CDLTest.java | 94.8% | Completed | | CookieTest.java | 97.5% | Completed | | CookieList.java |0% | | | HTTP.java | 0%| | @@ -34,9 +34,9 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | JSONArray.java |15.3% | | |JSONException.java | 26.7% | | | JSONML.java | 0%| | -| JSONObject.Null | 8.9% | | | +| JSONObject.Null | 13.4% | | | | JSONStringer.java | 0%| | -| JSONTokener.java |59.8% | | +| JSONTokener.java |65.4% | | | JSONWriter.java | 0% | | | PropertyTest.java | 94.8% | Completed | | XMLTest.java | 0% | Just started - stleary | From 964cb540fb4af3905e60199fc7ec8329cec923bf Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 22 Mar 2015 17:59:43 -0500 Subject: [PATCH 036/451] completed 94.8% coverage --- CDLTest.java | 269 ++++++++++++++++----------------------------------- 1 file changed, 82 insertions(+), 187 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index d5ead3c..4ff9c38 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -1,30 +1,24 @@ package org.json.junit; -import static org.junit.Assert.*; -import java.io.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; + import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import static org.junit.Assert.*; import org.junit.Test; + import org.json.JSONException; import org.json.JSONObject; import org.json.JSONArray; import org.json.CDL; - /** - * Tests for {@link CDL}. + * Tests for CDL.java. * CDL provides an application level API, but it is not used by the * reference app. To test it, strings will be converted to JSON-Java classes * and then converted back. Since each row is an unordered JSONObject, * can't use a simple string compare to check for equality. * @author JSON.org - * @version 2015-03-18 + * @version 2015-03-22 * */ public class CDLTest { @@ -42,6 +36,20 @@ public class CDLTest { "\"va\tl1\", \"v\bal2\", \"val3\", \"val\f4\", \"val5\", va\'l6, val7\n" ); + /** + * Something I did not expect is that CDL.toJSONArray() adds all values as + * strings, with no filtering or conversions. I suppose this makes it + * easier to emit it as CDL later. For testing, it means that the + * expected JSONObject values all must be quoted in the cases where the + * JSONObject parsing might normally convert the value into a non-string. + */ + String expectedLines = new String( + "[{Col 1:val1, Col 2:val2, Col 3:val3, Col 4:val4, Col 5:val5, Col 6:val6, Col 7:val7}, "+ + "{Col 1:1, Col 2:2, Col 3:3, Col 4:4, Col 5:5, Col 6:6, Col 7:7}, "+ + "{Col 1:true, Col 2:false, Col 3:true, Col 4:true, Col 5:false, Col 6:false, Col 7:false}, "+ + "{Col 1:\"0.23\", Col 2:\"57.42\", Col 3:\"5e27\", Col 4:\"-234.879\", Col 5:\"2.34e5\", Col 6:\"0.0\", Col 7:\"9e-3\"}, "+ + "{Col 1:\"va\tl1\", Col 2:\"v\bal2\", Col 3:val3, Col 4:\"val\f4\", Col 5:val5, Col 6:va\'l6, Col 7:val7}]"); + @Test(expected=NullPointerException.class) public void shouldThrowExceptionOnNullString() { String nullStr = null; @@ -72,32 +80,6 @@ public class CDLTest { jsonArray == null); } - @Test - public void toStringShouldCheckSpecialChars() { - /** - * Given a JSONArray that was not built by CDL, some chars may be - * found that would otherwise be filtered out by CDL. - */ - JSONArray jsonArray = new JSONArray(); - JSONObject jsonObject = new JSONObject(); - jsonArray.put(jsonObject); - // \r will be filtered from name - jsonObject.put("Col \r1", "V1"); - // \r will be filtered from value - jsonObject.put("Col 2", "V2\r"); - boolean normalize = true; - List> expectedLines = - sortColumnsInLines("Col 1, Col 2,\nV1, V2", normalize); - List> jsonArrayLines = - sortColumnsInLines(CDL.toString(jsonArray), normalize); - if (!expectedLines.equals(jsonArrayLines)) { - System.out.println("expected: " +expectedLines); - System.out.println("jsonArray: " +jsonArrayLines); - assertTrue("Should filter out certain chars", - false); - } - } - @Test(expected=JSONException.class) public void shouldHandleUnbalancedQuoteInName() { String badLine = "Col1, \"Col2\nVal1, Val2"; @@ -116,29 +98,46 @@ public class CDLTest { CDL.toJSONArray(badLine); } + + @Test + public void toStringShouldCheckSpecialChars() { + /** + * Given a JSONArray that was not built by CDL, some chars may be + * found that would otherwise be filtered out by CDL. + */ + JSONArray jsonArray = new JSONArray(); + JSONObject jsonObject = new JSONObject(); + jsonArray.put(jsonObject); + // \r will be filtered from name + jsonObject.put("Col \r1", "V1"); + // \r will be filtered from value + jsonObject.put("Col 2", "V2\r"); + assertTrue("expected length should be 1",jsonArray.length() == 1); + String cdlStr = CDL.toString(jsonArray); + jsonObject = jsonArray.getJSONObject(0); + assertTrue(cdlStr.contains("\"Col 1\"")); + assertTrue(cdlStr.contains("Col 2")); + assertTrue(cdlStr.contains("V1")); + assertTrue(cdlStr.contains("\"V2\"")); + } + @Test public void shouldConvertCDLToJSONArray() { + // this array is built by CDL JSONArray jsonArray = CDL.toJSONArray(lines); - String resultStr = compareJSONArrayToString(jsonArray, lines); - if (resultStr != null) { - assertTrue("CDL should convert string to JSONArray: " + - resultStr, false); - } + // This array is built from JSON parsing + JSONArray expectedJsonArray = new JSONArray(expectedLines); + compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } @Test public void shouldCreateJSONArrayUsingJSONArray() { - String names = "Col1, Col2"; - String nameArrayStr = "[" +names+ "]"; + String nameArrayStr = "[Col1, Col2]"; String values = "V1, V2"; JSONArray nameJSONArray = new JSONArray(nameArrayStr); JSONArray jsonArray = CDL.toJSONArray(nameJSONArray, values); - String combinedStr = names+ "\n" +values; - String resultStr = compareJSONArrayToString(jsonArray, combinedStr); - if (resultStr != null) { - assertTrue("CDL should convert JSONArray and string to JSONArray: " + - resultStr, false); - } + JSONArray expectedJsonArray = new JSONArray("[{Col1:V1,Col2:V2}]"); + compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } @Test @@ -148,147 +147,43 @@ public class CDLTest { * The string contains a typical variety of values * that might be found in a real CDL. */ - final boolean normalize = true; - final boolean doNotNormalize = false; JSONArray jsonArray = CDL.toJSONArray(lines); String jsonStr = CDL.toString(jsonArray); - // normal sorted - List> sortedLines = sortColumnsInLines(lines, normalize); - // sorted, should already be normalized - List> sortedJsonStr = sortColumnsInLines(jsonStr, doNotNormalize); - boolean result = sortedLines.equals(sortedJsonStr); - if (!result) { - System.out.println("lines: " +sortedLines); - System.out.println("jsonStr: " +sortedJsonStr); - assertTrue("CDL should convert JSONArray back to original string: " + - lines.equals(jsonStr), false); + JSONArray finalJsonArray = CDL.toJSONArray(jsonStr); + JSONArray expectedJsonArray = new JSONArray(expectedLines); + compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); + } + + + /////////////////////////// UTILITY METHODS ///////////////////////// + + /** + * Compares two json arrays for equality + * @param jsonArray created by the code to be tested + * @param expectedJsonArray created specifically for compar + */ + private void compareActualVsExpectedJsonArrays(JSONArray jsonArray, + JSONArray expectedJsonArray) { + assertTrue("jsonArray lengths should be equal", + jsonArray.length() == expectedJsonArray.length()); + for (int i = 0; i < jsonArray.length(); ++i) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + JSONObject expectedJsonObject = expectedJsonArray.getJSONObject(i); + assertTrue("jsonObjects should have the same length", + jsonObject.length() == expectedJsonObject.length()); + Iterator keys = jsonObject.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object value = jsonObject.get(key); + String testStr = "row: "+i+" key: "+key+" val: "+value.toString(); + String actualStr = expectedJsonObject .get(key).toString(); + assertTrue("values should be equal for actual: "+testStr+ + " expected: "+actualStr, + value.equals(expectedJsonArray.getJSONObject(i). + get(key).toString())); + } } } - - /******************************************************************\ - * SUPPORT AND UTILITY - \******************************************************************/ - - /** - * Compares a JSON array to the original string. The top row of the - * string contains the JSONObject keys and the remaining rows contain - * the values. The JSONObject in each JSONArray row is expected to have - * an entry corresponding to each key/value pair in the string. - * Each JSONObject row is unordered in its own way. - * @param jsonArray the JSONArray which was created from the string - * @param str the string which was used to create the JSONArray - * @return null if equal, otherwise error description - */ - private String compareJSONArrayToString(JSONArray jsonArray, String str) { - int rows = jsonArray.length(); - StringReader sr = new StringReader(str); - BufferedReader reader = new BufferedReader(sr); - try { - // first line contains the keys to the JSONObject array entries - String columnNames = reader.readLine(); - columnNames = normalizeString(columnNames); - String[] keys = columnNames.split(","); - /** - * Each line contains the values for the corresponding - * JSONObject array entry - */ - for (int i = 0; i < rows; ++i) { - String line = reader.readLine(); - line = normalizeString(line); - String[] values = line.split(","); - // need a value for every key to proceed - if (keys.length != values.length) { - System.out.println("keys: " + Arrays.toString(keys)); - System.out.println("values: " + Arrays.toString(values)); - return("row: " +i+ " key and value counts do not match"); - } - JSONObject jsonObject = jsonArray.getJSONObject(i); - // need a key for every JSONObject entry to proceed - if (keys.length != jsonObject.length()) { - System.out.println("keys: " + Arrays.toString(keys)); - System.out.println("jsonObject: " + jsonObject.toString()); - return("row: " +i+ " key and jsonObject counts do not match"); - } - // convert string entries into a natural order map. - Map strMap = new TreeMap(); - for (int j = 0; j < keys.length; ++j) { - strMap.put(keys[j], values[j]); - } - // put the JSONObjet key/value pairs in natural key order - Iterator keyIt = jsonObject.keys(); - Map jsonObjectMap = new TreeMap(); - while (keyIt.hasNext()) { - String key = keyIt.next(); - jsonObjectMap.put(key, jsonObject.get(key).toString()); - } - if (!strMap.equals(jsonObjectMap)) { - System.out.println("strMap: " +strMap.toString()); - System.out.println("jsonObjectMap: " +jsonObjectMap.toString()); - return("row: " +i+ "string does not match jsonObject"); - } - } - } catch (IOException ignore) { - } catch (JSONException ignore) {} - return null; - } - - /** - * Utility to trim and remove internal quotes from comma delimited strings. - * Need to do this because JSONObject does the same thing - * @param line the line to be normalized - * @return the normalized line - */ - private String normalizeString(String line) { - StringBuilder builder = new StringBuilder(); - boolean comma = false; - String[] values = line.split(","); - for (int i = 0; i < values.length; ++i) { - if (comma) { - builder.append(","); - } - comma = true; - values[i] = values[i].trim(); - // strip optional surrounding quotes - values[i] = values[i].replaceAll("^\"|\"$", ""); - builder.append(values[i]); - } - return builder.toString(); - } - - /** - * Utility to sort the columns in a (possibly) multi-lined string. - * The columns are column separated. Need to do this because - * JSONObects are not ordered - * @param string the string to be sorted - * @param normalize flag, true if line should be normalized - * @return a list of sorted lines, where each line is a list sorted - * in natural key order - */ - private List> sortColumnsInLines(String string, - boolean normalizeFlag) { - List> lineList = new ArrayList>(); - StringReader sr = new StringReader(string); - BufferedReader reader = new BufferedReader(sr); - try { - while (true) { - String line = reader.readLine(); - if (line == null) { - break; - } - if (normalizeFlag) { - line = normalizeString(line); - } - List columnList = new ArrayList(); - String[] values = line.split(","); - for (int i = 0; i < values.length; ++i) { - columnList.add(values[i]); - } - Collections.sort(columnList); - lineList.add(columnList); - } - } catch (IOException ignore) {} - return lineList; - } } \ No newline at end of file From 8b9c3cbf476cae2c2e295bcd4121a4b8e6fc26fe Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 22 Mar 2015 20:36:55 -0500 Subject: [PATCH 037/451] XMLTest, in progress --- XMLTest.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 XMLTest.java diff --git a/XMLTest.java b/XMLTest.java new file mode 100644 index 0000000..e69de29 From 4fbe651e57570b7841c16624d9b8831a7703d027 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 22 Mar 2015 20:37:24 -0500 Subject: [PATCH 038/451] XMLTest, in progress --- CDLTest.java | 40 ++--------------- JunitTestSuite.java | 3 +- Util.java | 107 +++++++++++++++++++++++++------------------- XMLTest.java | 93 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 160 insertions(+), 83 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index 4ff9c38..53284d0 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -1,8 +1,5 @@ package org.json.junit; - -import java.util.Iterator; - import static org.junit.Assert.*; import org.junit.Test; @@ -127,7 +124,7 @@ public class CDLTest { JSONArray jsonArray = CDL.toJSONArray(lines); // This array is built from JSON parsing JSONArray expectedJsonArray = new JSONArray(expectedLines); - compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } @Test @@ -137,7 +134,7 @@ public class CDLTest { JSONArray nameJSONArray = new JSONArray(nameArrayStr); JSONArray jsonArray = CDL.toJSONArray(nameJSONArray, values); JSONArray expectedJsonArray = new JSONArray("[{Col1:V1,Col2:V2}]"); - compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } @Test @@ -151,39 +148,8 @@ public class CDLTest { String jsonStr = CDL.toString(jsonArray); JSONArray finalJsonArray = CDL.toJSONArray(jsonStr); JSONArray expectedJsonArray = new JSONArray(expectedLines); - compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); + Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } - - /////////////////////////// UTILITY METHODS ///////////////////////// - - /** - * Compares two json arrays for equality - * @param jsonArray created by the code to be tested - * @param expectedJsonArray created specifically for compar - */ - private void compareActualVsExpectedJsonArrays(JSONArray jsonArray, - JSONArray expectedJsonArray) { - assertTrue("jsonArray lengths should be equal", - jsonArray.length() == expectedJsonArray.length()); - for (int i = 0; i < jsonArray.length(); ++i) { - JSONObject jsonObject = jsonArray.getJSONObject(i); - JSONObject expectedJsonObject = expectedJsonArray.getJSONObject(i); - assertTrue("jsonObjects should have the same length", - jsonObject.length() == expectedJsonObject.length()); - Iterator keys = jsonObject.keys(); - while (keys.hasNext()) { - String key = keys.next(); - Object value = jsonObject.get(key); - String testStr = "row: "+i+" key: "+key+" val: "+value.toString(); - String actualStr = expectedJsonObject .get(key).toString(); - assertTrue("values should be equal for actual: "+testStr+ - " expected: "+actualStr, - value.equals(expectedJsonArray.getJSONObject(i). - get(key).toString())); - } - } - } - } \ No newline at end of file diff --git a/JunitTestSuite.java b/JunitTestSuite.java index b9abad1..0d2b543 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -6,7 +6,8 @@ import org.junit.runners.Suite; @Suite.SuiteClasses({ CDLTest.class, CookieTest.class, - PropertyTest.class + PropertyTest.class, + XMLTest.class }) public class JunitTestSuite { } \ No newline at end of file diff --git a/Util.java b/Util.java index 89743c0..13407af 100644 --- a/Util.java +++ b/Util.java @@ -2,55 +2,72 @@ package org.json.junit; import static org.junit.Assert.*; +import java.util.*; + +import org.json.*; + public class Util { + + /////////////////////////// UTILITY METHODS ///////////////////////// + /** - * Utility method to check for a target string, then remove it from - * the string to be searched. - * @param jsonStr the string to be searched - * @param expectedStr the target string to search for - * @param assertStr the error message for the assert - * @return new string with target substring removed + * Compares two json arrays for equality + * @param jsonArray created by the code to be tested + * @param expectedJsonArray created specifically for compar */ - public static String checkAndRemoveString( - String jsonStr, String expectedStr, String assertStr) { - int idx = jsonStr.indexOf(expectedStr); - assertTrue(assertStr, idx != -1); - String newStr = jsonStr.substring(0, idx)+ - jsonStr.substring(idx+expectedStr.length()); - return newStr; - } - - /** - * Utility method to strip out selected punctuation chars and confirm - * that jsonStr is now empty - * @param jsonStr the string to be verified - * @param regexStr regex string of the chars to remove - * @param assertStr the error message for the assert - */ - public static void verifyEmptyJsonStr(String jsonStr, String regexStr, - String assertStr) { - jsonStr = jsonStr.replaceAll(regexStr, ""); - assertTrue(assertStr, jsonStr.length() == 0); - } - - /** - * Utility method to check for a set of target strings, - * then remove them from the string to be searched. - * When completed, punctuation marks are stripped out and - * the string to be searched is confirmed as empty - * @param jsonStr the string to be searched - * @param expectedStrArray the target strings to search for - * @param regexStr regex string of the chars to remove - * @param methodStr the method name - */ - public static void checkAndRemoveStrings(String jsonStr, - String[] expectedStr, String regexStr, String methodStr) { - for (int i = 0; i < expectedStr.length; ++i) { - jsonStr = Util.checkAndRemoveString(jsonStr, expectedStr[i], - methodStr+expectedStr+" should be included in string output"); + public static void compareActualVsExpectedJsonArrays(JSONArray jsonArray, + JSONArray expectedJsonArray) { + assertTrue("jsonArray lengths should be equal", + jsonArray.length() == expectedJsonArray.length()); + for (int i = 0; i < jsonArray.length(); ++i) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + JSONObject expectedJsonObject = expectedJsonArray.getJSONObject(i); + assertTrue("jsonObjects should have the same length", + jsonObject.length() == expectedJsonObject.length()); + Iterator keys = jsonObject.keys(); + while (keys.hasNext()) { + // TODO: check for nonstring types + String key = keys.next(); + Object value = jsonObject.get(key); + String testStr = "row: "+i+" key: "+key+" val: "+value.toString(); + String actualStr = expectedJsonObject .get(key).toString(); + assertTrue("values should be equal for actual: "+testStr+ + " expected: "+actualStr, + value.equals(expectedJsonArray.getJSONObject(i). + get(key).toString())); + } + } + } + + public static void compareActualVsExpectedJsonObjects( + JSONObject jsonObject, JSONObject expectedJsonObject) { + assertTrue("jsonObjects should have the same length", + jsonObject.length() == expectedJsonObject.length()); + Iterator keys = jsonObject.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object value = jsonObject.get(key); + Object expectedValue = expectedJsonObject.get(key); + if (value instanceof JSONObject) { + JSONObject childJsonObject = jsonObject.getJSONObject(key); + JSONObject expectedChildJsonObject = + expectedJsonObject.getJSONObject(key); + compareActualVsExpectedJsonObjects( + childJsonObject, expectedChildJsonObject); + } else if (value instanceof JSONArray) { + JSONArray childJsonArray = jsonObject.getJSONArray(key); + JSONArray expectedChildJsonArray = + expectedJsonObject.getJSONArray(key); + compareActualVsExpectedJsonArrays( + childJsonArray, expectedChildJsonArray); + } else { + String testStr = "key: "+key+" val: "+value.toString(); + String actualStr = expectedValue.toString(); + assertTrue("string values should be equal for actual: "+ + testStr+" expected: "+actualStr, + value.equals(expectedValue.toString())); + } } - Util.verifyEmptyJsonStr(jsonStr, regexStr, - methodStr+" jsonStr should be empty"); } } diff --git a/XMLTest.java b/XMLTest.java index e69de29..a6f1bf7 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -0,0 +1,93 @@ +package org.json.junit; + +import java.util.*; + +import static org.junit.Assert.*; + +import org.json.*; +import org.junit.Test; + + +/** + * Tests for JSON-Java XML.java + */ +public class XMLTest { + + @Test(expected=NullPointerException.class) + public void shouldHandleNullXML() { + + String xmlStr = null; + JSONObject jsonObject = XML.toJSONObject(xmlStr); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + @Test + public void shouldHandleEmptyXML() { + + String xmlStr = ""; + JSONObject jsonObject = XML.toJSONObject(xmlStr); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + @Test(expected=NullPointerException.class) + public void shouldHandleNullJSONXML() { + JSONObject jsonObject= null; + String xmlStr = XML.toString(jsonObject); + } + + @Test + public void shouldHandleEmptyJSONXML() { + JSONObject jsonObject= new JSONObject(); + String xmlStr = XML.toString(jsonObject); + } + + @Test + public void shouldHandleSimpleXML() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " Joe Tester\n"+ + " Baker street 5\n"+ + "
\n"+ + "
"; + + String expectedStr = + "{\"addresses\":{\"address\":{\"street\":\"Baker street 5\","+ + "\"name\":\"Joe Tester\"},\"xsi:noNamespaceSchemaLocation\":"+ + "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ + "XMLSchema-instance\"}}"; + + JSONObject expectedJsonObject = new JSONObject(expectedStr); + + JSONObject jsonObject = XML.toJSONObject(xmlStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void shouldHandleToString() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " [CDATA[Joe Tester]]\n"+ + " Baker street 5\n"+ + "
\n"+ + "
"; + + String expectedStr = + "{\"addr&esses\":{\"address\":{\"street\":\"Baker street 5\","+ + "\"name\":\"[CDATA[Joe Tester]]\"},\"xsi:noNamespaceSchemaLocation\":"+ + "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ + "XMLSchema-instance\"}}"; + + JSONObject jsonObject = XML.toJSONObject(xmlStr); + String xmlToStr = XML.toString(jsonObject); + JSONObject finalJsonObject = XML.toJSONObject(xmlToStr); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } +} From 4c6da0e6f9bad5dcdec60df7e3aa176b8edae988 Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 23 Mar 2015 19:23:22 -0500 Subject: [PATCH 039/451] In progress --- XMLTest.java | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/XMLTest.java b/XMLTest.java index a6f1bf7..aca2e40 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -21,6 +21,24 @@ public class XMLTest { assertTrue("jsonObject should be empty", jsonObject.length() == 0); } + @Test + public void shouldHandleCommentsInXML() { + + String xmlStr = + "\n"+ + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " Joe Tester\n"+ + " \n"+ + " Baker street 5\n"+ + "
\n"+ + "
"; + JSONObject jsonObject = XML.toJSONObject(xmlStr); + } + @Test public void shouldHandleEmptyXML() { @@ -69,17 +87,17 @@ public class XMLTest { public void shouldHandleToString() { String xmlStr = "\n"+ - "\n"+ "
\n"+ - " [CDATA[Joe Tester]]\n"+ + " [CDATA[Joe & T > e < s " t ' er]]\n"+ " Baker street 5\n"+ "
\n"+ - "
"; + ""; String expectedStr = - "{\"addr&esses\":{\"address\":{\"street\":\"Baker street 5\","+ - "\"name\":\"[CDATA[Joe Tester]]\"},\"xsi:noNamespaceSchemaLocation\":"+ + "{\"addresses\":{\"address\":{\"street\":\"Baker street 5\","+ + "\"name\":\"[CDATA[Joe & T > e < s \\\" t \\\' er]]\"},\"xsi:noNamespaceSchemaLocation\":"+ "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ "XMLSchema-instance\"}}"; From 2df27fc6e76b71aa2ddbb6174b3f9ae03183a1dc Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 25 Mar 2015 08:27:29 -0500 Subject: [PATCH 040/451] in progress --- XMLTest.java | 64 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/XMLTest.java b/XMLTest.java index aca2e40..87d956e 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -10,6 +10,7 @@ import org.junit.Test; /** * Tests for JSON-Java XML.java + * Note: noSpace() will be tested by JSONMLTest */ public class XMLTest { @@ -21,22 +22,25 @@ public class XMLTest { assertTrue("jsonObject should be empty", jsonObject.length() == 0); } - @Test - public void shouldHandleCommentsInXML() { + @Test(expected=NullPointerException.class) + public void shouldHandleNullJSONXML() { + JSONObject jsonObject= null; + String xmlStr = XML.toString(jsonObject); + } + @Test + public void shouldHandleInvalidCDATA() { String xmlStr = - "\n"+ - "\n"+ - "\n"+ - "
\n"+ - " \n"+ - " Joe Tester\n"+ - " \n"+ - " Baker street 5\n"+ - "
\n"+ - "
"; + "\n"+ + "\n"+ + "
\n"+ + " Joe Tester\n"+ + " ![Baker street 5\n"+ + "
\n"+ + "
"; JSONObject jsonObject = XML.toJSONObject(xmlStr); + assertTrue(jsonObject == null); } @Test @@ -47,12 +51,6 @@ public class XMLTest { assertTrue("jsonObject should be empty", jsonObject.length() == 0); } - @Test(expected=NullPointerException.class) - public void shouldHandleNullJSONXML() { - JSONObject jsonObject= null; - String xmlStr = XML.toString(jsonObject); - } - @Test public void shouldHandleEmptyJSONXML() { JSONObject jsonObject= new JSONObject(); @@ -67,15 +65,15 @@ public class XMLTest { " xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ "
\n"+ " Joe Tester\n"+ - " Baker street 5\n"+ + " [CDATA[Baker street 5]\n"+ "
\n"+ ""; String expectedStr = - "{\"addresses\":{\"address\":{\"street\":\"Baker street 5\","+ - "\"name\":\"Joe Tester\"},\"xsi:noNamespaceSchemaLocation\":"+ - "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ - "XMLSchema-instance\"}}"; + "{\"addresses\":{\"address\":{\"street\":\"[CDATA[Baker street 5]\","+ + "\"name\":\"Joe Tester\"},\"xsi:noNamespaceSchemaLocation\":"+ + "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ + "XMLSchema-instance\"}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); @@ -83,6 +81,24 @@ public class XMLTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + @Test + public void shouldHandleCommentsInXML() { + + String xmlStr = + "\n"+ + "\n"+ + "\n"+ + "
\n"+ + " comment ]]>\n"+ + " Joe Tester\n"+ + " \n"+ + " Baker street 5\n"+ + "
\n"+ + "
"; + JSONObject jsonObject = XML.toJSONObject(xmlStr); + } + @Test public void shouldHandleToString() { String xmlStr = From a18e9f7a259ba0bceba9bb4f8158b0313e58f1b2 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 25 Mar 2015 18:53:52 -0500 Subject: [PATCH 041/451] in progress --- XMLTest.java | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/XMLTest.java b/XMLTest.java index 87d956e..3f57710 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -28,15 +28,30 @@ public class XMLTest { String xmlStr = XML.toString(jsonObject); } - @Test - public void shouldHandleInvalidCDATA() { + @Test(expected=JSONException.class) + public void shouldHandleInvalidBangInTag() { String xmlStr = "\n"+ "\n"+ "
\n"+ " Joe Tester\n"+ - " ![Baker street 5\n"+ + " abc street\n"+ + "
\n"+ + "
"; + JSONObject jsonObject = XML.toJSONObject(xmlStr); + assertTrue(jsonObject == null); + } + + @Test(expected=JSONException.class) + public void shouldHandleInvalidSlashInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " abc street\n"+ "
\n"+ "
"; JSONObject jsonObject = XML.toJSONObject(xmlStr); @@ -66,12 +81,13 @@ public class XMLTest { "
\n"+ " Joe Tester\n"+ " [CDATA[Baker street 5]\n"+ + " \n"+ "
\n"+ ""; String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"[CDATA[Baker street 5]\","+ - "\"name\":\"Joe Tester\"},\"xsi:noNamespaceSchemaLocation\":"+ + "\"name\":\"Joe Tester\",\"NothingHere\":\"\"},\"xsi:noNamespaceSchemaLocation\":"+ "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ "XMLSchema-instance\"}}"; From 89f359e4f80ab4d62627fed635a1c2849a253025 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 26 Mar 2015 22:58:11 -0500 Subject: [PATCH 042/451] coverage XMLTest 81.2% / XMLTokener 82.2% --- Util.java | 74 ++++++++++-------- XMLTest.java | 210 ++++++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 225 insertions(+), 59 deletions(-) diff --git a/Util.java b/Util.java index 13407af..3a1cd09 100644 --- a/Util.java +++ b/Util.java @@ -9,12 +9,11 @@ import org.json.*; public class Util { - /////////////////////////// UTILITY METHODS ///////////////////////// /** * Compares two json arrays for equality * @param jsonArray created by the code to be tested - * @param expectedJsonArray created specifically for compar + * @param expectedJsonArray created specifically for comparing */ public static void compareActualVsExpectedJsonArrays(JSONArray jsonArray, JSONArray expectedJsonArray) { @@ -27,19 +26,17 @@ public class Util { jsonObject.length() == expectedJsonObject.length()); Iterator keys = jsonObject.keys(); while (keys.hasNext()) { - // TODO: check for nonstring types String key = keys.next(); - Object value = jsonObject.get(key); - String testStr = "row: "+i+" key: "+key+" val: "+value.toString(); - String actualStr = expectedJsonObject .get(key).toString(); - assertTrue("values should be equal for actual: "+testStr+ - " expected: "+actualStr, - value.equals(expectedJsonArray.getJSONObject(i). - get(key).toString())); + compareJsonObjectEntries(jsonObject, expectedJsonObject, key); } } } + /** + * Compares two json objects for equality + * @param jsonObject created by the code to be tested + * @param expectedJsonObject created specifically for comparing + */ public static void compareActualVsExpectedJsonObjects( JSONObject jsonObject, JSONObject expectedJsonObject) { assertTrue("jsonObjects should have the same length", @@ -47,27 +44,42 @@ public class Util { Iterator keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); - Object value = jsonObject.get(key); - Object expectedValue = expectedJsonObject.get(key); - if (value instanceof JSONObject) { - JSONObject childJsonObject = jsonObject.getJSONObject(key); - JSONObject expectedChildJsonObject = - expectedJsonObject.getJSONObject(key); - compareActualVsExpectedJsonObjects( - childJsonObject, expectedChildJsonObject); - } else if (value instanceof JSONArray) { - JSONArray childJsonArray = jsonObject.getJSONArray(key); - JSONArray expectedChildJsonArray = - expectedJsonObject.getJSONArray(key); - compareActualVsExpectedJsonArrays( - childJsonArray, expectedChildJsonArray); - } else { - String testStr = "key: "+key+" val: "+value.toString(); - String actualStr = expectedValue.toString(); - assertTrue("string values should be equal for actual: "+ - testStr+" expected: "+actualStr, - value.equals(expectedValue.toString())); - } + compareJsonObjectEntries(jsonObject, expectedJsonObject, key); + } + } + + /** + * Compare two jsonObject entries + * @param jsonObject created by the code to be tested + * @param expectedJsonObject created specifically for comparing + * @param key key to the jsonObject entry to be compared + */ + private static void compareJsonObjectEntries(JSONObject jsonObject, + JSONObject expectedJsonObject, String key) { + Object value = jsonObject.get(key); + Object expectedValue = expectedJsonObject.get(key); + if (value instanceof JSONObject) { + JSONObject childJsonObject = jsonObject.getJSONObject(key); + JSONObject expectedChildJsonObject = + expectedJsonObject.getJSONObject(key); + compareActualVsExpectedJsonObjects( + childJsonObject, expectedChildJsonObject); + } else if (value instanceof JSONArray) { + JSONArray childJsonArray = jsonObject.getJSONArray(key); + JSONArray expectedChildJsonArray = + expectedJsonObject.getJSONArray(key); + compareActualVsExpectedJsonArrays( + childJsonArray, expectedChildJsonArray); + } else if (!(value instanceof String) && !(expectedValue instanceof String)) { + assertTrue("string values should be equal for actual: "+ + value.toString()+" expected: "+expectedValue.toString(), + value.toString().equals(expectedValue.toString())); + } else { + String testStr = "key: "+key+" val: "+value.toString(); + String actualStr = expectedValue.toString(); + assertTrue("string values should be equal for actual: "+ + testStr+" expected: "+actualStr, + value.equals(expectedValue.toString())); } } } diff --git a/XMLTest.java b/XMLTest.java index 3f57710..0c86eeb 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -1,7 +1,5 @@ package org.json.junit; -import java.util.*; - import static org.junit.Assert.*; import org.json.*; @@ -22,25 +20,19 @@ public class XMLTest { assertTrue("jsonObject should be empty", jsonObject.length() == 0); } - @Test(expected=NullPointerException.class) - public void shouldHandleNullJSONXML() { - JSONObject jsonObject= null; - String xmlStr = XML.toString(jsonObject); + @Test + public void shouldHandleEmptyXML() { + + String xmlStr = ""; + JSONObject jsonObject = XML.toJSONObject(xmlStr); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); } - @Test(expected=JSONException.class) - public void shouldHandleInvalidBangInTag() { - String xmlStr = - "\n"+ - "\n"+ - "
\n"+ - " Joe Tester\n"+ - " abc street\n"+ - "
\n"+ - "
"; + @Test + public void shouldHandleNonXML() { + String xmlStr = "{ \"this is\": \"not xml\"}"; JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue(jsonObject == null); + assertTrue("xml string should be empty", jsonObject.length() == 0); } @Test(expected=JSONException.class) @@ -54,22 +46,96 @@ public class XMLTest { " abc street\n"+ " \n"+ ""; - JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue(jsonObject == null); + XML.toJSONObject(xmlStr); } - @Test - public void shouldHandleEmptyXML() { + @Test(expected=JSONException.class) + public void shouldHandleInvalidBangInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + "
\n"+ + "
"; + XML.toJSONObject(xmlStr); + } - String xmlStr = ""; - JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + @Test(expected=JSONException.class) + public void shouldHandleInvalidBangNoCloseInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + ""; + XML.toJSONObject(xmlStr); + } + + @Test(expected=JSONException.class) + public void shouldHandleNoCloseStartTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + ""; + XML.toJSONObject(xmlStr); + } + + @Test(expected=JSONException.class) + public void shouldHandleInvalidCDATABangInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " Joe Tester\n"+ + " \n"+ + "
\n"+ + "
"; + XML.toJSONObject(xmlStr); + } + + @Test(expected=NullPointerException.class) + public void shouldHandleNullJSONXML() { + JSONObject jsonObject= null; + XML.toString(jsonObject); } @Test public void shouldHandleEmptyJSONXML() { JSONObject jsonObject= new JSONObject(); String xmlStr = XML.toString(jsonObject); + assertTrue("xml string should be empty", xmlStr.length() == 0); + } + + @Test + public void shouldHandleNoStartTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " >\n"+ + "
\n"+ + "
"; + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ + "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject jsonObject = XML.toJSONObject(xmlStr); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test @@ -82,17 +148,28 @@ public class XMLTest { " Joe Tester\n"+ " [CDATA[Baker street 5]\n"+ " \n"+ + " true\n"+ + " false\n"+ + " null\n"+ + " 42\n"+ + " -23\n"+ + " -23.45\n"+ + " -23x.45\n"+ + " 1, 2, 3, 4.1, 5.2\n"+ "
\n"+ "
"; String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"[CDATA[Baker street 5]\","+ - "\"name\":\"Joe Tester\",\"NothingHere\":\"\"},\"xsi:noNamespaceSchemaLocation\":"+ + "\"name\":\"Joe Tester\",\"NothingHere\":\"\",TrueValue:true,\n"+ + "\"FalseValue\":false,\"NullValue\":null,\"PositiveValue\":42,\n"+ + "\"NegativeValue\":-23,\"DoubleValue\":-23.45,\"Nan\":-23x.45,\n"+ + "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ + "},\"xsi:noNamespaceSchemaLocation\":"+ "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ "XMLSchema-instance\"}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); - JSONObject jsonObject = XML.toJSONObject(xmlStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @@ -113,6 +190,11 @@ public class XMLTest { "
\n"+ "
"; JSONObject jsonObject = XML.toJSONObject(xmlStr); + String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker "+ + "street 5\",\"name\":\"Joe Tester\",\"content\":\" this is -- "+ + " comment \"}}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test @@ -124,12 +206,15 @@ public class XMLTest { "
\n"+ " [CDATA[Joe & T > e < s " t ' er]]\n"+ " Baker street 5\n"+ + " 1, 2, 3, 4.1, 5.2\n"+ "
\n"+ ""; String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker street 5\","+ - "\"name\":\"[CDATA[Joe & T > e < s \\\" t \\\' er]]\"},\"xsi:noNamespaceSchemaLocation\":"+ + "\"name\":\"[CDATA[Joe & T > e < s \\\" t \\\' er]]\","+ + "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ + "},\"xsi:noNamespaceSchemaLocation\":"+ "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ "XMLSchema-instance\"}}"; @@ -140,4 +225,73 @@ public class XMLTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } + + @Test + public void shouldHandleContentNoArraytoString() { + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ + "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + String finalStr = XML.toString(expectedJsonObject); + String expectedFinalStr = "
>"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr.equals(finalStr)); + } + + @Test + public void shouldHandleContentArraytoString() { + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ + "content\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + String finalStr = XML.toString(expectedJsonObject); + String expectedFinalStr = "
"+ + "1\n2\n3"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr.equals(finalStr)); + } + + @Test + public void shouldHandleArraytoString() { + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ + "\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + String finalStr = XML.toString(expectedJsonObject); + String expectedFinalStr = "
"+ + "123"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr.equals(finalStr)); + } + + @Test + public void shouldHandleNestedArraytoString() { + String xmlStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ + "\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject jsonObject = new JSONObject(xmlStr); + String finalStr = XML.toString(jsonObject); + JSONObject finalJsonObject = XML.toJSONObject(finalStr); + String expectedStr = "
"+ + "12"+ + "3"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + JSONObject expectedJsonObject = XML.toJSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } } From 210bb41ba12ade3a29089a630b7c8ec824aac41c Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Thu, 26 Mar 2015 23:05:07 -0500 Subject: [PATCH 043/451] Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 1cef7e3..8f83480 100644 --- a/README.md +++ b/README.md @@ -26,20 +26,20 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | ------------- | ------------- | ---- | | Total coverage | 20.8% | | | | | | | -| CDLTest.java | 94.8% | Completed | -| CookieTest.java | 97.5% | Completed | +| CDL.java | 94.8% | Completed | +| Cookie.java | 97.5% | Completed | | CookieList.java |0% | | | HTTP.java | 0%| | | HTTPTokener.java |0% | | | JSONArray.java |15.3% | | |JSONException.java | 26.7% | | | JSONML.java | 0%| | -| JSONObject.Null | 13.4% | | | +| JSONObject.Null | 17.6% | | | | JSONStringer.java | 0%| | -| JSONTokener.java |65.4% | | +| JSONTokener.java |68.5% | | | JSONWriter.java | 0% | | -| PropertyTest.java | 94.8% | Completed | -| XMLTest.java | 0% | Just started - stleary | -| XMLTokener.java| 0%| | +| Property.java | 94.8% | Completed | +| XML.java | 81.2% | Completed | +| XMLTokener.java| 82.2%| Completed | From 1ff945de69e981511981bf0646ad770fc66be0a7 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Thu, 26 Mar 2015 23:05:59 -0500 Subject: [PATCH 044/451] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8f83480..8555eb6 100644 --- a/README.md +++ b/README.md @@ -29,11 +29,11 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | CDL.java | 94.8% | Completed | | Cookie.java | 97.5% | Completed | | CookieList.java |0% | | -| HTTP.java | 0%| | -| HTTPTokener.java |0% | | +| HTTP.java | 0%| | +| HTTPTokener.java |0% | | | JSONArray.java |15.3% | | -|JSONException.java | 26.7% | | -| JSONML.java | 0%| | +| JSONException.java | 26.7% | | +| JSONML.java | 0%| In progress| | JSONObject.Null | 17.6% | | | | JSONStringer.java | 0%| | | JSONTokener.java |68.5% | | From bc07b5196b5a90cd0bfdbf62f669683ef5b96790 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 27 Mar 2015 17:52:41 -0500 Subject: [PATCH 045/451] starting jsonml test --- JSONMLTest.java | 297 ++++++++++++++++++++++++++++++++++++++++++++ JunitTestSuite.java | 3 +- 2 files changed, 299 insertions(+), 1 deletion(-) create mode 100644 JSONMLTest.java diff --git a/JSONMLTest.java b/JSONMLTest.java new file mode 100644 index 0000000..ca7c2d1 --- /dev/null +++ b/JSONMLTest.java @@ -0,0 +1,297 @@ +package org.json.junit; + +import static org.junit.Assert.*; + +import org.json.*; +import org.junit.Test; + + +/** + * Tests for JSON-Java JSONML.java + */ +public class JSONMLTest { + + @Test(expected=NullPointerException.class) + public void shouldHandleNullXML() { + + String xmlStr = null; + JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + @Test(expected=JSONException.class) + public void shouldHandleEmptyXML() { + + String xmlStr = ""; + JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + @Test + public void shouldHandleNonXML() { + String xmlStr = "{ \"this is\": \"not xml\"}"; + JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + assertTrue("xml string should be empty", jsonObject.length() == 0); + } + + @Test(expected=JSONException.class) + public void shouldHandleInvalidSlashInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " abc street\n"+ + "
\n"+ + "
"; + JSONML.toJSONObject(xmlStr); + } + + @Test(expected=JSONException.class) + public void shouldHandleInvalidBangInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + "
\n"+ + "
"; + JSONML.toJSONObject(xmlStr); + } + + @Test(expected=JSONException.class) + public void shouldHandleInvalidBangNoCloseInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + ""; + JSONML.toJSONObject(xmlStr); + } + + @Test(expected=JSONException.class) + public void shouldHandleNoCloseStartTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + ""; + JSONML.toJSONObject(xmlStr); + } + + @Test(expected=JSONException.class) + public void shouldHandleInvalidCDATABangInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " Joe Tester\n"+ + " \n"+ + "
\n"+ + "
"; + JSONML.toJSONObject(xmlStr); + } + + @Test(expected=NullPointerException.class) + public void shouldHandleNullJSONXML() { + JSONObject jsonObject= null; + JSONML.toString(jsonObject); + } + + @Test + public void shouldHandleEmptyJSONXML() { + JSONObject jsonObject= new JSONObject(); + String xmlStr = JSONML.toString(jsonObject); + assertTrue("xml string should be empty", xmlStr.length() == 0); + } + + @Test + public void shouldHandleNoStartTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " >\n"+ + "
\n"+ + "
"; + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ + "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void shouldHandleSimpleXML() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " Joe Tester\n"+ + " [CDATA[Baker street 5]\n"+ + " \n"+ + " true\n"+ + " false\n"+ + " null\n"+ + " 42\n"+ + " -23\n"+ + " -23.45\n"+ + " -23x.45\n"+ + " 1, 2, 3, 4.1, 5.2\n"+ + "
\n"+ + "
"; + + String expectedStr = + "{\"addresses\":{\"address\":{\"street\":\"[CDATA[Baker street 5]\","+ + "\"name\":\"Joe Tester\",\"NothingHere\":\"\",TrueValue:true,\n"+ + "\"FalseValue\":false,\"NullValue\":null,\"PositiveValue\":42,\n"+ + "\"NegativeValue\":-23,\"DoubleValue\":-23.45,\"Nan\":-23x.45,\n"+ + "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ + "},\"xsi:noNamespaceSchemaLocation\":"+ + "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ + "XMLSchema-instance\"}}"; + + JSONObject expectedJsonObject = new JSONObject(expectedStr); + JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void shouldHandleCommentsInXML() { + + String xmlStr = + "\n"+ + "\n"+ + "\n"+ + "
\n"+ + " comment ]]>\n"+ + " Joe Tester\n"+ + " \n"+ + " Baker street 5\n"+ + "
\n"+ + "
"; + JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker "+ + "street 5\",\"name\":\"Joe Tester\",\"content\":\" this is -- "+ + " comment \"}}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void shouldHandleToString() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " [CDATA[Joe & T > e < s " t ' er]]\n"+ + " Baker street 5\n"+ + " 1, 2, 3, 4.1, 5.2\n"+ + "
\n"+ + "
"; + + String expectedStr = + "{\"addresses\":{\"address\":{\"street\":\"Baker street 5\","+ + "\"name\":\"[CDATA[Joe & T > e < s \\\" t \\\' er]]\","+ + "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ + "},\"xsi:noNamespaceSchemaLocation\":"+ + "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ + "XMLSchema-instance\"}}"; + + JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + String xmlToStr = JSONML.toString(jsonObject); + JSONObject finalJsonObject = JSONML.toJSONObject(xmlToStr); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } + + @Test + public void shouldHandleContentNoArraytoString() { + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ + "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + String finalStr = JSONML.toString(expectedJsonObject); + String expectedFinalStr = "
>"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr.equals(finalStr)); + } + + @Test + public void shouldHandleContentArraytoString() { + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ + "content\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + String finalStr = JSONML.toString(expectedJsonObject); + String expectedFinalStr = "
"+ + "1\n2\n3"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr.equals(finalStr)); + } + + @Test + public void shouldHandleArraytoString() { + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ + "\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + String finalStr = JSONML.toString(expectedJsonObject); + String expectedFinalStr = "
"+ + "123"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr.equals(finalStr)); + } + + @Test + public void shouldHandleNestedArraytoString() { + String xmlStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ + "\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject jsonObject = new JSONObject(xmlStr); + String finalStr = JSONML.toString(jsonObject); + JSONObject finalJsonObject = JSONML.toJSONObject(finalStr); + String expectedStr = "
"+ + "12"+ + "3"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + JSONObject expectedJsonObject = JSONML.toJSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } + +} diff --git a/JunitTestSuite.java b/JunitTestSuite.java index 0d2b543..8c680a0 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -7,7 +7,8 @@ import org.junit.runners.Suite; CDLTest.class, CookieTest.class, PropertyTest.class, - XMLTest.class + XMLTest.class, + JSONMLTest.class }) public class JunitTestSuite { } \ No newline at end of file From ef7e0c7d08662739cddf9ef9ad977043855f5969 Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 30 Mar 2015 08:14:34 -0500 Subject: [PATCH 046/451] in progress --- JSONMLTest.java | 308 +++++++++++++++++++++++++----------------------- Util.java | 58 ++++----- 2 files changed, 186 insertions(+), 180 deletions(-) diff --git a/JSONMLTest.java b/JSONMLTest.java index ca7c2d1..3271584 100644 --- a/JSONMLTest.java +++ b/JSONMLTest.java @@ -12,30 +12,27 @@ import org.junit.Test; public class JSONMLTest { @Test(expected=NullPointerException.class) - public void shouldHandleNullXML() { + public void nullXMLException() { String xmlStr = null; - JSONObject jsonObject = JSONML.toJSONObject(xmlStr); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + JSONML.toJSONObject(xmlStr); } @Test(expected=JSONException.class) - public void shouldHandleEmptyXML() { + public void emptyXMLException() { String xmlStr = ""; - JSONObject jsonObject = JSONML.toJSONObject(xmlStr); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); - } - - @Test - public void shouldHandleNonXML() { - String xmlStr = "{ \"this is\": \"not xml\"}"; - JSONObject jsonObject = JSONML.toJSONObject(xmlStr); - assertTrue("xml string should be empty", jsonObject.length() == 0); + JSONML.toJSONObject(xmlStr); } @Test(expected=JSONException.class) - public void shouldHandleInvalidSlashInTag() { + public void nonXMLException() { + String xmlStr = "{ \"this is\": \"not xml\"}"; + JSONML.toJSONObject(xmlStr); + } + + @Test(expected=JSONException.class) + public void unvalidSlashInTagException() { String xmlStr = "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ - "
\n"+ - " \n"+ - " >\n"+ - "
\n"+ + "xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ + "
\n"+ + "\n"+ + ">\n"+ + "
\n"+ "
"; String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ - "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ + "\"childNodes\":[{"+ + "\"childNodes\":"+ + "[{\"tagName\":\"name\"},"+ + "{\"tagName\":\"nocontent\"},"+ + "\">\"],"+ + "\"tagName\":\"address\"}],"+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+ + "\"tagName\":\"addresses\"}"; JSONObject jsonObject = JSONML.toJSONObject(xmlStr); JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test - public void shouldHandleSimpleXML() { + public void simpleXML() { String xmlStr = "\n"+ "\n"+ - "
\n"+ - " Joe Tester\n"+ - " [CDATA[Baker street 5]\n"+ - " \n"+ - " true\n"+ - " false\n"+ - " null\n"+ - " 42\n"+ - " -23\n"+ - " -23.45\n"+ - " -23x.45\n"+ - " 1, 2, 3, 4.1, 5.2\n"+ - "
\n"+ + "xsi:noNamespaceSchemaLocation='test.xsd'>\n"+ + "
\n"+ + "Joe Tester\n"+ + "[CDATA[Baker street 5]\n"+ + "\n"+ + "true\n"+ + "false\n"+ + "null\n"+ + "42\n"+ + "-23\n"+ + "-23.45\n"+ + "-23x.45\n"+ + "1, 2, 3, 4.1, 5.2\n"+ + "
\n"+ "
"; String expectedStr = - "{\"addresses\":{\"address\":{\"street\":\"[CDATA[Baker street 5]\","+ - "\"name\":\"Joe Tester\",\"NothingHere\":\"\",TrueValue:true,\n"+ - "\"FalseValue\":false,\"NullValue\":null,\"PositiveValue\":42,\n"+ - "\"NegativeValue\":-23,\"DoubleValue\":-23.45,\"Nan\":-23x.45,\n"+ - "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ - "},\"xsi:noNamespaceSchemaLocation\":"+ - "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ - "XMLSchema-instance\"}}"; - - JSONObject expectedJsonObject = new JSONObject(expectedStr); + "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ + "\"childNodes\":[{"+ + "\"childNodes\":["+ + "{\"childNodes\":[\"Joe Tester\"],"+ + "\"tagName\":\"name\"},"+ + "{\"childNodes\":[\"[CDATA[Baker street 5]\"],"+ + "\"tagName\":\"street\"},"+ + "{\"tagName\":\"NothingHere\"},"+ + "{\"childNodes\":[true],"+ + "\"tagName\":\"TrueValue\"},"+ + "{\"childNodes\":[false],"+ + "\"tagName\":\"FalseValue\"},"+ + "{\"childNodes\":[null],"+ + "\"tagName\":\"NullValue\"},"+ + "{\"childNodes\":[42],"+ + "\"tagName\":\"PositiveValue\"},"+ + "{\"childNodes\":[-23],"+ + "\"tagName\":\"NegativeValue\"},"+ + "{\"childNodes\":[-23.45],"+ + "\"tagName\":\"DoubleValue\"},"+ + "{\"childNodes\":[\"-23x.45\"],"+ + "\"tagName\":\"Nan\"},"+ + "{\"childNodes\":[\"1, 2, 3, 4.1, 5.2\"],"+ + "\"tagName\":\"ArrayOfNum\"}],"+ + "\"tagName\":\"address\"}],"+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+ + "\"tagName\":\"addresses\"}"; JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test - public void shouldHandleCommentsInXML() { + public void commentsInXML() { String xmlStr = - "\n"+ - "\n"+ - "\n"+ - "
\n"+ - " comment ]]>\n"+ - " Joe Tester\n"+ - " \n"+ - " Baker street 5\n"+ - "
\n"+ - "
"; + "\n"+ + "\n"+ + "\n"+ + "
\n"+ + " comment ]]>\n"+ + "Joe Tester\n"+ + "\n"+ + "Baker street 5\n"+ + "
\n"+ + "
"; + String expectedStr = + "{\"childNodes\":["+ + "{\"childNodes\":["+ + "\" this is -- comment \","+ + "{\"childNodes\":[\"Joe Tester\"],"+ + "\"tagName\":\"name\"},"+ + "{\"childNodes\":[\"Baker street 5\"],"+ + "\"tagName\":\"street\"}],"+ + "\"tagName\":\"address\"}],"+ + "\"tagName\":\"addresses\"}"; JSONObject jsonObject = JSONML.toJSONObject(xmlStr); - String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker "+ - "street 5\",\"name\":\"Joe Tester\",\"content\":\" this is -- "+ - " comment \"}}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test - public void shouldHandleToString() { + public void jsonObjectToString() { String xmlStr = "\n"+ ""; String expectedStr = - "{\"addresses\":{\"address\":{\"street\":\"Baker street 5\","+ - "\"name\":\"[CDATA[Joe & T > e < s \\\" t \\\' er]]\","+ - "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ - "},\"xsi:noNamespaceSchemaLocation\":"+ - "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ - "XMLSchema-instance\"}}"; + "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ + "\"childNodes\":["+ + "{\"childNodes\":["+ + "{\"childNodes\":[\"[CDATA[Joe & T > e < s \\\" t ' er]]\"],"+ + "\"tagName\":\"name\"},"+ + "{\"childNodes\":[\"Baker street 5\"],"+ + "\"tagName\":\"street\"},"+ + "{\"childNodes\":[\"1, 2, 3, 4.1, 5.2\"],"+ + "\"tagName\":\"ArrayOfNum\"}],"+ + "\"tagName\":\"address\"}],"+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+ + "\"tagName\":\"addresses\"}"; JSONObject jsonObject = JSONML.toJSONObject(xmlStr); String xmlToStr = JSONML.toString(jsonObject); @@ -226,72 +259,57 @@ public class JSONMLTest { } @Test - public void shouldHandleContentNoArraytoString() { - String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ - "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; - JSONObject expectedJsonObject = new JSONObject(expectedStr); - String finalStr = JSONML.toString(expectedJsonObject); - String expectedFinalStr = "
>"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance
"; - assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr.equals(finalStr)); - } - - @Test - public void shouldHandleContentArraytoString() { - String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ - "content\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; - JSONObject expectedJsonObject = new JSONObject(expectedStr); - String finalStr = JSONML.toString(expectedJsonObject); - String expectedFinalStr = "
"+ - "1\n2\n3"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance
"; - assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr.equals(finalStr)); - } - - @Test - public void shouldHandleArraytoString() { - String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ - "\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; - JSONObject expectedJsonObject = new JSONObject(expectedStr); - String finalStr = JSONML.toString(expectedJsonObject); - String expectedFinalStr = "
"+ - "123"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance
"; - assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr.equals(finalStr)); - } - - @Test - public void shouldHandleNestedArraytoString() { - String xmlStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ - "\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; - JSONObject jsonObject = new JSONObject(xmlStr); - String finalStr = JSONML.toString(jsonObject); - JSONObject finalJsonObject = JSONML.toJSONObject(finalStr); - String expectedStr = "
"+ - "12"+ - "3"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance
"; - JSONObject expectedJsonObject = JSONML.toJSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + public void jsonArrayToString() { + String xmlStr = + ""+ + ""+ + "5"+ + "10"+ + "15"+ + ""+ + "val2"+ + "val3"+ + ""+ + "-6"+ + "true"+ + ""+ + "false"+ + "null"+ + ""+ + "10"+ + "20"+ + "33.33"+ + "5220"+ + ""+ + ""; + String expectedStr = + "[\"tag0\","+ + "[\"tag1\","+ + "[\"tag2\",5],"+ + "[\"tag2\",10],"+ + "[\"tag2\",15]"+ + "],"+ + "[\"tag2\",\"val2\"],"+ + "[\"tag3\",\"val3\"],"+ + "[\"tag4\","+ + "[\"tag5\",-6],"+ + "[\"tag5\",true]"+ + "],"+ + "[\"tag6\",false],"+ + "[\"tag7\",null],"+ + "[\"tag1\","+ + "[\"tag8\",10],"+ + "[\"tag8\",20],"+ + "[\"tag8\",33.33],"+ + "[\"tag8\",5220]"+ + "]"+ + "]"; + JSONArray jsonArray = JSONML.toJSONArray(xmlStr); + String xmlToStr = JSONML.toString(jsonArray); + JSONArray finalJsonArray = JSONML.toJSONArray(xmlToStr); + JSONArray expectedJsonArray= new JSONArray(expectedStr); + Util.compareActualVsExpectedJsonArrays(jsonArray,expectedJsonArray); + Util.compareActualVsExpectedJsonArrays(finalJsonArray,expectedJsonArray); } } diff --git a/Util.java b/Util.java index 3a1cd09..d494d13 100644 --- a/Util.java +++ b/Util.java @@ -20,15 +20,9 @@ public class Util { assertTrue("jsonArray lengths should be equal", jsonArray.length() == expectedJsonArray.length()); for (int i = 0; i < jsonArray.length(); ++i) { - JSONObject jsonObject = jsonArray.getJSONObject(i); - JSONObject expectedJsonObject = expectedJsonArray.getJSONObject(i); - assertTrue("jsonObjects should have the same length", - jsonObject.length() == expectedJsonObject.length()); - Iterator keys = jsonObject.keys(); - while (keys.hasNext()) { - String key = keys.next(); - compareJsonObjectEntries(jsonObject, expectedJsonObject, key); - } + Object value = jsonArray.get(i); + Object expectedValue = expectedJsonArray.get(i); + compareActualVsExpectedObjects(value, expectedValue); } } @@ -44,42 +38,36 @@ public class Util { Iterator keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); - compareJsonObjectEntries(jsonObject, expectedJsonObject, key); + Object value = jsonObject.get(key); + Object expectedValue = expectedJsonObject.get(key); + compareActualVsExpectedObjects(value, expectedValue); } } /** - * Compare two jsonObject entries - * @param jsonObject created by the code to be tested - * @param expectedJsonObject created specifically for comparing + * Compare two objects for equality. Might be JSONArray, JSONObject, + * or something else. + * @param value created by the code to be tested + * @param expectedValue created specifically for comparing * @param key key to the jsonObject entry to be compared */ - private static void compareJsonObjectEntries(JSONObject jsonObject, - JSONObject expectedJsonObject, String key) { - Object value = jsonObject.get(key); - Object expectedValue = expectedJsonObject.get(key); - if (value instanceof JSONObject) { - JSONObject childJsonObject = jsonObject.getJSONObject(key); - JSONObject expectedChildJsonObject = - expectedJsonObject.getJSONObject(key); + private static void compareActualVsExpectedObjects(Object value, + Object expectedValue) { + if (value instanceof JSONObject && expectedValue instanceof JSONObject) { + JSONObject jsonObject = (JSONObject)value; + JSONObject expectedJsonObject = (JSONObject)expectedValue; compareActualVsExpectedJsonObjects( - childJsonObject, expectedChildJsonObject); - } else if (value instanceof JSONArray) { - JSONArray childJsonArray = jsonObject.getJSONArray(key); - JSONArray expectedChildJsonArray = - expectedJsonObject.getJSONArray(key); + jsonObject, expectedJsonObject); + } else if (value instanceof JSONArray && expectedValue instanceof JSONArray) { + JSONArray jsonArray = (JSONArray)value; + JSONArray expectedJsonArray = (JSONArray)expectedValue; compareActualVsExpectedJsonArrays( - childJsonArray, expectedChildJsonArray); - } else if (!(value instanceof String) && !(expectedValue instanceof String)) { - assertTrue("string values should be equal for actual: "+ - value.toString()+" expected: "+expectedValue.toString(), - value.toString().equals(expectedValue.toString())); + jsonArray, expectedJsonArray); } else { - String testStr = "key: "+key+" val: "+value.toString(); - String actualStr = expectedValue.toString(); assertTrue("string values should be equal for actual: "+ - testStr+" expected: "+actualStr, - value.equals(expectedValue.toString())); + value.toString()+" expected: "+expectedValue.toString(), + value.toString().equals(expectedValue.toString())); } } + } From 9a6215c3bef6f47103d1d757a124dad0ddc0e4ce Mon Sep 17 00:00:00 2001 From: stleary Date: Tue, 31 Mar 2015 22:53:52 -0500 Subject: [PATCH 047/451] in progress --- JSONMLTest.java | 122 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 93 insertions(+), 29 deletions(-) diff --git a/JSONMLTest.java b/JSONMLTest.java index 3271584..3629fd4 100644 --- a/JSONMLTest.java +++ b/JSONMLTest.java @@ -15,20 +15,20 @@ public class JSONMLTest { public void nullXMLException() { String xmlStr = null; - JSONML.toJSONObject(xmlStr); + JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) public void emptyXMLException() { String xmlStr = ""; - JSONML.toJSONObject(xmlStr); + JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) public void nonXMLException() { String xmlStr = "{ \"this is\": \"not xml\"}"; - JSONML.toJSONObject(xmlStr); + JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) @@ -42,7 +42,7 @@ public class JSONMLTest { " abc street\n"+ "
\n"+ "
"; - JSONML.toJSONObject(xmlStr); + JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) @@ -56,7 +56,7 @@ public class JSONMLTest { " \n"+ "
\n"+ "
"; - JSONML.toJSONObject(xmlStr); + JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) @@ -70,7 +70,7 @@ public class JSONMLTest { " \n"+ ""; - JSONML.toJSONObject(xmlStr); + JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) @@ -84,7 +84,7 @@ public class JSONMLTest { " \n"+ ""; - JSONML.toJSONObject(xmlStr); + JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) @@ -98,23 +98,23 @@ public class JSONMLTest { " \n"+ " \n"+ ""; - JSONML.toJSONObject(xmlStr); + JSONML.toJSONArray(xmlStr); } @Test(expected=NullPointerException.class) public void nullJSONXMLException() { - JSONObject jsonObject= null; - JSONML.toString(jsonObject); + JSONArray jsonArray= null; + JSONML.toString(jsonArray); } @Test(expected=JSONException.class) public void emptyJSONXMLException() { - JSONObject jsonObject= new JSONObject(); - JSONML.toString(jsonObject); + JSONArray jsonArray = new JSONArray(); + JSONML.toString(jsonArray); } @Test - public void noStartTag() { + public void complexTypeXML() { String xmlStr = "\n"+ "\n"+ ""; String expectedStr = - "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ - "\"childNodes\":[{"+ - "\"childNodes\":"+ - "[{\"tagName\":\"name\"},"+ - "{\"tagName\":\"nocontent\"},"+ - "\">\"],"+ - "\"tagName\":\"address\"}],"+ - "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+ - "\"tagName\":\"addresses\"}"; - JSONObject jsonObject = JSONML.toJSONObject(xmlStr); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + "[\"addresses\","+ + "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ + "[\"address\","+ + "[\"name\"],"+ + "[\"nocontent\"],"+ + "\">\""+ + "]"+ + "]"; + JSONArray jsonArray = JSONML.toJSONArray(xmlStr); + JSONArray expectedJsonArray = new JSONArray(expectedStr); + Util.compareActualVsExpectedJsonArrays(jsonArray,expectedJsonArray); } @Test - public void simpleXML() { + public void basicXMLAsObject() { String xmlStr = "\n"+ "-23\n"+ "-23.45\n"+ "-23x.45\n"+ - "1, 2, 3, 4.1, 5.2\n"+ + "\n"+ + "1\n"+ + "2\n"+ + "3\n"+ + "4.1\n"+ + "5.2\n"+ + "\n"+ "\n"+ ""; @@ -183,8 +189,19 @@ public class JSONMLTest { "\"tagName\":\"DoubleValue\"},"+ "{\"childNodes\":[\"-23x.45\"],"+ "\"tagName\":\"Nan\"},"+ - "{\"childNodes\":[\"1, 2, 3, 4.1, 5.2\"],"+ - "\"tagName\":\"ArrayOfNum\"}],"+ + "{\"childNodes\":["+ + "{\"childNodes\":[1],"+ + "\"tagName\":\"value\"},"+ + "{\"childNodes\":[1],"+ + "\"tagName\":\"value\"},"+ + "{\"childNodes\":[1],"+ + "\"tagName\":\"value\"},"+ + "{\"childNodes\":[1],"+ + "\"tagName\":\"value\"},"+ + "{\"childNodes\":[1],"+ + "\"tagName\":\"value\"},"+ + "]," + "\"tagName\":\"address\"}],"+ "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+ "\"tagName\":\"addresses\"}"; @@ -193,6 +210,53 @@ public class JSONMLTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + public void basicXMLAsArray() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + "Joe Tester\n"+ + "[CDATA[Baker street 5]\n"+ + "\n"+ + "true\n"+ + "false\n"+ + "null\n"+ + "42\n"+ + "-23\n"+ + "-23.45\n"+ + "-23x.45\n"+ + "\n"+ + "1\n"+ + "2\n"+ + "3\n"+ + "4.1\n"+ + "5.2\n"+ + "\n"+ + "
\n"+ + "
"; + + String expectedStr = + "[\"addresses\","+ + "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ + "[\"address\","+ + "[\"name\", \"Joe Tester\"]"+ + "[\"street\", \"[CDATA[Baker street 5]\"]"+ + "[\"NothingHere\"]"+ + "[\"TrueValue\", true]"+ + "[\"FalseValue\", false]"+ + "[\"NullValue\", null]"+ + "[\"PositiveValue\", 42]"+ + "[\"NegativeValue\", -23]"+ + "[\"DoubleValue\", -23.45]"+ + "[\"Nan\", \"-23x.45\"]"+ + "[\"ArrayOfNum\", ]"+ + JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + @Test public void commentsInXML() { From de13c7de86b3dd604246bac4e3c3b53310e28c90 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 1 Apr 2015 01:12:22 -0500 Subject: [PATCH 048/451] coverage 84.9% --- JSONMLTest.java | 266 +++++++++++++++++++++--------------------------- 1 file changed, 117 insertions(+), 149 deletions(-) diff --git a/JSONMLTest.java b/JSONMLTest.java index 3629fd4..04f49d7 100644 --- a/JSONMLTest.java +++ b/JSONMLTest.java @@ -31,6 +31,38 @@ public class JSONMLTest { JSONML.toJSONArray(xmlStr); } + @Test(expected=JSONException.class) + public void emptyTagException() { + String jsonArrayStr = + "[\"addresses\","+ + "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ + "["+ + "[\"name\"],"+ + "[\"nocontent\"],"+ + "\">\""+ + "]"+ + "]"; + JSONArray jsonArray = new JSONArray(jsonArrayStr); + JSONML.toString(jsonArray); + } + + @Test(expected=JSONException.class) + public void spaceInTagException() { + String jsonArrayStr = + "[\"addresses\","+ + "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ + "[\"addr esses\","+ + "[\"name\"],"+ + "[\"nocontent\"],"+ + "\">\""+ + "]"+ + "]"; + JSONArray jsonArray = new JSONArray(jsonArrayStr); + JSONML.toString(jsonArray); + } + @Test(expected=JSONException.class) public void unvalidSlashInTagException() { String xmlStr = @@ -136,7 +168,10 @@ public class JSONMLTest { "]"; JSONArray jsonArray = JSONML.toJSONArray(xmlStr); JSONArray expectedJsonArray = new JSONArray(expectedStr); - Util.compareActualVsExpectedJsonArrays(jsonArray,expectedJsonArray); + String xmlToStr = JSONML.toString(jsonArray); + JSONArray finalJsonArray = JSONML.toJSONArray(xmlToStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } @Test @@ -166,50 +201,56 @@ public class JSONMLTest { "\n"+ ""; - String expectedStr = + String expectedStr = "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ - "\"childNodes\":[{"+ "\"childNodes\":["+ - "{\"childNodes\":[\"Joe Tester\"],"+ - "\"tagName\":\"name\"},"+ - "{\"childNodes\":[\"[CDATA[Baker street 5]\"],"+ - "\"tagName\":\"street\"},"+ - "{\"tagName\":\"NothingHere\"},"+ - "{\"childNodes\":[true],"+ - "\"tagName\":\"TrueValue\"},"+ - "{\"childNodes\":[false],"+ - "\"tagName\":\"FalseValue\"},"+ - "{\"childNodes\":[null],"+ - "\"tagName\":\"NullValue\"},"+ - "{\"childNodes\":[42],"+ - "\"tagName\":\"PositiveValue\"},"+ - "{\"childNodes\":[-23],"+ - "\"tagName\":\"NegativeValue\"},"+ - "{\"childNodes\":[-23.45],"+ - "\"tagName\":\"DoubleValue\"},"+ - "{\"childNodes\":[\"-23x.45\"],"+ - "\"tagName\":\"Nan\"},"+ "{\"childNodes\":["+ - "{\"childNodes\":[1],"+ - "\"tagName\":\"value\"},"+ - "{\"childNodes\":[1],"+ - "\"tagName\":\"value\"},"+ - "{\"childNodes\":[1],"+ - "\"tagName\":\"value\"},"+ - "{\"childNodes\":[1],"+ - "\"tagName\":\"value\"},"+ - "{\"childNodes\":[1],"+ - "\"tagName\":\"value\"},"+ - "]," - - "\"tagName\":\"address\"}],"+ - "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+ - "\"tagName\":\"addresses\"}"; + "{\"childNodes\":[\"Joe Tester\"],"+ + "\"tagName\":\"name\"},"+ + "{\"childNodes\":[\"[CDATA[Baker street 5]\"],"+ + "\"tagName\":\"street\"},"+ + "{\"tagName\":\"NothingHere\"},"+ + "{\"childNodes\":[true],"+ + "\"tagName\":\"TrueValue\"},"+ + "{\"childNodes\":[false],"+ + "\"tagName\":\"FalseValue\"},"+ + "{\"childNodes\":[null],"+ + "\"tagName\":\"NullValue\"},"+ + "{\"childNodes\":[42],"+ + "\"tagName\":\"PositiveValue\"},"+ + "{\"childNodes\":[-23],"+ + "\"tagName\":\"NegativeValue\"},"+ + "{\"childNodes\":[-23.45],"+ + "\"tagName\":\"DoubleValue\"},"+ + "{\"childNodes\":[\"-23x.45\"],"+ + "\"tagName\":\"Nan\"},"+ + "{\"childNodes\":["+ + "{\"childNodes\":[1],"+ + "\"tagName\":\"value\"},"+ + "{\"childNodes\":[2],"+ + "\"tagName\":\"value\"},"+ + "{\"childNodes\":[3],"+ + "\"tagName\":\"value\"},"+ + "{\"childNodes\":[4.1],"+ + "\"tagName\":\"value\"},"+ + "{\"childNodes\":[5.2],"+ + "\"tagName\":\"value\"}"+ + "],"+ + "\"tagName\":\"ArrayOfNum\"}"+ + "],"+ + "\"tagName\":\"address\"}"+ + "],"+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+ + "\"tagName\":\"addresses\"}"; JSONObject jsonObject = JSONML.toJSONObject(xmlStr); JSONObject expectedJsonObject = new JSONObject(expectedStr); + String xmlToStr = JSONML.toString(jsonObject); + JSONObject finalJsonObject = JSONML.toJSONObject(xmlToStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedJsonObject); } + @Test public void basicXMLAsArray() { String xmlStr = "\n"+ @@ -236,25 +277,38 @@ public class JSONMLTest { "\n"+ ""; - String expectedStr = + String expectedStr = "[\"addresses\","+ "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ - "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ "[\"address\","+ - "[\"name\", \"Joe Tester\"]"+ - "[\"street\", \"[CDATA[Baker street 5]\"]"+ - "[\"NothingHere\"]"+ - "[\"TrueValue\", true]"+ - "[\"FalseValue\", false]"+ - "[\"NullValue\", null]"+ - "[\"PositiveValue\", 42]"+ - "[\"NegativeValue\", -23]"+ - "[\"DoubleValue\", -23.45]"+ - "[\"Nan\", \"-23x.45\"]"+ - "[\"ArrayOfNum\", ]"+ - JSONObject jsonObject = JSONML.toJSONObject(xmlStr); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + "[\"name\",\"Joe Tester\"],"+ + "[\"street\",\"[CDATA[Baker street 5]\"],"+ + "[\"NothingHere\"],"+ + "[\"TrueValue\",true],"+ + "[\"FalseValue\",false],"+ + "[\"NullValue\",null],"+ + "[\"PositiveValue\",42],"+ + "[\"NegativeValue\",-23],"+ + "[\"DoubleValue\",-23.45],"+ + "[\"Nan\",\"-23x.45\"],"+ + "[\"ArrayOfNum\","+ + "[\"value\",1],"+ + "[\"value\",2],"+ + "[\"value\",3],"+ + "[\"value\",4.1],"+ + "[\"value\",5.2]"+ + "]"+ + "]"+ + "]"; + JSONArray jsonArray = JSONML.toJSONArray(xmlStr); + JSONArray expectedJsonArray = new JSONArray(expectedStr); + String xmlToStr = JSONML.toString(jsonArray); + JSONArray finalJsonArray = JSONML.toJSONArray(xmlToStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + // TODO: this test fails because JSONML.toString() does not emit values + // for true, false, null, and numbers + // Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } @Test @@ -272,108 +326,22 @@ public class JSONMLTest { "Baker street 5\n"+ "\n"+ ""; - String expectedStr = - "{\"childNodes\":["+ - "{\"childNodes\":["+ - "\" this is -- comment \","+ - "{\"childNodes\":[\"Joe Tester\"],"+ - "\"tagName\":\"name\"},"+ - "{\"childNodes\":[\"Baker street 5\"],"+ - "\"tagName\":\"street\"}],"+ - "\"tagName\":\"address\"}],"+ - "\"tagName\":\"addresses\"}"; - JSONObject jsonObject = JSONML.toJSONObject(xmlStr); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); - } - - @Test - public void jsonObjectToString() { - String xmlStr = - "\n"+ - "\n"+ - "
\n"+ - " [CDATA[Joe & T > e < s " t ' er]]\n"+ - " Baker street 5\n"+ - " 1, 2, 3, 4.1, 5.2\n"+ - "
\n"+ - "
"; - - String expectedStr = - "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ - "\"childNodes\":["+ - "{\"childNodes\":["+ - "{\"childNodes\":[\"[CDATA[Joe & T > e < s \\\" t ' er]]\"],"+ - "\"tagName\":\"name\"},"+ - "{\"childNodes\":[\"Baker street 5\"],"+ - "\"tagName\":\"street\"},"+ - "{\"childNodes\":[\"1, 2, 3, 4.1, 5.2\"],"+ - "\"tagName\":\"ArrayOfNum\"}],"+ - "\"tagName\":\"address\"}],"+ - "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+ - "\"tagName\":\"addresses\"}"; - - JSONObject jsonObject = JSONML.toJSONObject(xmlStr); - String xmlToStr = JSONML.toString(jsonObject); - JSONObject finalJsonObject = JSONML.toJSONObject(xmlToStr); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); - Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); - } - - @Test - public void jsonArrayToString() { - String xmlStr = - ""+ - ""+ - "5"+ - "10"+ - "15"+ - ""+ - "val2"+ - "val3"+ - ""+ - "-6"+ - "true"+ - ""+ - "false"+ - "null"+ - ""+ - "10"+ - "20"+ - "33.33"+ - "5220"+ - ""+ - ""; String expectedStr = - "[\"tag0\","+ - "[\"tag1\","+ - "[\"tag2\",5],"+ - "[\"tag2\",10],"+ - "[\"tag2\",15]"+ - "],"+ - "[\"tag2\",\"val2\"],"+ - "[\"tag3\",\"val3\"],"+ - "[\"tag4\","+ - "[\"tag5\",-6],"+ - "[\"tag5\",true]"+ - "],"+ - "[\"tag6\",false],"+ - "[\"tag7\",null],"+ - "[\"tag1\","+ - "[\"tag8\",10],"+ - "[\"tag8\",20],"+ - "[\"tag8\",33.33],"+ - "[\"tag8\",5220]"+ + "[\"addresses\","+ + "[\"address\","+ + "\" this is -- comment \","+ + "[\"name\",\"Joe Tester\"],"+ + "[\"street\",\"Baker street 5\"]"+ "]"+ "]"; JSONArray jsonArray = JSONML.toJSONArray(xmlStr); + JSONArray expectedJsonArray = new JSONArray(expectedStr); String xmlToStr = JSONML.toString(jsonArray); JSONArray finalJsonArray = JSONML.toJSONArray(xmlToStr); - JSONArray expectedJsonArray= new JSONArray(expectedStr); - Util.compareActualVsExpectedJsonArrays(jsonArray,expectedJsonArray); - Util.compareActualVsExpectedJsonArrays(finalJsonArray,expectedJsonArray); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + // TODO this test fails because JSONML.toString() escapes the + // <> chars in the comment. + // Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } } From 45d7503e249c7cc304583ae99b22245cf06663f8 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Wed, 1 Apr 2015 01:23:04 -0500 Subject: [PATCH 049/451] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8555eb6..8769cc4 100644 --- a/README.md +++ b/README.md @@ -24,22 +24,22 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 20.8% | | | +| Total coverage | 47.1% | | | | | | | | CDL.java | 94.8% | Completed | | Cookie.java | 97.5% | Completed | | CookieList.java |0% | | | HTTP.java | 0%| | | HTTPTokener.java |0% | | -| JSONArray.java |15.3% | | +| JSONArray.java |19.5% | | | JSONException.java | 26.7% | | -| JSONML.java | 0%| In progress| -| JSONObject.Null | 17.6% | | | +| JSONML.java | 84.9%| completed | +| JSONObject.Null | 75.0% | | | | JSONStringer.java | 0%| | | JSONTokener.java |68.5% | | | JSONWriter.java | 0% | | | Property.java | 94.8% | Completed | -| XML.java | 81.2% | Completed | -| XMLTokener.java| 82.2%| Completed | +| XML.java | 85.1% | Completed | +| XMLTokener.java| 82.7%| Completed | From e80ded6ebe6c74fe6bf9ec2ab7c0435edd6d92e8 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 2 Apr 2015 21:31:15 -0500 Subject: [PATCH 050/451] fixed comment test 83.2% coverage --- JSONMLTest.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/JSONMLTest.java b/JSONMLTest.java index 04f49d7..729c68f 100644 --- a/JSONMLTest.java +++ b/JSONMLTest.java @@ -319,7 +319,7 @@ public class JSONMLTest { "\n"+ "\n"+ "
\n"+ - " comment ]]>\n"+ + "\n"+ "Joe Tester\n"+ "\n"+ @@ -329,7 +329,6 @@ public class JSONMLTest { String expectedStr = "[\"addresses\","+ "[\"address\","+ - "\" this is -- comment \","+ "[\"name\",\"Joe Tester\"],"+ "[\"street\",\"Baker street 5\"]"+ "]"+ @@ -339,9 +338,7 @@ public class JSONMLTest { String xmlToStr = JSONML.toString(jsonArray); JSONArray finalJsonArray = JSONML.toJSONArray(xmlToStr); Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); - // TODO this test fails because JSONML.toString() escapes the - // <> chars in the comment. - // Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); + Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } } From 5ee4a3fc12fad158c8782ef4288935b18954ba1a Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 2 Apr 2015 21:44:35 -0500 Subject: [PATCH 051/451] fixed comment test 83.2% coverage --- JSONMLTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/JSONMLTest.java b/JSONMLTest.java index 729c68f..b2a4e06 100644 --- a/JSONMLTest.java +++ b/JSONMLTest.java @@ -5,7 +5,6 @@ import static org.junit.Assert.*; import org.json.*; import org.junit.Test; - /** * Tests for JSON-Java JSONML.java */ From ac8b1b098ada45301813a6ba71346c8f6de4b012 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 3 Apr 2015 11:29:16 -0500 Subject: [PATCH 052/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8769cc4..7e5f594 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | | | | | CDL.java | 94.8% | Completed | | Cookie.java | 97.5% | Completed | -| CookieList.java |0% | | +| CookieList.java |0% | In progress | | HTTP.java | 0%| | | HTTPTokener.java |0% | | | JSONArray.java |19.5% | | From 3406acd0aa2bc6a5e355b5b5da4ce2109b042dcc Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 3 Apr 2015 14:35:59 -0500 Subject: [PATCH 053/451] 97.5% coverage --- CookieTest.java | 268 ++++++++++++++++-------------------------------- 1 file changed, 86 insertions(+), 182 deletions(-) diff --git a/CookieTest.java b/CookieTest.java index d8453e9..d5bc239 100644 --- a/CookieTest.java +++ b/CookieTest.java @@ -10,211 +10,115 @@ import org.junit.Test; /** * Tests for JSON-Java Cookie.java - * Paraphrased from: - * http://www.nczonline.net/blog/2009/05/05/http-cookies-explained/ - * - * A web server specifies a cookie to be stored by sending an HTTP header - * called Set-Cookie. The format of the Set-Cookie header is a string as - * follows (parts in square brackets are optional): - * Set-Cookie: value[; expires=date][; domain=domain][; path=path][; secure] - * Where value is usually, but not always, a key/value pair: name=value - * Separators between the optional segments (e.g. expires=date) consist of a - * semicolon followed by a space. - * - * Although cookies are typically url-encoded, they don't have to be. - * - * expires date example: - * Set-Cookie: name=Nicholas; expires=Sat, 02 May 2009 23:38:25 GMT - * - * domain option example: - * Set-Cookie: name=Nicholas; domain=nczonline.net - * - * Path option example: - * Set-Cookie: name=Nicholas; path=/blog - * - * Secure option example (it is just a flag): - * Set-Cookie: name=Nicholas; secure - * - * Subcookies. There is a hard limit of size (4k) that can't be finessed. - * But many browsers (not Chrome) have a max cookies per domain limit - * (usually 50). To get around this, subcookies are encoded in the initial - * name/value pair as follows: - * name=a=b&c=d&e=f&g=h + * See RFC6265 + * At its most basic, a cookie is a name=value pair. + * A JSON-Java encoded cookie escapes '+', '%', '=', ';' with %hh values. */ public class CookieTest { - String simpleCookieStr = - "PH=deleted"+ - "; expires=Wed, 19-Mar-2014 17:53:53 GMT"+ - ";path=/"+ - "; domain=.yahoo.com"+ - ";secure"+ - ";not=included"; - - String encodedCookieStr = - "PH=contains+some+chars"+ - ";expires=Wed, 19-Mar-2014 17:53:53 GMT"+ - "; path=/"+ - ";domain=.yahoo.com?some+escape+chars"+ - "; secure"+ - "; CRZY=%7B%2233748770511_20150319%22%3A%7B%22expires%22%3A142696041"+ - "3419%2C%22data%22%3A%7B%22nv%22%3A3%2C%22bn%22%3A0%2C%22collapsed%2"+ - "2%3A0%7D%7D%7D"; - @Test(expected=NullPointerException.class) - public void shouldHandleNullCookie() { + public void nullCookieException() { String cookieStr = null; Cookie.toJSONObject(cookieStr); } @Test(expected=JSONException.class) - public void shouldHandleEmptyStringCookie() { + public void malFormedCookieException() { + String cookieStr = "thisCookieHasNoEqualsChar"; + Cookie.toJSONObject(cookieStr); + } + + @Test(expected=JSONException.class) + public void emptyStringCookieException() { + /** + * Cookie throws an exception, but CookieList does not + */ String cookieStr = ""; Cookie.toJSONObject(cookieStr); } @Test - public void shouldHandleNonEncodedCookie() { - JSONObject jsonObject = Cookie.toJSONObject(simpleCookieStr); - Set keySet = jsonObject.keySet(); - assertTrue("Keyset should have exactly 7 keys", keySet.size() == 7); - assertTrue("name should have expected value", - "PH".equals(jsonObject.getString("name"))); - assertTrue("Value should have expected value", - "deleted".equals(jsonObject.getString("value"))); - assertTrue("expires should have expected value", - "Wed, 19-Mar-2014 17:53:53 GMT".equals( - jsonObject.getString("expires"))); - assertTrue("domain should have expected value", - ".yahoo.com".equals( - jsonObject.getString("domain"))); - assertTrue("path should have expected value", - "/".equals( - jsonObject.getString("path"))); - assertTrue("not should have expected value", - "included".equals( - jsonObject.getString("not"))); - Boolean secureBool = jsonObject.getBoolean("secure"); - assertTrue("secure should be found in jsonObject", secureBool != null); - assertTrue("secure should have expected value", - secureBool.equals(true)); + public void simpleCookie() { + String cookieStr = "SID=31d4d96e407aad42"; + String expectedCookieStr = "{\"name\":\"SID\",\"value\":\"31d4d96e407aad42\"}"; + JSONObject jsonObject = Cookie.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test - public void shouldConvertNonEncodedCookieToString() { - int idx; - String expectedStr; - JSONObject jsonObject = Cookie.toJSONObject(simpleCookieStr); - String cookieStr = Cookie.toString(jsonObject); - - // check for unordered expected output - expectedStr = "path=/"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("path should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - expectedStr = "expires=Wed, 19-Mar-2014 17:53:53 GMT"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("expires should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - expectedStr = "domain=.yahoo.com"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("domain should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - expectedStr = "PH=deleted"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("name/value should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - expectedStr = "secure"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("secure should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - // after semicolons, nothing should be left - cookieStr = cookieStr.replaceAll(";", ""); - assertTrue("nothing else should remain in cookie toString()", - cookieStr.length() == 0); + public void multiPartCookie() { + String cookieStr = + "PH=deleted; "+ + " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ + "path=/; "+ + " domain=.yahoo.com;"+ + "secure"; + String expectedCookieStr = + "{\"path\":\"/\","+ + "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ + "\"domain\":\".yahoo.com\","+ + "\"name\":\"PH\","+ + "\"secure\":true,"+ + "\"value\":\"deleted\"}"; + JSONObject jsonObject = Cookie.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } @Test - public void shouldHandleEncodedCookie() { - JSONObject jsonObject = Cookie.toJSONObject(encodedCookieStr); - Set keySet = jsonObject.keySet(); - // Note: the 7th key/value is not used by Cookie.java - assertTrue("Keyset should have exactly 7 keys", keySet.size() == 7); - assertTrue("name should have expected value", - "PH".equals(jsonObject.getString("name"))); - assertTrue("Value should have expected value", - "contains+some+chars".equals(jsonObject.getString("value"))); - assertTrue("expires should have expected value", - "Wed, 19-Mar-2014 17:53:53 GMT".equals( - jsonObject.getString("expires"))); - assertTrue("domain should have expected value", - ".yahoo.com?some escape chars".equals( - jsonObject.getString("domain"))); - assertTrue("path should have expected value", - "/".equals( - jsonObject.getString("path"))); - Boolean secureBool = jsonObject.getBoolean("secure"); - assertTrue("secure should be found in jsonObject", secureBool != null); - assertTrue("secure should have expected value", - secureBool.equals(true)); - String expectedStr = "{\"33748770511_20150319\":{\"expires\":14269604134"+ - "19,\"data\":{\"nv\":3,\"bn\":0,\"collapsed\":0}}}"; - assertTrue("CRZY should have expected value", - expectedStr.equals(jsonObject.getString("CRZY"))); + public void convertCookieToString() { + String cookieStr = + "PH=deleted; "+ + " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ + "path=/; "+ + " domain=.yahoo.com;"+ + "thisWont=beIncluded;"+ + "secure"; + String expectedCookieStr = + "{\"path\":\"/\","+ + "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ + "\"domain\":\".yahoo.com\","+ + "\"name\":\"PH\","+ + "\"secure\":true,"+ + "\"value\":\"deleted\"}"; + /** + * ToString() will omit the non-standard segment, + * but it will still be stored in the JSONObject + */ + String expectedDirectCompareCookieStr = + expectedCookieStr.replaceAll("\\{", "\\{\"thisWont\":\"beIncluded\","); + JSONObject jsonObject = Cookie.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + JSONObject expectedDirectCompareJsonObject = + new JSONObject(expectedDirectCompareCookieStr); + String cookieToStr = Cookie.toString(jsonObject); + JSONObject finalJsonObject = Cookie.toJSONObject(cookieToStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedDirectCompareJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } @Test - public void shouldConvertEncodedCookieToString() { - int idx; - String expectedStr; - JSONObject jsonObject = Cookie.toJSONObject(encodedCookieStr); - String cookieStr = Cookie.toString(jsonObject); - - // check for unordered expected output - expectedStr = "path=/"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("path should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - expectedStr = "expires=Wed, 19-Mar-2014 17:53:53 GMT"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("expires should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - expectedStr = "domain=.yahoo.com?some escape chars"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("domain should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - expectedStr = "PH=contains%2bsome%2bchars"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("name/value should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - expectedStr = "secure"; - idx = cookieStr.indexOf(expectedStr); - assertTrue("secure should be included in string output", idx != -1); - cookieStr = cookieStr.substring(0, idx)+ - cookieStr.substring(idx+expectedStr.length()); - - // after semicolons, nothing should be left - cookieStr = cookieStr.replaceAll(";", ""); - assertTrue("nothing else should remain in cookie toString()", - cookieStr.length() == 0); + public void convertEncodedCookieToString() { + String cookieStr = + "PH=deleted; "+ + " expires=Wed,+19-Mar-2014+17:53:53+GMT;"+ + "path=/%2Bthis/is%26/a/spec%3Bsegment%3D; "+ + " domain=.yahoo.com;"+ + "secure"; + String expectedCookieStr = + "{\"path\":\"/+this/is&/a/spec;segment=\","+ + "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ + "\"domain\":\".yahoo.com\","+ + "\"name\":\"PH\","+ + "\"secure\":true,"+ + "\"value\":\"deleted\"}"; + JSONObject jsonObject = Cookie.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + String cookieToStr = Cookie.toString(jsonObject); + JSONObject finalJsonObject = Cookie.toJSONObject(cookieToStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } } From 519c21c8b06b603b3129928d70ada198fe09df95 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 3 Apr 2015 14:36:18 -0500 Subject: [PATCH 054/451] 96.5% coverage --- CookieListTest.java | 113 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 CookieListTest.java diff --git a/CookieListTest.java b/CookieListTest.java new file mode 100644 index 0000000..c8e4c8a --- /dev/null +++ b/CookieListTest.java @@ -0,0 +1,113 @@ +package org.json.junit; + +import java.util.*; + +import static org.junit.Assert.*; + +import org.json.*; +import org.junit.Test; + + +/** + * Tests for JSON-Java CookieList.java + * The main differences between Cookie and CookieList appears to be that + * CookieList does not treat the initial name/value pair different than + * the other segments, and does not handle "secure". + * Therefore the tests will be similar, but not identical. + */ +public class CookieListTest { + @Test(expected=NullPointerException.class) + public void nullCookieListException() { + String cookieStr = null; + CookieList.toJSONObject(cookieStr); + } + + @Test(expected=JSONException.class) + public void malFormedCookieListException() { + String cookieStr = "thisCookieHasNoEqualsChar"; + CookieList.toJSONObject(cookieStr); + } + + @Test(expected=JSONException.class) + public void emptyStringCookieList() { + /** + * Cookie throws an exception, but CookieList does not + */ + String cookieStr = ""; + String expectedCookieStr = ""; + JSONObject jsonObject = CookieList.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void simpleCookieList() { + String cookieStr = "SID=31d4d96e407aad42"; + String expectedCookieStr = "{\"SID\":\"31d4d96e407aad42\"}"; + JSONObject jsonObject = CookieList.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void multiPartCookieList() { + String cookieStr = + "PH=deleted; "+ + " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ + "path=/; "+ + " domain=.yahoo.com;"; + String expectedCookieStr = + "{\"path\":\"/\","+ + "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ + "\"domain\":\".yahoo.com\","+ + "\"name\":\"PH\","+ + "\"value\":\"deleted\"}"; + JSONObject jsonObject = CookieList.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void convertCookieListToString() { + String cookieStr = + "PH=deleted; "+ + " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ + "path=/; "+ + " domain=.yahoo.com;"+ + "thisWont=beIncluded;"; + String expectedCookieStr = + "{\"path\":\"/\","+ + "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ + "\"domain\":\".yahoo.com\","+ + "\"thisWont\":\"beIncluded\","+ + "\"PH\":\"deleted\"}"; + JSONObject jsonObject = CookieList.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + String cookieToStr = CookieList.toString(jsonObject); + JSONObject finalJsonObject = CookieList.toJSONObject(cookieToStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } + + @Test + public void convertEncodedCookieListToString() { + String cookieStr = + "PH=deleted; "+ + " expires=Wed,+19-Mar-2014+17:53:53+GMT;"+ + "path=/%2Bthis/is%26/a/spec%3Bsegment%3D; "+ + " domain=.yahoo.com;"; + String expectedCookieStr = + "{\"path\":\"/+this/is&/a/spec;segment=\","+ + "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ + "\"domain\":\".yahoo.com\","+ + "\"PH\":\"deleted\"}"; + JSONObject jsonObject = CookieList.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + String cookieToStr = CookieList.toString(jsonObject); + JSONObject finalJsonObject = CookieList.toJSONObject(cookieToStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } + + +} From 970e7a45a9bdb409d77753e77103a3597ce7cf25 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 3 Apr 2015 14:36:40 -0500 Subject: [PATCH 055/451] added cookielisttest --- JunitTestSuite.java | 1 + 1 file changed, 1 insertion(+) diff --git a/JunitTestSuite.java b/JunitTestSuite.java index 8c680a0..e76a7c3 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -6,6 +6,7 @@ import org.junit.runners.Suite; @Suite.SuiteClasses({ CDLTest.class, CookieTest.class, + CookieListTest.class, PropertyTest.class, XMLTest.class, JSONMLTest.class From 83ac581f3d9bee43adb2e8accd3d43452e41491e Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 3 Apr 2015 14:46:45 -0500 Subject: [PATCH 056/451] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7e5f594..00bbaad 100644 --- a/README.md +++ b/README.md @@ -24,19 +24,19 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 47.1% | | | +| Total coverage | 48.4% | | | | | | | | CDL.java | 94.8% | Completed | | Cookie.java | 97.5% | Completed | -| CookieList.java |0% | In progress | -| HTTP.java | 0%| | -| HTTPTokener.java |0% | | +| CookieList.java |96.5% | Completed | +| HTTP.java | 0%| In progress | +| HTTPTokener.java |0% |In progress | | JSONArray.java |19.5% | | | JSONException.java | 26.7% | | -| JSONML.java | 84.9%| completed | +| JSONML.java | 83.2%| completed | | JSONObject.Null | 75.0% | | | | JSONStringer.java | 0%| | -| JSONTokener.java |68.5% | | +| JSONTokener.java |70.3% | | | JSONWriter.java | 0% | | | Property.java | 94.8% | Completed | | XML.java | 85.1% | Completed | From f7b51414b8c013e12f08f53e45d0dcad3c369a35 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 3 Apr 2015 14:46:51 -0500 Subject: [PATCH 057/451] 96.5% coverage --- CookieListTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CookieListTest.java b/CookieListTest.java index c8e4c8a..d8b4a5b 100644 --- a/CookieListTest.java +++ b/CookieListTest.java @@ -60,8 +60,7 @@ public class CookieListTest { "{\"path\":\"/\","+ "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ "\"domain\":\".yahoo.com\","+ - "\"name\":\"PH\","+ - "\"value\":\"deleted\"}"; + "\"PH\":\"deleted\"}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); From 400bbd7fbf17c66c572ab175d9c04eab28d73ddc Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 3 Apr 2015 19:12:15 -0500 Subject: [PATCH 058/451] 98.7% coverage --- HTTPTest.java | 149 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 HTTPTest.java diff --git a/HTTPTest.java b/HTTPTest.java new file mode 100644 index 0000000..04b9daf --- /dev/null +++ b/HTTPTest.java @@ -0,0 +1,149 @@ +package org.json.junit; + +import java.util.*; + +import static org.junit.Assert.*; + +import org.json.*; +import org.junit.Test; + + +/** + * Tests for JSON-Java HTTP.java + * See RFC7230 + */ +public class HTTPTest { + + @Test(expected=NullPointerException.class) + public void nullHTTPException() { + String httpStr = null; + HTTP.toJSONObject(httpStr); + } + + @Test(expected=JSONException.class) + public void notEnoughHTTPException() { + String httpStr = "{}"; + JSONObject jsonObject = new JSONObject(httpStr); + HTTP.toString(jsonObject); + } + + @Test + public void emptyStringHTTPException() { + String httpStr = ""; + String expectedHTTPStr = "{\"Request-URI\":\"\",\"Method\":\"\",\"HTTP-Version\":\"\"}"; + JSONObject jsonObject = HTTP.toJSONObject(httpStr); + JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void simpleHTTPRequest() { + String httpStr = "GET /hello.txt HTTP/1.1"; + String expectedHTTPStr = + "{\"Request-URI\":\"/hello.txt\",\"Method\":\"GET\",\"HTTP-Version\":\"HTTP/1.1\"}"; + JSONObject jsonObject = HTTP.toJSONObject(httpStr); + JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void simpleHTTPResponse() { + String httpStr = "HTTP/1.1 200 OK"; + String expectedHTTPStr = + "{\"HTTP-Version\":\"HTTP/1.1\",\"Status-Code\":\"200\",\"Reason-Phrase\":\"OK\"}"; + JSONObject jsonObject = HTTP.toJSONObject(httpStr); + JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void extendedHTTPRequest() { + String httpStr = + "POST /enlighten/calais.asmx HTTP/1.1\n"+ + "Host: api.opencalais.com\n"+ + "Content-Type: text/xml; charset=utf-8\n"+ + "Content-Length: 100\n"+ + "SOAPAction: \"http://clearforest.com/Enlighten\""; + String expectedHTTPStr = + "{"+ + "\"Request-URI\":\"/enlighten/calais.asmx\","+ + "\"Host\":\"api.opencalais.com\","+ + "\"Method\":\"POST\","+ + "\"HTTP-Version\":\"HTTP/1.1\","+ + "\"Content-Length\":\"100\","+ + "\"Content-Type\":\"text/xml; charset=utf-8\"}"; + JSONObject jsonObject = HTTP.toJSONObject(httpStr); + JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); + // not too easy for JSONObject to parse a string with embedded quotes + expectedJsonObject.put("SOAPAction","\"http://clearforest.com/Enlighten\""); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void extendedHTTPResponse() { + String httpStr = + "HTTP/1.1 200 OK\n"+ + "Content-Type: text/xml; charset=utf-8\n"+ + "Content-Length: 100\n"; + String expectedHTTPStr = + "{\"HTTP-Version\":\"HTTP/1.1\","+ + "\"Status-Code\":\"200\","+ + "\"Content-Length\":\"100\","+ + "\"Reason-Phrase\":\"OK\","+ + "\"Content-Type\":\"text/xml; charset=utf-8\"}"; + JSONObject jsonObject = HTTP.toJSONObject(httpStr); + JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void convertHTTPRequestToString() { + String httpStr = + "POST /enlighten/calais.asmx HTTP/1.1\n"+ + "Host: api.opencalais.com\n"+ + "Content-Type: text/xml; charset=utf-8\n"+ + "Content-Length: 100"; + String expectedHTTPStr = + "{"+ + "\"Request-URI\":\"/enlighten/calais.asmx\","+ + "\"Host\":\"api.opencalais.com\","+ + "\"Method\":\"POST\","+ + "\"HTTP-Version\":\"HTTP/1.1\","+ + "\"Content-Length\":\"100\","+ + "\"Content-Type\":\"text/xml; charset=utf-8\"}"; + JSONObject jsonObject = HTTP.toJSONObject(httpStr); + JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); + String httpToStr = HTTP.toString(jsonObject); + // JSONObject objects to crlfs and any trailing chars + // httpToStr = httpToStr.replaceAll("(\r\n\r\n)", ""); + httpToStr = httpToStr.replaceAll("("+HTTP.CRLF+HTTP.CRLF+")", ""); + httpToStr = httpToStr.replaceAll(HTTP.CRLF, "\n"); + JSONObject finalJsonObject = HTTP.toJSONObject(httpToStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } + + @Test + public void convertHTTPResponseToString() { + String httpStr = + "HTTP/1.1 200 OK\n"+ + "Content-Type: text/xml; charset=utf-8\n"+ + "Content-Length: 100\n"; + String expectedHTTPStr = + "{\"HTTP-Version\":\"HTTP/1.1\","+ + "\"Status-Code\":\"200\","+ + "\"Content-Length\":\"100\","+ + "\"Reason-Phrase\":\"OK\","+ + "\"Content-Type\":\"text/xml; charset=utf-8\"}"; + JSONObject jsonObject = HTTP.toJSONObject(httpStr); + JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); + String httpToStr = HTTP.toString(jsonObject); + // JSONObject objects to crlfs and any trailing chars + // httpToStr = httpToStr.replaceAll("(\r\n\r\n)", ""); + httpToStr = httpToStr.replaceAll("("+HTTP.CRLF+HTTP.CRLF+")", ""); + httpToStr = httpToStr.replaceAll(HTTP.CRLF, "\n"); + JSONObject finalJsonObject = HTTP.toJSONObject(httpToStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } +} From 76cb83643d5db55311ebc8fe7ab29c318f0f2954 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 3 Apr 2015 19:12:41 -0500 Subject: [PATCH 059/451] add http test --- JunitTestSuite.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/JunitTestSuite.java b/JunitTestSuite.java index e76a7c3..b965fb8 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -9,7 +9,8 @@ import org.junit.runners.Suite; CookieListTest.class, PropertyTest.class, XMLTest.class, - JSONMLTest.class + JSONMLTest.class, + HTTPTest.class }) public class JunitTestSuite { } \ No newline at end of file From 702a91827114bab63894079a0bc294bf41d2e8c4 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 3 Apr 2015 19:16:45 -0500 Subject: [PATCH 060/451] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 00bbaad..4d0a6c7 100644 --- a/README.md +++ b/README.md @@ -24,18 +24,18 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 48.4% | | | +| Total coverage | 52.6% | | | | | | | | CDL.java | 94.8% | Completed | | Cookie.java | 97.5% | Completed | | CookieList.java |96.5% | Completed | -| HTTP.java | 0%| In progress | -| HTTPTokener.java |0% |In progress | +| HTTP.java | 98.7%| Completed | +| HTTPTokener.java |93.2% |Completed | | JSONArray.java |19.5% | | | JSONException.java | 26.7% | | | JSONML.java | 83.2%| completed | | JSONObject.Null | 75.0% | | | -| JSONStringer.java | 0%| | +| JSONStringer.java | 0%| In progress | | JSONTokener.java |70.3% | | | JSONWriter.java | 0% | | | Property.java | 94.8% | Completed | From 03d1f0af727993f85a3c65eb572e8776456564e3 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 3 Apr 2015 19:18:13 -0500 Subject: [PATCH 061/451] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 4d0a6c7..41996e9 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | JSONArray.java |19.5% | | | JSONException.java | 26.7% | | | JSONML.java | 83.2%| completed | +| JSONObject | 19.0% | | | | JSONObject.Null | 75.0% | | | | JSONStringer.java | 0%| In progress | | JSONTokener.java |70.3% | | From 2db11cd4db8139e9a1ee2fd766ab0609377a6ef7 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 4 Apr 2015 14:00:57 -0500 Subject: [PATCH 062/451] add JSONStringerTest --- JunitTestSuite.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/JunitTestSuite.java b/JunitTestSuite.java index b965fb8..2519e81 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -10,7 +10,8 @@ import org.junit.runners.Suite; PropertyTest.class, XMLTest.class, JSONMLTest.class, - HTTPTest.class + HTTPTest.class, + JSONStringerTest.class }) public class JunitTestSuite { } \ No newline at end of file From b2e0a77ae06573f53d383743f7c39a6718362fb8 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 4 Apr 2015 14:01:29 -0500 Subject: [PATCH 063/451] 98.7% coverage --- HTTPTest.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/HTTPTest.java b/HTTPTest.java index 04b9daf..52e166b 100644 --- a/HTTPTest.java +++ b/HTTPTest.java @@ -1,9 +1,5 @@ package org.json.junit; -import java.util.*; - -import static org.junit.Assert.*; - import org.json.*; import org.junit.Test; From 8168e6f52a52843cf7b4547b090dc21dc9abefd8 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 4 Apr 2015 14:01:52 -0500 Subject: [PATCH 064/451] 93.8% coverage --- JSONStringerTest.java | 224 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 224 insertions(+) create mode 100644 JSONStringerTest.java diff --git a/JSONStringerTest.java b/JSONStringerTest.java new file mode 100644 index 0000000..d76bfb1 --- /dev/null +++ b/JSONStringerTest.java @@ -0,0 +1,224 @@ +package org.json.junit; + +import org.json.*; +import org.junit.Test; + + +/** + * Tests for JSON-Java JSONStringer.java + */ +public class JSONStringerTest { + + @Test(expected=JSONException.class) + public void nullKeyException() { + JSONStringer jsonStringer = new JSONStringer(); + jsonStringer.object(); + jsonStringer.key(null); + } + + @Test(expected=JSONException.class) + public void outOfSequenceException() { + JSONStringer jsonStringer = new JSONStringer(); + jsonStringer.key("hi"); + } + + @Test(expected=JSONException.class) + public void missplacedArrayException() { + JSONStringer jsonStringer = new JSONStringer(); + jsonStringer.object().endObject(); + jsonStringer.array(); + } + + @Test(expected=JSONException.class) + public void missplacedEndArrayException() { + JSONStringer jsonStringer = new JSONStringer(); + jsonStringer.object(); + jsonStringer.endArray(); + } + + @Test(expected=JSONException.class) + public void missplacedEndObjectException() { + JSONStringer jsonStringer = new JSONStringer(); + jsonStringer.array(); + jsonStringer.endObject(); + } + + @Test(expected=JSONException.class) + public void missplacedObjectException() { + JSONStringer jsonStringer = new JSONStringer(); + jsonStringer.object().endObject(); + jsonStringer.object(); + } + + @Test(expected=JSONException.class) + public void exceedNestDepthException() { + new JSONStringer().object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(); + } + + @Test + public void simpleObjectString() { + String expectedStr = + "{"+ + "\"trueValue\":true,"+ + "\"falseValue\":false,"+ + "\"nullValue\":null,"+ + "\"stringValue\":\"hello world!\","+ + "\"complexStringValue\":\"h\be\tllo w\u1234orld!\","+ + "\"intValue\":42,"+ + "\"doubleValue\":-23.45e67"+ + "}"; + JSONStringer jsonStringer = new JSONStringer(); + jsonStringer.object(); + jsonStringer.key("trueValue").value(true); + jsonStringer.key("falseValue").value(false); + jsonStringer.key("nullValue").value(null); + jsonStringer.key("stringValue").value("hello world!"); + jsonStringer.key("complexStringValue").value("h\be\tllo w\u1234orld!"); + jsonStringer.key("intValue").value(42); + jsonStringer.key("doubleValue").value(-23.45e67); + jsonStringer.endObject(); + String str = jsonStringer.toString(); + JSONObject jsonObject = new JSONObject(str); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void simpleArrayString() { + String expectedStr = + "["+ + "true,"+ + "false,"+ + "null,"+ + "\"hello world!\","+ + "42,"+ + "-23.45e67"+ + "]"; + JSONStringer jsonStringer = new JSONStringer(); + jsonStringer.array(); + jsonStringer.value(true); + jsonStringer.value(false); + jsonStringer.value(null); + jsonStringer.value("hello world!"); + jsonStringer.value(42); + jsonStringer.value(-23.45e67); + jsonStringer.endArray(); + String str = jsonStringer.toString(); + JSONArray jsonArray = new JSONArray(str); + JSONArray expectedJsonArray = new JSONArray(expectedStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + } + + @Test + public void complexObjectString() { + String expectedStr = + "{"+ + "\"trueValue\":true,"+ + "\"falseValue\":false,"+ + "\"nullValue\":null,"+ + "\"stringValue\":\"hello world!\","+ + "\"object2\":{"+ + "\"k1\":\"v1\","+ + "\"k2\":\"v2\","+ + "\"k3\":\"v3\","+ + "\"array1\":["+ + "1,"+ + "2,"+ + "{"+ + "\"k4\":\"v4\","+ + "\"k5\":\"v5\","+ + "\"k6\":\"v6\","+ + "\"array2\":["+ + "5,"+ + "6,"+ + "7,"+ + "8"+ + "]"+ + "},"+ + "3,"+ + "4"+ + "]"+ + "},"+ + "\"complexStringValue\":\"h\be\tllo w\u1234orld!\","+ + "\"intValue\":42,"+ + "\"doubleValue\":-23.45e67"+ + "}"; + JSONStringer jsonStringer = new JSONStringer(); + jsonStringer.object(); + jsonStringer.key("trueValue").value(true); + jsonStringer.key("falseValue").value(false); + jsonStringer.key("nullValue").value(null); + jsonStringer.key("stringValue").value("hello world!"); + jsonStringer.key("object2").object(); + jsonStringer.key("k1").value("v1"); + jsonStringer.key("k2").value("v2"); + jsonStringer.key("k3").value("v3"); + jsonStringer.key("array1").array(); + jsonStringer.value(1); + jsonStringer.value(2); + jsonStringer.object(); + jsonStringer.key("k4").value("v4"); + jsonStringer.key("k5").value("v5"); + jsonStringer.key("k6").value("v6"); + jsonStringer.key("array2").array(); + jsonStringer.value(5); + jsonStringer.value(6); + jsonStringer.value(7); + jsonStringer.value(8); + jsonStringer.endArray(); + jsonStringer.endObject(); + jsonStringer.value(3); + jsonStringer.value(4); + jsonStringer.endArray(); + jsonStringer.endObject(); + jsonStringer.key("complexStringValue").value("h\be\tllo w\u1234orld!"); + jsonStringer.key("intValue").value(42); + jsonStringer.key("doubleValue").value(-23.45e67); + jsonStringer.endObject(); + String str = jsonStringer.toString(); + JSONObject jsonObject = new JSONObject(str); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + +} From 2219b5919b86906c80e96d9b06099c8ccdb717ea Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 4 Apr 2015 14:05:06 -0500 Subject: [PATCH 065/451] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 41996e9..da0c4ee 100644 --- a/README.md +++ b/README.md @@ -24,21 +24,21 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 52.6% | | | +| Total coverage | 58.4% | | | | | | | | CDL.java | 94.8% | Completed | | Cookie.java | 97.5% | Completed | | CookieList.java |96.5% | Completed | | HTTP.java | 98.7%| Completed | | HTTPTokener.java |93.2% |Completed | -| JSONArray.java |19.5% | | +| JSONArray.java |18.3% | | | JSONException.java | 26.7% | | | JSONML.java | 83.2%| completed | -| JSONObject | 19.0% | | | +| JSONObject | 24.9% | | in progress | | JSONObject.Null | 75.0% | | | -| JSONStringer.java | 0%| In progress | -| JSONTokener.java |70.3% | | -| JSONWriter.java | 0% | | +| JSONStringer.java | 93.8%| Completed | +| JSONTokener.java | 72.1% | | +| JSONWriter.java | 88.9% | Completed | | Property.java | 94.8% | Completed | | XML.java | 85.1% | Completed | | XMLTokener.java| 82.7%| Completed | From 22d5fd3aed9cc452d305bed5cd4154025b2195e3 Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 6 Apr 2015 19:01:54 -0500 Subject: [PATCH 066/451] in progress --- JSONObjectTest.java | 161 +++++++++++++++++++++++++++++++++++++ JunitTestSuite.java | 3 +- MyBean.java | 37 +++++++++ StringsResourceBundle.java | 15 ++++ 4 files changed, 215 insertions(+), 1 deletion(-) create mode 100644 JSONObjectTest.java create mode 100644 MyBean.java create mode 100644 StringsResourceBundle.java diff --git a/JSONObjectTest.java b/JSONObjectTest.java new file mode 100644 index 0000000..301f149 --- /dev/null +++ b/JSONObjectTest.java @@ -0,0 +1,161 @@ +package org.json.junit; + +import java.util.*; + +import org.json.*; +import org.junit.*; + + +public class JSONObjectTest { + + + @Test + public void jsonObjectByNames() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"nullKey\":null,"+ + "\"stringKey\":\"hello world!\","+ + "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"intKey\":42,"+ + "\"doubleKey\":-23.45e67"+ + "}"; + String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"}; + String expectedStr = + "{"+ + "\"falseKey\":false,"+ + "\"nullKey\":null,"+ + "\"stringKey\":\"hello world!\","+ + "\"doubleKey\":-23.45e67"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + JSONObject copyJsonObject = new JSONObject(jsonObject, keys); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(copyJsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectByMap() { + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"intKey\":42,"+ + "\"doubleKey\":-23.45e67"+ + "}"; + Map jsonMap = new HashMap(); + jsonMap.put("trueKey", new Boolean(true)); + jsonMap.put("falseKey", new Boolean(false)); + jsonMap.put("stringKey", "hello world!"); + jsonMap.put("complexStringKey", "h\be\tllo w\u1234orld!"); + jsonMap.put("intKey", new Long(42)); + jsonMap.put("doubleKey", new Double(-23.45e67)); + + JSONObject jsonObject = new JSONObject(jsonMap); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectByBean() { + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"intKey\":42,"+ + "\"doubleKey\":-23.45e7"+ + "}"; + MyBean myBean = new MyBean(); + JSONObject jsonObject = new JSONObject(myBean); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectByBeanAndNames() { + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"doubleKey\":-23.45e7"+ + "}"; + String[] keys = {"trueKey", "complexStringKey", "doubleKey"}; + MyBean myBean = new MyBean(); + JSONObject jsonObject = new JSONObject(myBean, keys); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectByResourceBundle() { + String expectedStr = + "{"+ + "\"greetings\": {"+ + "\"hello\":\"Hello, \","+ + "\"world\":\"World!\""+ + "},"+ + "\"farewells\": {"+ + "\"later\":\"Later, \","+ + "\"gator\":\"Alligator!\""+ + "}"+ + "}"; + JSONObject jsonObject = new + JSONObject("org.json.junit.StringsResourceBundle", + Locale.getDefault()); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectAccumulate() { + String expectedStr = + "{"+ + "\"myArray\": ["+ + "true,"+ + "false,"+ + "\"hello world!\","+ + "\"h\be\tllo w\u1234orld!\","+ + "42,"+ + "-23.45e7"+ + "]"+ + "}"; + JSONObject jsonObject = new JSONObject(); + jsonObject.accumulate("myArray", true); + jsonObject.accumulate("myArray", false); + jsonObject.accumulate("myArray", "hello world!"); + jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); + jsonObject.accumulate("myArray", 42); + jsonObject.accumulate("myArray", -23.45e7); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectAppend() { + String expectedStr = + "{"+ + "\"myArray\": ["+ + "true,"+ + "false,"+ + "\"hello world!\","+ + "\"h\be\tllo w\u1234orld!\","+ + "42,"+ + "-23.45e7"+ + "]"+ + "}"; + JSONObject jsonObject = new JSONObject(); + jsonObject.append("myArray", true); + jsonObject.append("myArray", false); + jsonObject.append("myArray", "hello world!"); + jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); + jsonObject.append("myArray", 42); + jsonObject.append("myArray", -23.45e7); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } +} diff --git a/JunitTestSuite.java b/JunitTestSuite.java index 2519e81..63bde2f 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -11,7 +11,8 @@ import org.junit.runners.Suite; XMLTest.class, JSONMLTest.class, HTTPTest.class, - JSONStringerTest.class + JSONStringerTest.class, + JSONObjectTest.class }) public class JunitTestSuite { } \ No newline at end of file diff --git a/MyBean.java b/MyBean.java new file mode 100644 index 0000000..6477fde --- /dev/null +++ b/MyBean.java @@ -0,0 +1,37 @@ +package org.json.junit; + +public class MyBean { + public int intKey; + public double doubleKey; + public String stringKey; + public String complexStringKey; + public boolean trueKey; + public boolean falseKey; + + public MyBean() { + intKey = 42; + doubleKey = -23.45e7; + stringKey = "hello world!"; + complexStringKey = "h\be\tllo w\u1234orld!"; + trueKey = true; + falseKey = false; + } + public int getIntKey() { + return intKey; + } + public double getDoubleKey() { + return doubleKey; + } + public String getStringKey() { + return stringKey; + } + public String getComplexStringKey() { + return complexStringKey; + } + public boolean isTrueKey() { + return trueKey; + } + public boolean isFalseKey() { + return falseKey; + } +} diff --git a/StringsResourceBundle.java b/StringsResourceBundle.java new file mode 100644 index 0000000..b1b9df4 --- /dev/null +++ b/StringsResourceBundle.java @@ -0,0 +1,15 @@ +package org.json.junit; + +import java.util.*; + +public class StringsResourceBundle extends ListResourceBundle { + public Object[][] getContents() { + return contents; + } + static final Object[][] contents = { + {"greetings.hello", "Hello, "}, + {"greetings.world", "World!"}, + {"farewells.later", "Later, "}, + {"farewells.gator", "Alligator!"} + }; +} \ No newline at end of file From a9bce1d6b28a18ddbba35c660933914cde310f7f Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 8 Apr 2015 22:23:39 -0500 Subject: [PATCH 067/451] in progress --- JSONObjectTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 301f149..3fb20fc 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -1,5 +1,7 @@ package org.json.junit; +import static org.junit.Assert.*; + import java.util.*; import org.json.*; @@ -158,4 +160,17 @@ public class JSONObjectTest { JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + + @Test + public void jsonObjectValuesToString() { + String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", null }; + Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, + new Double(1/0) }; + for (int i = 0; i < expectedStrs.length; ++i) { + String actualStr = JSONObject.doubleToString(doubles[i]); + assertTrue("double value expected ["+expectedStrs[i]+ + "] found ["+actualStr+ "]", + expectedStrs[i].equals(actualStr)); + } + } } From bef37079dcf3842185977c21f492da6cd54ce957 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 9 Apr 2015 18:02:45 -0500 Subject: [PATCH 068/451] in progress --- JSONObjectTest.java | 70 +++++++++++++++++++++++++++++++++++++++++---- Util.java | 13 +++++++++ 2 files changed, 78 insertions(+), 5 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 3fb20fc..aa434ea 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -162,15 +162,75 @@ public class JSONObjectTest { } @Test - public void jsonObjectValuesToString() { - String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", null }; - Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, - new Double(1/0) }; + public void jsonObjectDoubleToString() { + String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68" }; + Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67 }; for (int i = 0; i < expectedStrs.length; ++i) { String actualStr = JSONObject.doubleToString(doubles[i]); - assertTrue("double value expected ["+expectedStrs[i]+ + assertTrue("value expected ["+expectedStrs[i]+ "] found ["+actualStr+ "]", expectedStrs[i].equals(actualStr)); } } + + @Test + public void jsonObjectValues() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"trueStrKey\":\"true\","+ + "\"falseStrKey\":\"false\","+ + "\"stringKey\":\"hello world!\","+ + "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"intKey\":42,"+ + "\"intStrKey\":\"43\","+ + "\"longKey\":1234567890123456789,"+ + "\"longStrKey\":\"987654321098765432\","+ + "\"doubleKey\":-23.45e7,"+ + "\"doubleStrKey\":\"00001.000\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{\"myKey\":\"myVal\"}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); + assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); + assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); + assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); + assertTrue("doubleKey should be double", + jsonObject.getDouble("doubleKey") == -23.45e7); + assertTrue("doubleStrKey should be double", + jsonObject.getDouble("doubleStrKey") == 1); + assertTrue("intKey should be int", + jsonObject.getInt("intKey") == 42); + assertTrue("intStrKey should be int", + jsonObject.getInt("intStrKey") == 43); + assertTrue("longKey should be long", + jsonObject.getLong("longKey") == 1234567890123456789L); + assertTrue("longStrKey should be long", + jsonObject.getLong("longStrKey") == 987654321098765432L); + JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); + assertTrue("arrayKey should be JSONArray", + jsonArray.getInt(0) == 0 && + jsonArray.getInt(1) == 1 && + jsonArray.getInt(2) == 2); + JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); + assertTrue("objectKey should be JSONObject", + jsonObjectInner.get("myKey").equals("myVal")); + } + + @Test + public void jsonObjectNames() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; + String [] expectedNames = {"trueKey", "falseKey", "stringKey"}; + JSONObject jsonObject = new JSONObject(str); + String [] names = JSONObject.getNames(jsonObject); + Util.compareActualVsExpectedStringArrays(names, expectedNames); + } + } diff --git a/Util.java b/Util.java index d494d13..71f6c0d 100644 --- a/Util.java +++ b/Util.java @@ -70,4 +70,17 @@ public class Util { } } + public static void compareActualVsExpectedStringArrays(String[] names, + String [] expectedNames) { + assertTrue("Array lengths should be equal", + names.length == expectedNames.length); + List lNames = new ArrayList(Arrays.asList(names)); + for (int i = 0; i < expectedNames.length; ++i) { + String expectedName = expectedNames[i]; + assertTrue("expected to find "+expectedName, + lNames.contains(expectedName)); + lNames.remove(expectedName); + } + } + } From 2784c614d4bd6ee8c5810417c3de39d39ddda8da Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 10 Apr 2015 08:21:09 -0500 Subject: [PATCH 069/451] ip --- JSONObjectTest.java | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index aa434ea..a46dc8b 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -182,7 +182,6 @@ public class JSONObjectTest { "\"trueStrKey\":\"true\","+ "\"falseStrKey\":\"false\","+ "\"stringKey\":\"hello world!\","+ - "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ "\"intKey\":42,"+ "\"intStrKey\":\"43\","+ "\"longKey\":1234567890123456789,"+ @@ -233,4 +232,42 @@ public class JSONObjectTest { Util.compareActualVsExpectedStringArrays(names, expectedNames); } + @Test + public void objectNames() { + MyBean myBean = new MyBean(); + String [] expectedNames = {"intKey", "doubleKey", "stringKey", + "complexStringKey", "trueKey", "falseKey"}; + String [] names = JSONObject.getNames(myBean); + Util.compareActualVsExpectedStringArrays(names, expectedNames); + } + + @Test + public void jsonObjectIncrement() { + String str = + "{"+ + "\"keyLong\":1L,"+ + "\"keyDouble\":1.1,"+ + "\"keyFloat\":1.1F,"+ + "}"; + String expectedStr = + "{"+ + "\"keyInt\":3,"+ + "\"keyLong\":3,"+ + "\"keyDouble\":3.1,"+ + "\"keyFloat\":3.1"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("keyInt"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); + jsonObject.increment("keyFloat"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); + jsonObject.increment("keyFloat"); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + } From dcaf5fa23a43504a0ae2894dd4b3f43bcee48928 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 10 Apr 2015 19:42:34 -0500 Subject: [PATCH 070/451] ip --- JSONObjectTest.java | 70 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 64 insertions(+), 6 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index a46dc8b..860bbcf 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -193,8 +193,10 @@ public class JSONObjectTest { "}"; JSONObject jsonObject = new JSONObject(str); assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); + assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); + assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); assertTrue("doubleKey should be double", jsonObject.getDouble("doubleKey") == -23.45e7); @@ -208,6 +210,12 @@ public class JSONObjectTest { jsonObject.getLong("longKey") == 1234567890123456789L); assertTrue("longStrKey should be long", jsonObject.getLong("longStrKey") == 987654321098765432L); + assertTrue("xKey should not exist", + jsonObject.isNull("xKey")); + assertTrue("stringKey should exist", + jsonObject.has("stringKey")); + assertTrue("stringKey should string", + jsonObject.getString("stringKey").equals("hello world!")); JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); assertTrue("arrayKey should be JSONArray", jsonArray.getInt(0) == 0 && @@ -232,6 +240,32 @@ public class JSONObjectTest { Util.compareActualVsExpectedStringArrays(names, expectedNames); } + @Test + public void jsonObjectNamesToJsonAray() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; + String [] expectedNames = {"trueKey", "falseKey", "stringKey" }; + + JSONObject jsonObject = new JSONObject(str); + JSONArray jsonArray = jsonObject.names(); + /** + * Cannot really compare to an expected JSONArray because the ordering + * of the JSONObject keys is not fixed, and JSONArray comparisons + * presume fixed. Since this test is limited to key strings, a + * string comparison will have to suffice. + */ + String namesStr = jsonArray.toString(); + // remove square brackets, commas, and spaces + namesStr = namesStr.replaceAll("[\\]|\\[|\"]", ""); + String [] names = namesStr.split(","); + + Util.compareActualVsExpectedStringArrays(names, expectedNames); + } + @Test public void objectNames() { MyBean myBean = new MyBean(); @@ -245,29 +279,53 @@ public class JSONObjectTest { public void jsonObjectIncrement() { String str = "{"+ - "\"keyLong\":1L,"+ + "\"keyLong\":9999999991,"+ "\"keyDouble\":1.1,"+ - "\"keyFloat\":1.1F,"+ "}"; String expectedStr = "{"+ "\"keyInt\":3,"+ - "\"keyLong\":3,"+ + "\"keyLong\":9999999993,"+ "\"keyDouble\":3.1,"+ - "\"keyFloat\":3.1"+ "}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("keyInt"); jsonObject.increment("keyInt"); jsonObject.increment("keyLong"); jsonObject.increment("keyDouble"); - jsonObject.increment("keyFloat"); jsonObject.increment("keyInt"); jsonObject.increment("keyLong"); jsonObject.increment("keyDouble"); - jsonObject.increment("keyFloat"); JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + @Test + public void jsonObjectNamesToArray() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; + String [] expectedNames = {"trueKey", "falseKey", "stringKey"}; + JSONObject jsonObject = new JSONObject(str); + String [] names = JSONObject.getNames(jsonObject); + Util.compareActualVsExpectedStringArrays(names, expectedNames); + } + + @Test + public void jsonObjectNumberToString() { + String str; + Double dVal; + Integer iVal = 1; + str = JSONObject.numberToString(iVal); + assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); + dVal = 12.34; + str = JSONObject.numberToString(dVal); + assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + dVal = 12.34e27; + str = JSONObject.numberToString(dVal); + assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + } } From c4d9a9c5f9f8c88b1f0a4b123c7f2bbf81cd0ca9 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 12 Apr 2015 19:29:32 -0500 Subject: [PATCH 071/451] 90.8% coverage --- JSONObjectTest.java | 554 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 552 insertions(+), 2 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 860bbcf..db4e153 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -2,11 +2,19 @@ package org.json.junit; import static org.junit.Assert.*; +import java.io.*; import java.util.*; import org.json.*; import org.junit.*; +class MyJsonString implements JSONString { + + @Override + public String toJSONString() { + return "my string"; + } +} public class JSONObjectTest { @@ -198,36 +206,154 @@ public class JSONObjectTest { assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); + assertTrue("stringKey should be string", + jsonObject.getString("stringKey").equals("hello world!")); assertTrue("doubleKey should be double", jsonObject.getDouble("doubleKey") == -23.45e7); assertTrue("doubleStrKey should be double", jsonObject.getDouble("doubleStrKey") == 1); + assertTrue("opt doubleKey should be double", + jsonObject.optDouble("doubleKey") == -23.45e7); + assertTrue("opt doubleKey with Default should be double", + jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); assertTrue("intKey should be int", + jsonObject.optInt("intKey") == 42); + assertTrue("opt intKey should be int", + jsonObject.optInt("intKey", 0) == 42); + assertTrue("opt intKey with default should be int", jsonObject.getInt("intKey") == 42); assertTrue("intStrKey should be int", jsonObject.getInt("intStrKey") == 43); assertTrue("longKey should be long", jsonObject.getLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey should be long", + jsonObject.optLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey with default should be long", + jsonObject.optLong("longKey", 0) == 1234567890123456789L); assertTrue("longStrKey should be long", jsonObject.getLong("longStrKey") == 987654321098765432L); assertTrue("xKey should not exist", jsonObject.isNull("xKey")); assertTrue("stringKey should exist", jsonObject.has("stringKey")); - assertTrue("stringKey should string", - jsonObject.getString("stringKey").equals("hello world!")); + assertTrue("opt stringKey should string", + jsonObject.optString("stringKey").equals("hello world!")); + assertTrue("opt stringKey with default should string", + jsonObject.optString("stringKey", "not found").equals("hello world!")); JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); assertTrue("arrayKey should be JSONArray", jsonArray.getInt(0) == 0 && jsonArray.getInt(1) == 1 && jsonArray.getInt(2) == 2); + jsonArray = jsonObject.optJSONArray("arrayKey"); + assertTrue("opt arrayKey should be JSONArray", + jsonArray.getInt(0) == 0 && + jsonArray.getInt(1) == 1 && + jsonArray.getInt(2) == 2); JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); assertTrue("objectKey should be JSONObject", jsonObjectInner.get("myKey").equals("myVal")); } + @Test + public void jsonObjectNonAndWrongValues() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"trueStrKey\":\"true\","+ + "\"falseStrKey\":\"false\","+ + "\"stringKey\":\"hello world!\","+ + "\"intKey\":42,"+ + "\"intStrKey\":\"43\","+ + "\"longKey\":1234567890123456789,"+ + "\"longStrKey\":\"987654321098765432\","+ + "\"doubleKey\":-23.45e7,"+ + "\"doubleStrKey\":\"00001.000\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{\"myKey\":\"myVal\"}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + int tryCount = 0; + int exceptionCount = 0; + try { + ++tryCount; + jsonObject.getBoolean("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getBoolean("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getString("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getString("trueKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getDouble("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getDouble("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getInt("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getInt("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getLong("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getLong("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getJSONArray("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getJSONArray("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getJSONObject("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getJSONObject("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("all get calls should have failed", + exceptionCount == tryCount); + } + @Test public void jsonObjectNames() { + + // getNames() from null JSONObject + assertTrue("null names from null Object", + null == JSONObject.getNames((Object)null)); + + // getNames() from object with no fields + assertTrue("null names from Object with no fields", + null == JSONObject.getNames(new MyJsonString())); + + // getNames() from empty JSONObject + String emptyStr = "{}"; + JSONObject emptyJsonObject = new JSONObject(emptyStr); + assertTrue("empty JSONObject should have null names", + null == JSONObject.getNames(emptyJsonObject)); + + // getNames() from JSONObject String str = "{"+ "\"trueKey\":true,"+ @@ -327,5 +453,429 @@ public class JSONObjectTest { dVal = 12.34e27; str = JSONObject.numberToString(dVal); assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + // trailing .0 is truncated, so it doesn't quite match toString() + dVal = 5000000.0000000; + str = JSONObject.numberToString(dVal); + assertTrue("expected 5000000 actual "+str, str.equals("5000000")); + } + + @Test + public void jsonObjectPut() { + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + String expectedStrAfterRemoval = + "{"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("trueKey", true); + jsonObject.put("falseKey", false); + Integer [] intArray = { 0, 1, 2 }; + jsonObject.put("arrayKey", Arrays.asList(intArray)); + Map myMap = new HashMap(); + myMap.put("myKey1", "myVal1"); + myMap.put("myKey2", "myVal2"); + myMap.put("myKey3", "myVal3"); + myMap.put("myKey4", "myVal4"); + jsonObject.put("objectKey", myMap); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + assertTrue("equal jsonObjects should be similar", + jsonObject.similar(expectedJsonObject)); + + jsonObject.remove("trueKey"); + JSONObject expectedJsonObjectAfterRemoval = + new JSONObject(expectedStrAfterRemoval); + Util.compareActualVsExpectedJsonObjects(jsonObject, + expectedJsonObjectAfterRemoval); + assertTrue("unequal jsonObjects should not be similar", + !jsonObject.similar(expectedJsonObject)); + assertTrue("unequal Objects should not be similar", + !jsonObject.similar(new JSONArray())); + + String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; + String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; + JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); + JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); + assertTrue("different values should not be similar", + !aCompareValueJsonObject.similar(bCompareValueJsonObject)); + + String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; + String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; + JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); + JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); + assertTrue("different nested JSONObjects should not be similar", + !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); + + String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; + String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; + JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); + JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); + assertTrue("different nested JSONArrays should not be similar", + !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); + } + + @Test + public void jsonObjectToString() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + String toStr = jsonObject.toString(); + JSONObject expectedJsonObject = new JSONObject(toStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void valueToString() { + + assertTrue("null valueToString() incorrect", + "null".equals(JSONObject.valueToString(null))); + MyJsonString jsonString = new MyJsonString(); + assertTrue("jsonstring valueToString() incorrect", + "my string".equals(JSONObject.valueToString(jsonString))); + assertTrue("boolean valueToString() incorrect", + "true".equals(JSONObject.valueToString(Boolean.TRUE))); + assertTrue("non-numeric double", + "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); + String jsonObjectStr = + "{"+ + "\"key1\":\"val1\","+ + "\"key2\":\"val2\","+ + "\"key3\":\"val3\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("jsonObject valueToString() incorrect", + JSONObject.valueToString(jsonObject).equals(jsonObject.toString())); + String jsonArrayStr = + "[1,2,3]"; + JSONArray jsonArray = new JSONArray(jsonArrayStr); + assertTrue("jsonArra valueToString() incorrect", + JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); + Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + assertTrue("map valueToString() incorrect", + jsonObject.toString().equals(JSONObject.valueToString(map))); + Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + assertTrue("collection valueToString() expected: "+ + jsonArray.toString()+ " actual: "+ + JSONObject.valueToString(collection), + jsonArray.toString().equals(JSONObject.valueToString(collection))); + Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; + assertTrue("array valueToString() incorrect", + jsonArray.toString().equals(JSONObject.valueToString(array))); + } + + @Test + public void wrapObject() { + // wrap(null) returns NULL + assertTrue("null wrap() incorrect", + JSONObject.NULL == JSONObject.wrap(null)); + + // wrap(Integer) returns Integer + Integer in = new Integer(1); + assertTrue("Integer wrap() incorrect", + in == JSONObject.wrap(in)); + + // wrap JSONObject returns JSONObject + String jsonObjectStr = + "{"+ + "\"key1\":\"val1\","+ + "\"key2\":\"val2\","+ + "\"key3\":\"val3\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("JSONObject wrap() incorrect", + jsonObject == JSONObject.wrap(jsonObject)); + + // wrap collection returns JSONArray + Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + JSONArray jsonArray = (JSONArray)(JSONObject.wrap(collection)); + String expectedCollectionJsonArrayStr = + "[1,2,3]"; + JSONArray expectedCollectionJsonArray = + new JSONArray(expectedCollectionJsonArrayStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, + expectedCollectionJsonArray); + + // wrap Array returns JSONArray + Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; + JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); + JSONArray expectedIntegerArrayJsonArray = new JSONArray("[1,2,3]"); + Util.compareActualVsExpectedJsonArrays(integerArrayJsonArray, + expectedIntegerArrayJsonArray); + + // wrap map returns JSONObject + Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + JSONObject mapJsonObject = (JSONObject)(JSONObject.wrap(map)); + Util.compareActualVsExpectedJsonObjects(jsonObject, mapJsonObject); + + // TODO test wrap(package) + } + + @Test + public void jsonObjectEquals() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + String diffStr = + "{"+ + "\"arrayKey\":[0]"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + JSONObject otherJsonObject = new JSONObject(str); + JSONObject unequalJsonObject = new JSONObject(diffStr); + assertTrue("equal JSONObjects should be equal", + jsonObject.equals(otherJsonObject)); + assertTrue("unequal JSONObjects should not be equal", + !jsonObject.equals(unequalJsonObject)); + + // make sure hashcode returns some interesting value + assertTrue("equal JSONObjects should have equal hashCode", + jsonObject.hashCode() == otherJsonObject.hashCode()); + assertTrue("unequal JSONObjects should have unequal hashCode", + jsonObject.hashCode() != unequalJsonObject.hashCode()); + } + + @Test + public void jsonObjectParsingErrors() { + int tryCount = 0; + int exceptionCount = 0; + try { + // does not start with '{' + ++tryCount; + String str = "abc"; + new JSONObject(str); + } catch (JSONException ignore) {++exceptionCount; } + try { + // does not end with '}' + ++tryCount; + String str = "{"; + new JSONObject(str); + } catch (JSONException ignore) {++exceptionCount; } + try { + // key with no ':' + ++tryCount; + String str = "{\"myKey\" = true}"; + new JSONObject(str); + } catch (JSONException ignore) {++exceptionCount; } + try { + // entries with no ',' separator + ++tryCount; + String str = "{\"myKey\":true \"myOtherKey\":false}"; + new JSONObject(str); + } catch (JSONException ignore) {++exceptionCount; } + try { + // append to wrong key + ++tryCount; + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.append("myKey", "hello"); + } catch (JSONException ignore) {++exceptionCount; } + try { + // increment wrong key + ++tryCount; + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("myKey"); + } catch (JSONException ignore) {++exceptionCount; } + try { + // invalid key + ++tryCount; + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.get(null); + } catch (JSONException ignore) {++exceptionCount; } + try { + // invalid numberToString() + ++tryCount; + JSONObject.numberToString((Number)null); + } catch (JSONException ignore) {++exceptionCount; } + try { + // null put key + ++tryCount; + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0); + } catch (NullPointerException ignore) {++exceptionCount; } + try { + // multiple putOnce key + ++tryCount; + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.putOnce("hello", "world"); + jsonObject.putOnce("hello", "world!"); + } catch (JSONException ignore) {++exceptionCount; } + try { + // test validity of invalid double + ++tryCount; + JSONObject.testValidity(Double.NaN); + } catch (JSONException ignore) {++exceptionCount; } + try { + // test validity of invalid float + ++tryCount; + JSONObject.testValidity(Float.NEGATIVE_INFINITY); + } catch (JSONException ignore) {++exceptionCount; } + + assertTrue("all tries should have failed", + exceptionCount == tryCount); + } + + @Test + public void jsonObjectOptDefault() { + + String str = "{\"myKey\": \"myval\"}"; + JSONObject jsonObject = new JSONObject(str); + + assertTrue("optBoolean() should return default boolean", + Boolean.TRUE == jsonObject.optBoolean("myKey", Boolean.TRUE)); + assertTrue("optInt() should return default int", + 42 == jsonObject.optInt("myKey", 42)); + assertTrue("optInt() should return default int", + 42 == jsonObject.optInt("myKey", 42)); + assertTrue("optLong() should return default long", + 42 == jsonObject.optLong("myKey", 42)); + assertTrue("optDouble() should return default double", + 42.3 == jsonObject.optDouble("myKey", 42.3)); + assertTrue("optString() should return default string", + "hi".equals(jsonObject.optString("hiKey", "hi"))); + } + + @Test + public void jsonObjectputNull() { + + // put null should remove the item. + String str = "{\"myKey\": \"myval\"}"; + JSONObject jsonObjectRemove = new JSONObject(str); + JSONObject jsonObjectPutNull = new JSONObject(str); + jsonObjectRemove.remove("myKey"); + jsonObjectPutNull.put("myKey", (Object)null); + Util.compareActualVsExpectedJsonObjects(jsonObjectRemove, jsonObjectPutNull); + assertTrue("jsonObject should be empty", + jsonObjectRemove.length() == 0 && + jsonObjectPutNull.length() == 0); + } + + @Test + public void jsonObjectQuote() { + String str; + str = ""; + String quotedStr; + quotedStr = JSONObject.quote(str); + assertTrue("quote() expected escaped quotes, found "+quotedStr, + "\"\"".equals(quotedStr)); + str = "\"\""; + quotedStr = JSONObject.quote(str); + assertTrue("quote() expected escaped quotes, found "+quotedStr, + "\"\\\"\\\"\"".equals(quotedStr)); + str = " Date: Sun, 12 Apr 2015 19:35:34 -0500 Subject: [PATCH 072/451] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index da0c4ee..195f080 100644 --- a/README.md +++ b/README.md @@ -31,11 +31,11 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | CookieList.java |96.5% | Completed | | HTTP.java | 98.7%| Completed | | HTTPTokener.java |93.2% |Completed | -| JSONArray.java |18.3% | | +| JSONArray.java |42.3% | In progress | | JSONException.java | 26.7% | | -| JSONML.java | 83.2%| completed | -| JSONObject | 24.9% | | in progress | -| JSONObject.Null | 75.0% | | | +| JSONML.java | 83.2%| Completed | +| JSONObject | 90.8% | Completed | +| JSONObject.Null | 87.5% | | | | JSONStringer.java | 93.8%| Completed | | JSONTokener.java | 72.1% | | | JSONWriter.java | 88.9% | Completed | From a85786952201351a0522892f2c02b49b142e345f Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sun, 12 Apr 2015 19:36:01 -0500 Subject: [PATCH 073/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 195f080..53f11a5 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 58.4% | | | +| Total coverage | 81.6% | | | | | | | | CDL.java | 94.8% | Completed | | Cookie.java | 97.5% | Completed | From 6a2c974581fca0d889fc5b9799ea7d9e7c2395c5 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 12 Apr 2015 23:34:23 -0500 Subject: [PATCH 074/451] 90.9% coverage --- JSONObjectTest.java | 38 -------------------------------------- 1 file changed, 38 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index db4e153..824a674 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -650,39 +650,6 @@ public class JSONObjectTest { // TODO test wrap(package) } - @Test - public void jsonObjectEquals() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{"+ - "\"myKey1\":\"myVal1\","+ - "\"myKey2\":\"myVal2\","+ - "\"myKey3\":\"myVal3\","+ - "\"myKey4\":\"myVal4\""+ - "}"+ - "}"; - String diffStr = - "{"+ - "\"arrayKey\":[0]"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - JSONObject otherJsonObject = new JSONObject(str); - JSONObject unequalJsonObject = new JSONObject(diffStr); - assertTrue("equal JSONObjects should be equal", - jsonObject.equals(otherJsonObject)); - assertTrue("unequal JSONObjects should not be equal", - !jsonObject.equals(unequalJsonObject)); - - // make sure hashcode returns some interesting value - assertTrue("equal JSONObjects should have equal hashCode", - jsonObject.hashCode() == otherJsonObject.hashCode()); - assertTrue("unequal JSONObjects should have unequal hashCode", - jsonObject.hashCode() != unequalJsonObject.hashCode()); - } - @Test public void jsonObjectParsingErrors() { int tryCount = 0; @@ -869,13 +836,8 @@ public class JSONObjectTest { public void equals() { String str = "{\"key\":\"value\"}"; JSONObject aJsonObject = new JSONObject(str); - JSONObject bJsonObject = new JSONObject(str); assertTrue("Same JSONObject should be equal to itself", aJsonObject.equals(aJsonObject)); - assertTrue("JSONObjects with equal content should be equal", - aJsonObject.equals(bJsonObject)); - assertTrue("JSONObjects should not be equal to non J", - !aJsonObject.equals(new String())); } } From 76c30539ccb0583f81548a837b6ca6ab8e7120fd Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 13 Apr 2015 21:39:26 -0500 Subject: [PATCH 075/451] 95.9% coverage --- JSONArrayTest.java | 455 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 455 insertions(+) create mode 100644 JSONArrayTest.java diff --git a/JSONArrayTest.java b/JSONArrayTest.java new file mode 100644 index 0000000..2799a04 --- /dev/null +++ b/JSONArrayTest.java @@ -0,0 +1,455 @@ +package org.json.junit; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.json.*; +import org.junit.Test; + + +/** + * Tests for JSON-Java JSONArray.java + */ +public class JSONArrayTest { + String arrayStr = + "["+ + "true,"+ + "false,"+ + "\"true\","+ + "\"false\","+ + "\"hello\","+ + "23.45e-4,"+ + "\"23.45\","+ + "42,"+ + "\"43\","+ + "["+ + "\"world\""+ + "],"+ + "{"+ + "\"key1\":\"value1\","+ + "\"key2\":\"value2\","+ + "\"key3\":\"value3\","+ + "\"key4\":\"value4\""+ + "},"+ + "0,"+ + "\"-1\""+ + "]"; + + @Test(expected=NullPointerException.class) + public void nullException() { + String str = null; + new JSONArray(str); + } + + @Test(expected=JSONException.class) + public void emptStr() { + String str = ""; + new JSONArray(str); + } + + @Test(expected=JSONException.class) + public void badObject() { + String str = "abc"; + new JSONArray((Object)str); + } + + @Test + public void getArrayValues() { + JSONArray jsonArray = new JSONArray(arrayStr); + assertTrue("Array true", + true == jsonArray.getBoolean(0)); + assertTrue("Array false", + false == jsonArray.getBoolean(1)); + assertTrue("Array string true", + true == jsonArray.getBoolean(2)); + assertTrue("Array string false", + false == jsonArray.getBoolean(3)); + + assertTrue("Array double", + new Double(23.45e-4).equals(jsonArray.getDouble(5))); + assertTrue("Array string double", + new Double(23.45).equals(jsonArray.getDouble(6))); + + assertTrue("Array value int", + new Integer(42).equals(jsonArray.getInt(7))); + assertTrue("Array value string int", + new Integer(43).equals(jsonArray.getInt(8))); + + JSONArray nestedJsonArray = jsonArray.getJSONArray(9); + assertTrue("Array value JSONArray", nestedJsonArray != null); + + JSONObject nestedJsonObject = jsonArray.getJSONObject(10); + assertTrue("Array value JSONObject", nestedJsonObject != null); + + assertTrue("Array value long", + new Long(0).equals(jsonArray.getLong(11))); + assertTrue("Array value string long", + new Long(-1).equals(jsonArray.getLong(12))); + + assertTrue("Array value string", + "hello".equals(jsonArray.getString(4))); + + assertTrue("Array value null", jsonArray.isNull(-1)); + } + + @Test + public void failedGetArrayValues() { + int tryCount = 0; + int exceptionCount = 0; + JSONArray jsonArray = new JSONArray(arrayStr); + try { + tryCount++; + jsonArray.getBoolean(4); + assertTrue("expected getBoolean to fail", false); + } catch (JSONException ignored) { exceptionCount++; } + try { + tryCount++; + jsonArray.get(-1); + assertTrue("expected get to fail", false); + } catch (JSONException ignored) { exceptionCount++; } + try { + tryCount++; + jsonArray.getDouble(4); + assertTrue("expected getDouble to fail", false); + } catch (JSONException ignored) { exceptionCount++; } + try { + tryCount++; + jsonArray.getInt(4); + assertTrue("expected getInt to fail", false); + } catch (JSONException ignored) { exceptionCount++; } + try { + tryCount++; + jsonArray.getJSONArray(4); + assertTrue("expected getJSONArray to fail", false); + } catch (JSONException ignored) { exceptionCount++; } + try { + tryCount++; + jsonArray.getJSONObject(4); + assertTrue("expected getJSONObject to fail", false); + } catch (JSONException ignored) { exceptionCount++; } + try { + tryCount++; + jsonArray.getLong(4); + assertTrue("expected getLong to fail", false); + } catch (JSONException ignored) { exceptionCount++; } + try { + tryCount++; + jsonArray.getString(5); + assertTrue("expected getString to fail", false); + } catch (JSONException ignored) { exceptionCount++; } + assertTrue("tryCount should match exceptionCount", + tryCount == exceptionCount); + } + + @Test + public void join() { + String expectedStr = + "["+ + "true,"+ + "false,"+ + "\"true\","+ + "\"false\","+ + "\"hello\","+ + "0.002345,"+ + "\"23.45\","+ + "42,"+ + "\"43\","+ + "["+ + "\"world\""+ + "],"+ + "{"+ + "\"key1\":\"value1\","+ + "\"key2\":\"value2\","+ + "\"key3\":\"value3\","+ + "\"key4\":\"value4\""+ + "},"+ + "0,"+ + "\"-1\""+ + "]"; + + JSONArray jsonArray = new JSONArray(arrayStr); + String joinStr = jsonArray.join(","); + JSONArray finalJsonArray = new JSONArray("["+joinStr+"]"); + JSONArray expectedJsonArray = new JSONArray(expectedStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); + } + + @Test + public void length() { + assertTrue("expected empty JSONArray length 0", + new JSONArray().length() == 0); + JSONArray jsonArray = new JSONArray(arrayStr); + assertTrue("expected JSONArray length 13", jsonArray.length() == 13); + JSONArray nestedJsonArray = jsonArray.getJSONArray(9); + assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1); + } + + @Test + public void opt() { + JSONArray jsonArray = new JSONArray(arrayStr); + assertTrue("Array opt value true", + Boolean.TRUE == jsonArray.opt(0)); + assertTrue("Array opt value out of range", + null == jsonArray.opt(-1)); + + assertTrue("Array opt boolean", + Boolean.TRUE == jsonArray.optBoolean(0)); + assertTrue("Array opt boolean default", + Boolean.FALSE == jsonArray.optBoolean(-1, Boolean.FALSE)); + assertTrue("Array opt boolean implicit default", + Boolean.FALSE == jsonArray.optBoolean(-1)); + + assertTrue("Array opt double", + new Double(23.45e-4).equals(jsonArray.optDouble(5))); + assertTrue("Array opt double default", + new Double(1).equals(jsonArray.optDouble(0, 1))); + assertTrue("Array opt double default implicit", + new Double(jsonArray.optDouble(99)).isNaN()); + + assertTrue("Array opt int", + new Integer(42).equals(jsonArray.optInt(7))); + assertTrue("Array opt int default", + new Integer(-1).equals(jsonArray.optInt(0, -1))); + assertTrue("Array opt int default implicit", + 0 == jsonArray.optInt(0)); + + JSONArray nestedJsonArray = jsonArray.optJSONArray(9); + assertTrue("Array opt JSONArray", nestedJsonArray != null); + assertTrue("Array opt JSONArray default", + null == jsonArray.optJSONArray(99)); + + JSONObject nestedJsonObject = jsonArray.optJSONObject(10); + assertTrue("Array opt JSONObject", nestedJsonObject != null); + assertTrue("Array opt JSONObject default", + null == jsonArray.optJSONObject(99)); + + assertTrue("Array opt long", + 0 == jsonArray.optLong(11)); + assertTrue("Array opt long default", + -2 == jsonArray.optLong(-1, -2)); + assertTrue("Array opt long default implicit", + 0 == jsonArray.optLong(-1)); + + assertTrue("Array opt string", + "hello".equals(jsonArray.optString(4))); + assertTrue("Array opt string default implicit", + "".equals(jsonArray.optString(-1))); + } + + @Test + public void put() { + String expectedStr = + "["+ + "true,"+ + "false,"+ + "["+ + "hello,"+ + "world"+ + "],"+ + "2.5,"+ + "1,"+ + "45,"+ + "\"objectPut\","+ + "{"+ + "\"key10\":\"val10\","+ + "\"key20\":\"val20\","+ + "\"key30\":\"val30\""+ + "},"+ + "{"+ + "\"k1\":\"v1\""+ + "},"+ + "["+ + "1,"+ + "2"+ + "]"+ + "]"; + JSONArray jsonArray = new JSONArray(); + JSONArray expectedJsonArray = new JSONArray(expectedStr); + + // index 0 + jsonArray.put(true); + // 1 + jsonArray.put(false); + + String jsonArrayStr = + "["+ + "hello,"+ + "world"+ + "]"; + // 2 + jsonArray.put(new JSONArray(jsonArrayStr)); + + // 3 + jsonArray.put(2.5); + // 4 + jsonArray.put(1); + // 5 + jsonArray.put(45L); + + // 6 + jsonArray.put("objectPut"); + + String jsonObjectStr = + "{"+ + "\"key10\":\"val10\","+ + "\"key20\":\"val20\","+ + "\"key30\":\"val30\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + // 7 + jsonArray.put(jsonObject); + + Map map = new HashMap(); + map.put("k1", "v1"); + // 8 + jsonArray.put(map); + + Collection collection = new ArrayList(); + collection.add(1); + collection.add(2); + // 9 + jsonArray.put(collection); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + } + + @Test + public void putIndex() { + String expectedStr = + "["+ + "true,"+ + "false,"+ + "["+ + "hello,"+ + "world"+ + "],"+ + "2.5,"+ + "1,"+ + "45,"+ + "\"objectPut\","+ + "null,"+ + "{"+ + "\"key10\":\"val10\","+ + "\"key20\":\"val20\","+ + "\"key30\":\"val30\""+ + "},"+ + "["+ + "1,"+ + "2"+ + "],"+ + "{"+ + "\"k1\":\"v1\""+ + "},"+ + "]"; + JSONArray jsonArray = new JSONArray(); + JSONArray expectedJsonArray = new JSONArray(expectedStr); + + // 1 + jsonArray.put(1, false); + // index 0 + jsonArray.put(0, true); + + String jsonArrayStr = + "["+ + "hello,"+ + "world"+ + "]"; + // 2 + jsonArray.put(2, new JSONArray(jsonArrayStr)); + + // 5 + jsonArray.put(5, 45L); + // 4 + jsonArray.put(4, 1); + // 3 + jsonArray.put(3, 2.5); + + // 6 + jsonArray.put(6, "objectPut"); + + // 7 will be null + + String jsonObjectStr = + "{"+ + "\"key10\":\"val10\","+ + "\"key20\":\"val20\","+ + "\"key30\":\"val30\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + jsonArray.put(8, jsonObject); + Collection collection = new ArrayList(); + collection.add(1); + collection.add(2); + jsonArray.put(9,collection); + + Map map = new HashMap(); + map.put("k1", "v1"); + jsonArray.put(10, map); + try { + jsonArray.put(-1, "abc"); + assertTrue("put index < 0 should have thrown exception", false); + } catch(Exception ignored) {} + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + } + + @Test + public void remove() { + String arrayStr = + "["+ + "1"+ + "]"; + JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray expectedJsonArray = new JSONArray(); + jsonArray.remove(0); + assertTrue("array should be empty", null == jsonArray.remove(5)); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + } + + @Test + public void notSimilar() { + String arrayStr = + "["+ + "1"+ + "]"; + JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray otherJsonArray = new JSONArray(); + assertTrue("arrays lengths differ", !jsonArray.similar(otherJsonArray)); + + JSONObject jsonObject = new JSONObject("{\"k1\":\"v1\"}"); + JSONObject otherJsonObject = new JSONObject(); + jsonArray = new JSONArray(); + jsonArray.put(jsonObject); + otherJsonArray = new JSONArray(); + otherJsonArray.put(otherJsonObject); + assertTrue("arrays JSONObjects differ", !jsonArray.similar(otherJsonArray)); + + JSONArray nestedJsonArray = new JSONArray("[1, 2]"); + JSONArray otherNestedJsonArray = new JSONArray(); + jsonArray = new JSONArray(); + jsonArray.put(nestedJsonArray); + otherJsonArray = new JSONArray(); + otherJsonArray.put(otherNestedJsonArray); + assertTrue("arrays nested JSONArrays differ", + !jsonArray.similar(otherJsonArray)); + + jsonArray = new JSONArray(); + jsonArray.put("hello"); + otherJsonArray = new JSONArray(); + otherJsonArray.put("world"); + assertTrue("arrays values differ", + !jsonArray.similar(otherJsonArray)); + } + + @Test + public void toJSONObject() { + JSONArray names = new JSONArray(); + JSONArray jsonArray = new JSONArray(); + assertTrue("toJSONObject should return null", + null == jsonArray.toJSONObject(names)); + + } +} From 51e8a2d1e57cf5626b83403813f1c7e3cc028a46 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 13 Apr 2015 21:45:31 -0500 Subject: [PATCH 076/451] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 53f11a5..d6439c8 100644 --- a/README.md +++ b/README.md @@ -24,17 +24,17 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 81.6% | | | +| Total coverage | 88.7% | | | | | | | | CDL.java | 94.8% | Completed | | Cookie.java | 97.5% | Completed | | CookieList.java |96.5% | Completed | | HTTP.java | 98.7%| Completed | | HTTPTokener.java |93.2% |Completed | -| JSONArray.java |42.3% | In progress | +| JSONArray.java |95.9% | In progress | | JSONException.java | 26.7% | | | JSONML.java | 83.2%| Completed | -| JSONObject | 90.8% | Completed | +| JSONObject | 90.9% | Completed | | JSONObject.Null | 87.5% | | | | JSONStringer.java | 93.8%| Completed | | JSONTokener.java | 72.1% | | From 9bffd5b3ca341b9dc0d97a71960f1fe854351ee6 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 13 Apr 2015 22:25:13 -0500 Subject: [PATCH 077/451] Update README.md --- README.md | 40 ++++++++++++++++++++++++---------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index d6439c8..a8f37a0 100644 --- a/README.md +++ b/README.md @@ -26,21 +26,29 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | ------------- | ------------- | ---- | | Total coverage | 88.7% | | | | | | | -| CDL.java | 94.8% | Completed | -| Cookie.java | 97.5% | Completed | -| CookieList.java |96.5% | Completed | -| HTTP.java | 98.7%| Completed | -| HTTPTokener.java |93.2% |Completed | -| JSONArray.java |95.9% | In progress | -| JSONException.java | 26.7% | | -| JSONML.java | 83.2%| Completed | -| JSONObject | 90.9% | Completed | -| JSONObject.Null | 87.5% | | | -| JSONStringer.java | 93.8%| Completed | -| JSONTokener.java | 72.1% | | -| JSONWriter.java | 88.9% | Completed | -| Property.java | 94.8% | Completed | -| XML.java | 85.1% | Completed | -| XMLTokener.java| 82.7%| Completed | +| CDLTest.java | 94.8% | Completed | +| CookieTest.java | 97.5% | Completed | +| CookieListTest.java |96.5% | Completed | +| HTTPTest.java | 98.7%| Completed | +| HTTPTokene.java |93.2% |(no test file) | +| JSONArrayTest.java |95.9% | In progress | +| JSONException.java | 26.7% | (no test file) | +| JSONMLTest.java | 83.2%| Completed | +| JSONObjectTest | 90.9% | Completed | +| JSONObject.Null | 87.5% | (no test file) | +| JSONString.java | | (no lines to test) | +| JSONStringerTest.java | 93.8%| Completed | +| JSONTokener.java | 72.1% | (no test file) | +| JSONWriter.java | 88.9% | (no test file) | +| PropertyTest.java | 94.8% | Completed | +| XMLTest.java | 85.1% | Completed | +| XMLTokener.java| 82.7%| (no test file) | + +|| Files used in test || +| JunitTestSuite.java | +| MyBean.java | +| StringsResourceBundle.java | +|TestRUnner.java | +| Util.java | From 67fbfa12eaf7569e9157b731d7d717fd889b67c6 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 13 Apr 2015 22:27:48 -0500 Subject: [PATCH 078/451] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a8f37a0..768288b 100644 --- a/README.md +++ b/README.md @@ -31,14 +31,14 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | CookieListTest.java |96.5% | Completed | | HTTPTest.java | 98.7%| Completed | | HTTPTokene.java |93.2% |(no test file) | -| JSONArrayTest.java |95.9% | In progress | +| JSONArrayTest.java |95.9% | Completed | | JSONException.java | 26.7% | (no test file) | | JSONMLTest.java | 83.2%| Completed | | JSONObjectTest | 90.9% | Completed | | JSONObject.Null | 87.5% | (no test file) | | JSONString.java | | (no lines to test) | | JSONStringerTest.java | 93.8%| Completed | -| JSONTokener.java | 72.1% | (no test file) | +| JSONTokenerTest.java | 72.1% | In progress | | JSONWriter.java | 88.9% | (no test file) | | PropertyTest.java | 94.8% | Completed | | XMLTest.java | 85.1% | Completed | From 98cdaf6a3963cb272d413a7b98c3f3eba9a691e2 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 13 Apr 2015 22:28:57 -0500 Subject: [PATCH 079/451] Update README.md --- README.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 768288b..f5b12f4 100644 --- a/README.md +++ b/README.md @@ -44,11 +44,12 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | XMLTest.java | 85.1% | Completed | | XMLTokener.java| 82.7%| (no test file) | -|| Files used in test || -| JunitTestSuite.java | -| MyBean.java | -| StringsResourceBundle.java | -|TestRUnner.java | -| Util.java | +|| Files used in test || || +| ------------- | | +| JunitTestSuite.java | | +| MyBean.java | | +| StringsResourceBundle.java | | +|TestRUnner.java | | +| Util.java | | From e5c01e4ff8ab95d0592e0526b8293b46aff3f1c5 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 13 Apr 2015 22:29:27 -0500 Subject: [PATCH 080/451] Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f5b12f4..588481e 100644 --- a/README.md +++ b/README.md @@ -44,12 +44,12 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | XMLTest.java | 85.1% | Completed | | XMLTokener.java| 82.7%| (no test file) | -|| Files used in test || || -| ------------- | | -| JunitTestSuite.java | | -| MyBean.java | | -| StringsResourceBundle.java | | -|TestRUnner.java | | -| Util.java | | +| Files used in test | +| ------------- | +| JunitTestSuite.java | +| MyBean.java | +| StringsResourceBundle.java | +|TestRUnner.java | +| Util.java | From d75a96ae59c723fbac857443b750b32cb8856006 Mon Sep 17 00:00:00 2001 From: stleary Date: Tue, 14 Apr 2015 01:12:08 -0500 Subject: [PATCH 081/451] 95.9% coverage --- JSONArrayTest.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/JSONArrayTest.java b/JSONArrayTest.java index 2799a04..78b194e 100644 --- a/JSONArrayTest.java +++ b/JSONArrayTest.java @@ -450,6 +450,18 @@ public class JSONArrayTest { JSONArray jsonArray = new JSONArray(); assertTrue("toJSONObject should return null", null == jsonArray.toJSONObject(names)); - + } + + @Test + public void objectArrayVsIsArray() { + String expectedStr = + "["+ + "1,2,3,4,5,6,7"+ + "]"; + int[] myInts = { 1, 2, 3, 4, 5, 6, 7 }; + Object myObject = myInts; + JSONArray jsonArray = new JSONArray(myObject); + JSONArray expectedJsonArray = new JSONArray(expectedStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } } From 0409c9bfb225a11c7d1ddc75dcc9cb9f5d58d68b Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 14 Apr 2015 10:59:19 -0500 Subject: [PATCH 082/451] Update README.md --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 588481e..848a02f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ # JSON-Java-unit-test -Unit tests to validate the JSON-Java GitHub project code (https://github.com/douglascrockford/JSON-java).
+Unit tests to validate the JSON-Java GitHub project code
+https://github.com/douglascrockford/JSON-java
+ +*These tests are a work in progress. Help improving the tests is welcome* +More coverage is needed, but more important is to improve the quality of the tests. Test harness: http://junit.org
Coverage: http://www.eclemma.org/
From 9e78cfc48df7058e1497160ea290fe17c9ccdada Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 14 Apr 2015 11:00:42 -0500 Subject: [PATCH 083/451] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 848a02f..8bfa5e8 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ Unit tests to validate the JSON-Java GitHub project code
https://github.com/douglascrockford/JSON-java
-*These tests are a work in progress. Help improving the tests is welcome* -More coverage is needed, but more important is to improve the quality of the tests. +*These tests are a work in progress. Help from interested developers is welcome.*
+More coverage is needed, but more important is to improve the quality of the tests.
Test harness: http://junit.org
Coverage: http://www.eclemma.org/
From d9e04ec5b64a15af0b133056aca4a3e67df8ac2e Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 14 Apr 2015 11:01:29 -0500 Subject: [PATCH 084/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8bfa5e8..bd17a5f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Unit tests to validate the JSON-Java GitHub project code
https://github.com/douglascrockford/JSON-java
*These tests are a work in progress. Help from interested developers is welcome.*
-More coverage is needed, but more important is to improve the quality of the tests.
+More coverage is needed, but more importantly, improvements to test quality is needed.
Test harness: http://junit.org
Coverage: http://www.eclemma.org/
From 9df929963f83c209a36a64c776a679371855cc67 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 19 Apr 2015 17:10:47 -0500 Subject: [PATCH 085/451] added a trivial XML string compare method - still needs work --- Util.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Util.java b/Util.java index 71f6c0d..53ec402 100644 --- a/Util.java +++ b/Util.java @@ -83,4 +83,13 @@ public class Util { } } + public static void compareXML(String aXmlStr, String bXmlStr) { + // TODO For simple tests this may be adequate, but it won't work for + // elements with multiple attributes and possibly other cases as well. + // Should use XMLUnit or similar. + assertTrue("expected equal XML strings \naXmlStr: "+ + aXmlStr+ "\nbXmlStr: " +bXmlStr, aXmlStr.equals(bXmlStr)); + + } + } From f0d175c5b2005b9061287f843af03c7d24e2000c Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 19 Apr 2015 17:11:05 -0500 Subject: [PATCH 086/451] Added JSONArrayTest --- JunitTestSuite.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/JunitTestSuite.java b/JunitTestSuite.java index 63bde2f..a91426d 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -12,7 +12,8 @@ import org.junit.runners.Suite; JSONMLTest.class, HTTPTest.class, JSONStringerTest.class, - JSONObjectTest.class + JSONObjectTest.class, + JSONArrayTest.class }) public class JunitTestSuite { } \ No newline at end of file From 35a4fefd2ebef1f14b1b251bf5d5332ba9ddc8ca Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 19 Apr 2015 17:11:51 -0500 Subject: [PATCH 087/451] test JSONML.toString(JSONArray) --- JSONMLTest.java | 406 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 301 insertions(+), 105 deletions(-) diff --git a/JSONMLTest.java b/JSONMLTest.java index b2a4e06..fa982e1 100644 --- a/JSONMLTest.java +++ b/JSONMLTest.java @@ -6,36 +6,63 @@ import org.json.*; import org.junit.Test; /** - * Tests for JSON-Java JSONML.java + * Tests for org.json.JSONML.java + * + * Certain inputs are expected to result in exceptions. These tests are + * executed first. JSONML provides an API to: + * Convert an XML string into a JSONArray or a JSONObject. + * Convert a JSONArray or JSONObject into an XML string. + * Both fromstring and tostring operations operations should be symmetrical + * within the limits of JSONML. + * It should be possible to perform the following operations, which should + * result in the original string being recovered, within the limits of the + * underlying classes: + * Convert a string -> JSONArray -> string -> JSONObject -> string + * Convert a string -> JSONObject -> string -> JSONArray -> string + * */ public class JSONMLTest { @Test(expected=NullPointerException.class) public void nullXMLException() { - + /** + * Attempts to transform a null XML string to JSON + */ String xmlStr = null; JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) public void emptyXMLException() { - + /** + * Attempts to transform an empty XML string to JSON + */ String xmlStr = ""; JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) public void nonXMLException() { + /** + * Attempts to transform a nonXML string to JSON + */ String xmlStr = "{ \"this is\": \"not xml\"}"; JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) public void emptyTagException() { + /** + * jsonArrayStr is used to build a JSONArray which is then + * turned into XML. For this transformation, all arrays represent + * elements and the first array entry is the name of the element. + * In this case, one of the arrays does not have a name + */ String jsonArrayStr = "[\"addresses\","+ "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ + // this array has no name "["+ "[\"name\"],"+ "[\"nocontent\"],"+ @@ -48,10 +75,18 @@ public class JSONMLTest { @Test(expected=JSONException.class) public void spaceInTagException() { + /** + * jsonArrayStr is used to build a JSONArray which is then + * turned into XML. For this transformation, all arrays represent + * elements and the first array entry is the name of the element. + * In this case, one of the element names has an embedded space, + * which is not allowed. + */ String jsonArrayStr = "[\"addresses\","+ "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ + // this array has an invalid name "[\"addr esses\","+ "[\"name\"],"+ "[\"nocontent\"],"+ @@ -63,7 +98,12 @@ public class JSONMLTest { } @Test(expected=JSONException.class) - public void unvalidSlashInTagException() { + public void invalidSlashInTagException() { + /** + * xmlStr contains XML text which is transformed into a JSONArray. + * In this case, the XML is invalid because the 'name' element + * contains an invalid frontslash. + */ String xmlStr = "\n"+ "\n"+ " \n"+ " abc street\n"+ - " \n"+ + " \n"+ ""; JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) public void invalidBangInTagException() { + /** + * xmlStr contains XML text which is transformed into a JSONArray. + * In this case, the XML is invalid because an element + * has the invalid name '!'. + */ String xmlStr = "\n"+ "\n"+ " \n"+ " \n"+ - " \n"+ + " \n"+ ""; JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) public void invalidBangNoCloseInTagException() { + /** + * xmlStr contains XML text which is transformed into a JSONArray. + * In this case, the XML is invalid because an element + * starts with '!' and has no closing tag + */ String xmlStr = "\n"+ "\n"+ " \n"+ " \n"+ + " \n"+ ""; JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) public void noCloseStartTagException() { + /** + * xmlStr contains XML text which is transformed into a JSONArray. + * In this case, the XML is invalid because an element + * has no closing '>'. + */ String xmlStr = "\n"+ "\n"+ " \n"+ " \n"+ + " \n"+ + ""; + JSONML.toJSONArray(xmlStr); + } + + @Test(expected=JSONException.class) + public void noCloseEndTagException() { + /** + * xmlStr contains XML text which is transformed into a JSONArray. + * In this case, the XML is invalid because an element + * has no name after the closing tag '\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + " \n"+ + ""; + JSONML.toJSONArray(xmlStr); + } + + @Test(expected=JSONException.class) + public void noCloseEndBraceException() { + /** + * xmlStr contains XML text which is transformed into a JSONArray. + * In this case, the XML is invalid because an element + * has '>' after the closing tag '\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + " "; JSONML.toJSONArray(xmlStr); } @Test(expected=JSONException.class) public void invalidCDATABangInTagException() { + /** + * xmlStr contains XML text which is transformed into a JSONArray. + * In this case, the XML is invalid because an element + * does not have a complete CDATA string. + */ String xmlStr = "\n"+ "\n"+ "\n"+ - "
\n"+ - "\n"+ + "
\n"+ + "myName\n"+ ">\n"+ "
\n"+ ""; @@ -160,7 +276,8 @@ public class JSONMLTest { "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ "[\"address\","+ - "[\"name\"],"+ + "{\"attr1\":\"attrValue1\",\"attr2\":\"attrValue2\",\"attr3\":\"attrValue3\"},"+ + "[\"name\", {\"nameType\":\"mine\"},\"myName\"],"+ "[\"nocontent\"],"+ "\">\""+ "]"+ @@ -174,15 +291,34 @@ public class JSONMLTest { } @Test - public void basicXMLAsObject() { + public void toJSONObjectToJSONArray() { + /** + * xmlStr contains XML text which is transformed into a JSONObject, + * restored to XML, transformed into a JSONArray, and then restored + * to XML again. Both JSONObject and JSONArray should contain the same + * information and should produce the same XML, allowing for non-ordered + * attributes. + * + * Transformation to JSONObject: + * The elementName is stored as a string where key="tagName" + * Attributes are simply stored as key/value pairs + * If the element has either content or child elements, they are stored + * in a jsonArray with key="childNodes". + * + * Transformation to JSONArray: + * 1st entry = elementname + * 2nd entry = attributes object (if present) + * 3rd entry = content (if present) + * 4th entry = child element JSONArrays (if present) + */ String xmlStr = "\n"+ "\n"+ - "
\n"+ - "Joe Tester\n"+ - "[CDATA[Baker street 5]\n"+ - "\n"+ + "
\n"+ + "Joe Tester\n"+ + "\n"+ + "\n"+ "true\n"+ "false\n"+ "null\n"+ @@ -193,6 +329,7 @@ public class JSONMLTest { "\n"+ "1\n"+ "2\n"+ + "abc\n"+ "3\n"+ "4.1\n"+ "5.2\n"+ @@ -200,90 +337,121 @@ public class JSONMLTest { "
\n"+ ""; - String expectedStr = - "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ + String expectedJSONObjectStr = + "{"+ + "\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ "\"childNodes\":["+ - "{\"childNodes\":["+ - "{\"childNodes\":[\"Joe Tester\"],"+ - "\"tagName\":\"name\"},"+ - "{\"childNodes\":[\"[CDATA[Baker street 5]\"],"+ - "\"tagName\":\"street\"},"+ - "{\"tagName\":\"NothingHere\"},"+ - "{\"childNodes\":[true],"+ - "\"tagName\":\"TrueValue\"},"+ - "{\"childNodes\":[false],"+ - "\"tagName\":\"FalseValue\"},"+ - "{\"childNodes\":[null],"+ - "\"tagName\":\"NullValue\"},"+ - "{\"childNodes\":[42],"+ - "\"tagName\":\"PositiveValue\"},"+ - "{\"childNodes\":[-23],"+ - "\"tagName\":\"NegativeValue\"},"+ - "{\"childNodes\":[-23.45],"+ - "\"tagName\":\"DoubleValue\"},"+ - "{\"childNodes\":[\"-23x.45\"],"+ - "\"tagName\":\"Nan\"},"+ - "{\"childNodes\":["+ - "{\"childNodes\":[1],"+ - "\"tagName\":\"value\"},"+ - "{\"childNodes\":[2],"+ - "\"tagName\":\"value\"},"+ - "{\"childNodes\":[3],"+ - "\"tagName\":\"value\"},"+ - "{\"childNodes\":[4.1],"+ - "\"tagName\":\"value\"},"+ - "{\"childNodes\":[5.2],"+ - "\"tagName\":\"value\"}"+ - "],"+ - "\"tagName\":\"ArrayOfNum\"}"+ - "],"+ - "\"tagName\":\"address\"}"+ + "{"+ + "\"childNodes\":["+ + "{"+ + "\"childNodes\":[\"Joe Tester\"],"+ + "\"nameType\":\"my name\","+ + "\"tagName\":\"name\""+ + "},"+ + "{"+ + "\"childNodes\":[\"Baker street 5\"],"+ + "\"tagName\":\"street\""+ + "},"+ + "{"+ + "\"tagName\":\"NothingHere\","+ + "\"except\":\"an attribute\""+ + "},"+ + "{"+ + "\"childNodes\":[true],"+ + "\"tagName\":\"TrueValue\""+ + "},"+ + "{"+ + "\"childNodes\":[false],"+ + "\"tagName\":\"FalseValue\""+ + "},"+ + "{"+ + "\"childNodes\":[null],"+ + "\"tagName\":\"NullValue\""+ + "},"+ + "{"+ + "\"childNodes\":[42],"+ + "\"tagName\":\"PositiveValue\""+ + "},"+ + "{"+ + "\"childNodes\":[-23],"+ + "\"tagName\":\"NegativeValue\""+ + "},"+ + "{"+ + "\"childNodes\":[-23.45],"+ + "\"tagName\":\"DoubleValue\""+ + "},"+ + "{"+ + "\"childNodes\":[\"-23x.45\"],"+ + "\"tagName\":\"Nan\""+ + "},"+ + "{"+ + "\"childNodes\":["+ + "{"+ + "\"childNodes\":[1],"+ + "\"tagName\":\"value\""+ + "},"+ + "{"+ + "\"childNodes\":[2],"+ + "\"tagName\":\"value\""+ + "},"+ + "{"+ + "\"childNodes\":["+ + "{"+ + "\"childNodes\":[\"abc\"],"+ + "\"svAttr\":\"svValue\","+ + "\"tagName\":\"subValue\""+ + "}"+ + "],"+ + "\"tagName\":\"value\""+ + "},"+ + "{"+ + "\"childNodes\":[3],"+ + "\"tagName\":\"value\""+ + "},"+ + "{"+ + "\"childNodes\":[4.1],"+ + "\"tagName\":\"value\""+ + "},"+ + "{"+ + "\"childNodes\":[5.2],"+ + "\"tagName\":\"value\""+ + "}"+ + "],"+ + "\"tagName\":\"ArrayOfNum\""+ + "}"+ + "],"+ + "\"addrType\":\"my address\","+ + "\"tagName\":\"address\""+ + "}"+ "],"+ "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\","+ - "\"tagName\":\"addresses\"}"; - JSONObject jsonObject = JSONML.toJSONObject(xmlStr); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - String xmlToStr = JSONML.toString(jsonObject); - JSONObject finalJsonObject = JSONML.toJSONObject(xmlToStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); - Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedJsonObject); - } + "\"tagName\":\"addresses\""+ + "}"; - @Test - public void basicXMLAsArray() { - String xmlStr = - "\n"+ - "\n"+ - "
\n"+ - "Joe Tester\n"+ - "[CDATA[Baker street 5]\n"+ - "\n"+ - "true\n"+ - "false\n"+ - "null\n"+ - "42\n"+ - "-23\n"+ - "-23.45\n"+ - "-23x.45\n"+ - "\n"+ - "1\n"+ - "2\n"+ - "3\n"+ - "4.1\n"+ - "5.2\n"+ - "\n"+ - "
\n"+ - "
"; - - String expectedStr = - "[\"addresses\","+ - "{\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ - "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"},"+ - "[\"address\","+ - "[\"name\",\"Joe Tester\"],"+ - "[\"street\",\"[CDATA[Baker street 5]\"],"+ - "[\"NothingHere\"],"+ + String expectedJSONArrayStr = + "["+ + "\"addresses\","+ + "{"+ + "\"xsi:noNamespaceSchemaLocation\":\"test.xsd\","+ + "\"xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\""+ + "},"+ + "["+ + "\"address\","+ + "{"+ + "\"addrType\":\"my address\""+ + "},"+ + "["+ + "\"name\","+ + "{"+ + "\"nameType\":\"my name\""+ + "},"+ + "\"Joe Tester\""+ + "],"+ + "[\"street\",\"Baker street 5\"],"+ + "["+ + "\"NothingHere\","+ + "{\"except\":\"an attribute\"}"+ + "],"+ "[\"TrueValue\",true],"+ "[\"FalseValue\",false],"+ "[\"NullValue\",null],"+ @@ -291,25 +459,53 @@ public class JSONMLTest { "[\"NegativeValue\",-23],"+ "[\"DoubleValue\",-23.45],"+ "[\"Nan\",\"-23x.45\"],"+ - "[\"ArrayOfNum\","+ + "["+ + "\"ArrayOfNum\","+ "[\"value\",1],"+ "[\"value\",2],"+ + "[\"value\","+ + "["+ + "\"subValue\","+ + "{\"svAttr\":\"svValue\"},"+ + "\"abc\""+ + "],"+ + "],"+ "[\"value\",3],"+ "[\"value\",4.1],"+ "[\"value\",5.2]"+ "]"+ "]"+ "]"; + + // make a JSONObject and make sure it looks as expected + JSONObject jsonObject = JSONML.toJSONObject(xmlStr); + JSONObject expectedJsonObject = new JSONObject(expectedJSONObjectStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + + // restore the XML, then make another JSONObject and make sure it + // looks as expected + String jsonObjectXmlToStr = JSONML.toString(jsonObject); + JSONObject finalJsonObject = JSONML.toJSONObject(jsonObjectXmlToStr); + Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedJsonObject); + + // create a JSON array from the original string and make sure it + // looks as expected JSONArray jsonArray = JSONML.toJSONArray(xmlStr); - JSONArray expectedJsonArray = new JSONArray(expectedStr); - String xmlToStr = JSONML.toString(jsonArray); - JSONArray finalJsonArray = JSONML.toJSONArray(xmlToStr); - Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); - // TODO: this test fails because JSONML.toString() does not emit values - // for true, false, null, and numbers - // Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); + JSONArray expectedJsonArray = new JSONArray(expectedJSONArrayStr); + Util.compareActualVsExpectedJsonArrays(jsonArray,expectedJsonArray); + + // restore the XML, then make another JSONArray and make sure it + // looks as expected + String jsonArrayXmlToStr = JSONML.toString(jsonArray); + JSONArray finalJsonArray = JSONML.toJSONArray(jsonArrayXmlToStr); + Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); + + // lastly, confirm the restored JSONObject XML and JSONArray XML look + // reasonably similar + Util.compareXML(jsonObjectXmlToStr, jsonArrayXmlToStr); } + @Test public void commentsInXML() { From 5acbee2719293d6ae3bd75bbb8f53d6f2180ee68 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 23 Apr 2015 21:41:46 -0500 Subject: [PATCH 088/451] 98% coverage --- CDLTest.java | 163 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 107 insertions(+), 56 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index 53284d0..d218b10 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -12,11 +12,7 @@ import org.json.CDL; * Tests for CDL.java. * CDL provides an application level API, but it is not used by the * reference app. To test it, strings will be converted to JSON-Java classes - * and then converted back. Since each row is an unordered JSONObject, - * can't use a simple string compare to check for equality. - * @author JSON.org - * @version 2015-03-22 - * + * and then converted back. */ public class CDLTest { @@ -25,40 +21,90 @@ public class CDLTest { * and all subsequent rows are values. All keys and values should be legal. */ String lines = new String( - "Col 1, Col 2, Col 3, Col 4, Col 5, Col 6, Col 7\n" + + "Col 1, Col 2, \tCol 3, Col 4, Col 5, Col 6, Col 7\n" + "val1, val2, val3, val4, val5, val6, val7\n" + - "1, 2, 3, 4, 5, 6, 7\n" + + "1, 2, 3, 4\t, 5, 6, 7\n" + "true, false, true, true, false, false, false\n" + "0.23, 57.42, 5e27, -234.879, 2.34e5, 0.0, 9e-3\n" + "\"va\tl1\", \"v\bal2\", \"val3\", \"val\f4\", \"val5\", va\'l6, val7\n" ); /** - * Something I did not expect is that CDL.toJSONArray() adds all values as - * strings, with no filtering or conversions. I suppose this makes it - * easier to emit it as CDL later. For testing, it means that the - * expected JSONObject values all must be quoted in the cases where the - * JSONObject parsing might normally convert the value into a non-string. + * CDL.toJSONArray() adds all values asstrings, with no filtering or + * conversions. For testing, this means that the expected JSONObject + * values all must be quoted in the cases where the JSONObject parsing + * might normally convert the value into a non-string. */ String expectedLines = new String( "[{Col 1:val1, Col 2:val2, Col 3:val3, Col 4:val4, Col 5:val5, Col 6:val6, Col 7:val7}, "+ - "{Col 1:1, Col 2:2, Col 3:3, Col 4:4, Col 5:5, Col 6:6, Col 7:7}, "+ - "{Col 1:true, Col 2:false, Col 3:true, Col 4:true, Col 5:false, Col 6:false, Col 7:false}, "+ + "{Col 1:\"1\", Col 2:\"2\", Col 3:\"3\", Col 4:\"4\", Col 5:\"5\", Col 6:\"6\", Col 7:\"7\"}, "+ + "{Col 1:\"true\", Col 2:\"false\", Col 3:\"true\", Col 4:\"true\", Col 5:\"false\", Col 6:\"false\", Col 7:\"false\"}, "+ "{Col 1:\"0.23\", Col 2:\"57.42\", Col 3:\"5e27\", Col 4:\"-234.879\", Col 5:\"2.34e5\", Col 6:\"0.0\", Col 7:\"9e-3\"}, "+ "{Col 1:\"va\tl1\", Col 2:\"v\bal2\", Col 3:val3, Col 4:\"val\f4\", Col 5:val5, Col 6:va\'l6, Col 7:val7}]"); @Test(expected=NullPointerException.class) - public void shouldThrowExceptionOnNullString() { + public void exceptionOnNullString() { + /** + * Attempts to create a JSONArray from a null string + */ String nullStr = null; CDL.toJSONArray(nullStr); } + @Test(expected=JSONException.class) + public void unbalancedQuoteInName() { + /** + * Attempts to create a JSONArray from a string with unbalanced quotes + * in column title line + */ + String badLine = "Col1, \"Col2\nVal1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test(expected=JSONException.class) + public void unbalancedQuoteInValue() { + /** + * Attempts to create a JSONArray from a string with unbalanced quotes + * in value line + */ + String badLine = "Col1, Col2\n\"Val1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test(expected=JSONException.class) + public void nullInName() { + /** + * Attempts to create a JSONArray from a string with null char + * in column title line + */ + String badLine = "C\0ol1, Col2\nVal1, Val2"; + CDL.toJSONArray(badLine); + } + + @Test(expected=NullPointerException.class) + public void nullJSONArrayToString() { + /** + * call toString with a null array + */ + CDL.toString((JSONArray)null); + } + @Test - /** - * Note: This test reveals a bug in the method JavaDoc. It should - * mention it might return null, or it should return an empty JSONArray. - */ - public void shouldHandleOnlyColumnNames() { + public void emptyString() { + /** + * Create a JSONArray from an empty string + */ + String emptyStr = ""; + JSONArray jsonArray = CDL.toJSONArray(emptyStr); + assertTrue("CDL should return null when the input string is empty", + jsonArray == null); + } + + @Test + public void onlyColumnNames() { + /** + * Create a JSONArray with only 1 row + */ String columnNameStr = "col1, col2, col3"; JSONArray jsonArray = CDL.toJSONArray(columnNameStr); assertTrue("CDL should return null when only 1 row is given", @@ -66,38 +112,39 @@ public class CDLTest { } @Test - /** - * Note: This test reveals a bug in the method JavaDoc. It should - * mention it might return null, or it should return an empty JSONArray. - */ - public void shouldHandleEmptyString() { - String emptyStr = ""; - JSONArray jsonArray = CDL.toJSONArray(emptyStr); - assertTrue("CDL should return null when the input string is empty", + public void emptyLinesToJSONArray() { + /** + * Create a JSONArray from string containing only whitespace and commas + */ + String str = " , , , \n , , , "; + JSONArray jsonArray = CDL.toJSONArray(str); + assertTrue("JSONArray should be null for no content", jsonArray == null); } - @Test(expected=JSONException.class) - public void shouldHandleUnbalancedQuoteInName() { - String badLine = "Col1, \"Col2\nVal1, Val2"; - CDL.toJSONArray(badLine); - } - - @Test(expected=JSONException.class) - public void shouldHandleUnbalancedQuoteInValue() { - String badLine = "Col1, Col2\n\"Val1, Val2"; - CDL.toJSONArray(badLine); - } - - @Test(expected=JSONException.class) - public void shouldHandleNullInName() { - String badLine = "C\0ol1, Col2\nVal1, Val2"; - CDL.toJSONArray(badLine); - } - - @Test - public void toStringShouldCheckSpecialChars() { + public void emptyJSONArrayToString() { + /** + * call toString with a null array + */ + JSONArray jsonArray = new JSONArray(); + String str = CDL.toString(jsonArray); + assertTrue("CDL should return null for toString(null)", + str == null); + } + + @Test + public void nullJSONArraysToString() { + /** + * call toString with a null arrays for names and values + */ + String str = CDL.toString(null, null); + assertTrue("CDL should return null for toString(null)", + str == null); + } + + @Test + public void checkSpecialChars() { /** * Given a JSONArray that was not built by CDL, some chars may be * found that would otherwise be filtered out by CDL. @@ -119,16 +166,21 @@ public class CDLTest { } @Test - public void shouldConvertCDLToJSONArray() { - // this array is built by CDL + public void textToJSONArray() { + /** + * Create a JSONArray from a string of lines + */ JSONArray jsonArray = CDL.toJSONArray(lines); - // This array is built from JSON parsing JSONArray expectedJsonArray = new JSONArray(expectedLines); Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } @Test - public void shouldCreateJSONArrayUsingJSONArray() { + public void jsonArrayToJSONArray() { + /** + * Create a JSONArray from a JSONArray of titles and a + * string of value lines + */ String nameArrayStr = "[Col1, Col2]"; String values = "V1, V2"; JSONArray nameJSONArray = new JSONArray(nameArrayStr); @@ -138,11 +190,10 @@ public class CDLTest { } @Test - public void shouldConvertCDLToJSONArrayAndBackToString() { + public void textToJSONArrayAndBackToString() { /** - * This is the first test of normal functionality. - * The string contains a typical variety of values - * that might be found in a real CDL. + * Create a JSONArray from a string of lines, + * then convert to string and then back to JSONArray */ JSONArray jsonArray = CDL.toJSONArray(lines); String jsonStr = CDL.toString(jsonArray); From 30c86811c037ffa9adec44ed6015d442752348c8 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 23 Apr 2015 21:42:04 -0500 Subject: [PATCH 089/451] improved object comparison --- Util.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Util.java b/Util.java index 71f6c0d..635b7a6 100644 --- a/Util.java +++ b/Util.java @@ -64,6 +64,20 @@ public class Util { compareActualVsExpectedJsonArrays( jsonArray, expectedJsonArray); } else { + /** + * Certain helper classes (e.g. XML) may create Long instead of + * Integer for small int values. As long as both are Numbers, + * just compare the toString() values. + */ + if (!(value instanceof Number && expectedValue instanceof Number)) { + assertTrue("object types should be equal for actual: "+ + value.toString()+" ("+ + value.getClass().toString()+") expected: "+ + expectedValue.toString()+" ("+ + expectedValue.getClass().toString()+")", + value.getClass().toString().equals( + expectedValue.getClass().toString())); + } assertTrue("string values should be equal for actual: "+ value.toString()+" expected: "+expectedValue.toString(), value.toString().equals(expectedValue.toString())); @@ -83,4 +97,13 @@ public class Util { } } + public static void compareXML(String aXmlStr, String bXmlStr) { + // TODO For simple tests this may be adequate, but it won't work for + // elements with multiple attributes and possibly other cases as well. + // Should use XMLUnit or similar. + assertTrue("expected equal XML strings \naXmlStr: "+ + aXmlStr+ "\nbXmlStr: " +bXmlStr, aXmlStr.equals(bXmlStr)); + + } + } From 890fd4a39726bebb16d8d6f17a65b58c275f7b70 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Thu, 23 Apr 2015 21:46:13 -0500 Subject: [PATCH 090/451] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bd17a5f..76ac4c2 100644 --- a/README.md +++ b/README.md @@ -28,9 +28,9 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 88.7% | | | +| Total coverage | 88.6% | | | | | | | -| CDLTest.java | 94.8% | Completed | +| CDLTest.java | 98% | Completed | | CookieTest.java | 97.5% | Completed | | CookieListTest.java |96.5% | Completed | | HTTPTest.java | 98.7%| Completed | From 9bca907208631de2e13d009a82aa6126d02d2e7a Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 23 Apr 2015 21:47:15 -0500 Subject: [PATCH 091/451] added JSONArrayTest --- JunitTestSuite.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/JunitTestSuite.java b/JunitTestSuite.java index 63bde2f..a91426d 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -12,7 +12,8 @@ import org.junit.runners.Suite; JSONMLTest.class, HTTPTest.class, JSONStringerTest.class, - JSONObjectTest.class + JSONObjectTest.class, + JSONArrayTest.class }) public class JunitTestSuite { } \ No newline at end of file From 15b5306f48104874639965cd9bf7d93dc2719965 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Thu, 23 Apr 2015 22:01:33 -0500 Subject: [PATCH 092/451] Update README.md --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 76ac4c2..43bbfb1 100644 --- a/README.md +++ b/README.md @@ -30,22 +30,22 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | ------------- | ------------- | ---- | | Total coverage | 88.6% | | | | | | | -| CDLTest.java | 98% | Completed | -| CookieTest.java | 97.5% | Completed | -| CookieListTest.java |96.5% | Completed | -| HTTPTest.java | 98.7%| Completed | -| HTTPTokene.java |93.2% |(no test file) | -| JSONArrayTest.java |95.9% | Completed | +| CDLTest.java | 98% | basic coverage completed. Reasonable testing completed. | +| CookieTest.java | 97.5% | basic coverage completed | +| CookieListTest.java |96.5% | basic coverage completed | +| HTTPTest.java | 98.7%| basic coverage completed | +| HTTPTokener.java |93.2% |(no test file) | +| JSONArrayTest.java |95.9% | basic coverage completed | | JSONException.java | 26.7% | (no test file) | -| JSONMLTest.java | 83.2%| Completed | -| JSONObjectTest | 90.9% | Completed | +| JSONMLTest.java | 83.2%| working on basic coverage | +| JSONObjectTest | 90.9% | basic coverage completed | | JSONObject.Null | 87.5% | (no test file) | | JSONString.java | | (no lines to test) | -| JSONStringerTest.java | 93.8%| Completed | +| JSONStringerTest.java | 93.8%| basic coverage completed | | JSONTokenerTest.java | 72.1% | In progress | | JSONWriter.java | 88.9% | (no test file) | -| PropertyTest.java | 94.8% | Completed | -| XMLTest.java | 85.1% | Completed | +| PropertyTest.java | 94.8% | basic coverage completed | +| XMLTest.java | 85.1% | working on basic coverage | | XMLTokener.java| 82.7%| (no test file) | | Files used in test | @@ -53,7 +53,7 @@ A unit test is considered complete when the coverage is >= 90% as measured by Ec | JunitTestSuite.java | | MyBean.java | | StringsResourceBundle.java | -|TestRUnner.java | +|TestRunner.java | | Util.java | From 102d273be3d5a9b53974eccd0d0f5b68b6a18844 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 24 Apr 2015 00:25:53 -0500 Subject: [PATCH 093/451] Update README.md --- README.md | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 43bbfb1..2fde1d2 100644 --- a/README.md +++ b/README.md @@ -24,29 +24,34 @@ The fundamental issues with JSON-Java testing are: When you start working on a test, add the empty file to the repository and update the readme, so that others will know that test is taken. -A unit test is considered complete when the coverage is >= 90% as measured by EclEmma. +A unit test has the following stages: +|No test| +|In progress| +|Coverage > 90%| +|Reasonable test cases| +|Checked against previous unit tests| | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | | Total coverage | 88.6% | | | | | | | -| CDLTest.java | 98% | basic coverage completed. Reasonable testing completed. | -| CookieTest.java | 97.5% | basic coverage completed | -| CookieListTest.java |96.5% | basic coverage completed | -| HTTPTest.java | 98.7%| basic coverage completed | -| HTTPTokener.java |93.2% |(no test file) | -| JSONArrayTest.java |95.9% | basic coverage completed | -| JSONException.java | 26.7% | (no test file) | -| JSONMLTest.java | 83.2%| working on basic coverage | -| JSONObjectTest | 90.9% | basic coverage completed | -| JSONObject.Null | 87.5% | (no test file) | -| JSONString.java | | (no lines to test) | -| JSONStringerTest.java | 93.8%| basic coverage completed | +| CDLTest.java | 98% | Reasonable test cases. | +| CookieTest.java | 97.5% | Coverage > 90% | +| CookieListTest.java |96.5% | Coverage > 90% | +| HTTPTest.java | 98.7%| Coverage > 90% | +| HTTPTokener.java |93.2% | No test | +| JSONArrayTest.java |95.9% | Coverage > 90% | +| JSONException.java | 26.7% | No test | +| JSONMLTest.java | 83.2%| In progress | +| JSONObjectTest | 90.9% | Coverage > 90% | +| JSONObject.Null | 87.5% | No test | +| JSONString.java | | No test | +| JSONStringerTest.java | 93.8%| Coverage > 90% | | JSONTokenerTest.java | 72.1% | In progress | -| JSONWriter.java | 88.9% | (no test file) | -| PropertyTest.java | 94.8% | basic coverage completed | -| XMLTest.java | 85.1% | working on basic coverage | -| XMLTokener.java| 82.7%| (no test file) | +| JSONWriter.java | 88.9% | No test | +| PropertyTest.java | 94.8% | Coverage > 90% | +| XMLTest.java | 85.1% | In progress | +| XMLTokener.java| 82.7%| No test | | Files used in test | | ------------- | From 3112e320895c1c2da2fbd75b2a2484bf89aa593d Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 24 Apr 2015 00:26:26 -0500 Subject: [PATCH 094/451] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2fde1d2..9b934ac 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ The fundamental issues with JSON-Java testing are: When you start working on a test, add the empty file to the repository and update the readme, so that others will know that test is taken. A unit test has the following stages: + |No test| |In progress| |Coverage > 90%| From 571b1a79bb8c0f69b78bac591a01ac2c2b347654 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 24 Apr 2015 00:27:34 -0500 Subject: [PATCH 095/451] Update README.md --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 9b934ac..2c01eb3 100644 --- a/README.md +++ b/README.md @@ -26,11 +26,13 @@ When you start working on a test, add the empty file to the repository and updat A unit test has the following stages: -|No test| -|In progress| -|Coverage > 90%| -|Reasonable test cases| -|Checked against previous unit tests| +| Test phase | +|----| +| No test | +| In progress | +| Coverage > 90% | +| Reasonable test cases | +| Checked against previous unit tests | | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | From d2e19cc78ccfa657ba60c857956685fe4f8348c6 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 24 Apr 2015 16:40:42 -0500 Subject: [PATCH 096/451] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2c01eb3..b22295e 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,8 @@ A unit test has the following stages: | Coverage > 90% | | Reasonable test cases | | Checked against previous unit tests | +| Completed | + | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | From da2e548f56087cb29a4d86777ab2dfb71a257b6a Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 26 Apr 2015 17:46:52 -0500 Subject: [PATCH 097/451] 98.9% coverage --- CookieTest.java | 165 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 120 insertions(+), 45 deletions(-) diff --git a/CookieTest.java b/CookieTest.java index d5bc239..c96bd72 100644 --- a/CookieTest.java +++ b/CookieTest.java @@ -1,6 +1,6 @@ package org.json.junit; -import java.util.*; + import static org.junit.Assert.*; @@ -9,29 +9,52 @@ import org.junit.Test; /** - * Tests for JSON-Java Cookie.java - * See RFC6265 - * At its most basic, a cookie is a name=value pair. + * HTTP cookie specification: RFC6265 + * + * At its most basic, a cookie is a name=value pair. The value may be subdivided + * into other cookies, but that is not tested here. The cookie may also include + * certain named attributes, delimited by semicolons. + * + * The Cookie.toString() method emits certain attributes if present: expires, + * domain, path, secure. All but secure are name-value pairs. Other attributes + * are not included in the toString() output. + * * A JSON-Java encoded cookie escapes '+', '%', '=', ';' with %hh values. */ public class CookieTest { @Test(expected=NullPointerException.class) public void nullCookieException() { + /** + * Attempts to create a JSONObject from a null string + */ String cookieStr = null; Cookie.toJSONObject(cookieStr); } @Test(expected=JSONException.class) - public void malFormedCookieException() { + public void malFormedNameValueException() { + /** + * Attempts to create a JSONObject from a malformed cookie string + */ String cookieStr = "thisCookieHasNoEqualsChar"; Cookie.toJSONObject(cookieStr); } + @Test(expected=JSONException.class) + public void malFormedAttributeException() { + /** + * Attempts to create a JSONObject from a malformed cookie string + */ + String cookieStr = "this=Cookie;myAttribute"; + Cookie.toJSONObject(cookieStr); + } + @Test(expected=JSONException.class) public void emptyStringCookieException() { /** - * Cookie throws an exception, but CookieList does not + * Attempts to create a JSONObject from an empty cookie string + * Note: Cookie throws an exception, but CookieList does not */ String cookieStr = ""; Cookie.toJSONObject(cookieStr); @@ -39,6 +62,9 @@ public class CookieTest { @Test public void simpleCookie() { + /** + * The simplest cookie is a name/value pair with no delimiter + */ String cookieStr = "SID=31d4d96e407aad42"; String expectedCookieStr = "{\"name\":\"SID\",\"value\":\"31d4d96e407aad42\"}"; JSONObject jsonObject = Cookie.toJSONObject(cookieStr); @@ -48,12 +74,45 @@ public class CookieTest { @Test public void multiPartCookie() { + /** + * Store a cookie with all of the supported attributes in a + * JSONObject. The secure attribute, which has no value, is treated + * as a boolean. + */ String cookieStr = "PH=deleted; "+ " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ "path=/; "+ " domain=.yahoo.com;"+ "secure"; + String expectedCookieStr = + "{"+ + "\"name\":\"PH\","+ + "\"value\":\"deleted\","+ + "\"path\":\"/\","+ + "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ + "\"domain\":\".yahoo.com\","+ + "\"secure\":true"+ + "}"; + JSONObject jsonObject = Cookie.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void convertCookieToString() { + /** + * ToString() will omit the non-standard "thiswont=beIncluded" + * attribute, but the attribute is still stored in the JSONObject. + * This test confirms both behaviors. + */ + String cookieStr = + "PH=deleted; "+ + " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ + "path=/; "+ + " domain=.yahoo.com;"+ + "thisWont=beIncluded;"+ + "secure"; String expectedCookieStr = "{\"path\":\"/\","+ "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ @@ -61,58 +120,45 @@ public class CookieTest { "\"name\":\"PH\","+ "\"secure\":true,"+ "\"value\":\"deleted\"}"; - JSONObject jsonObject = Cookie.toJSONObject(cookieStr); - JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); - } - - @Test - public void convertCookieToString() { - String cookieStr = - "PH=deleted; "+ - " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ - "path=/; "+ - " domain=.yahoo.com;"+ - "thisWont=beIncluded;"+ - "secure"; - String expectedCookieStr = - "{\"path\":\"/\","+ - "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ - "\"domain\":\".yahoo.com\","+ - "\"name\":\"PH\","+ - "\"secure\":true,"+ - "\"value\":\"deleted\"}"; - /** - * ToString() will omit the non-standard segment, - * but it will still be stored in the JSONObject - */ - String expectedDirectCompareCookieStr = - expectedCookieStr.replaceAll("\\{", "\\{\"thisWont\":\"beIncluded\","); + // Add the nonstandard attribute to the expected cookie string + String expectedDirectCompareCookieStr = + expectedCookieStr.replaceAll("\\{", "\\{\"thisWont\":\"beIncluded\","); + // convert all strings into JSONObjects JSONObject jsonObject = Cookie.toJSONObject(cookieStr); JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); JSONObject expectedDirectCompareJsonObject = new JSONObject(expectedDirectCompareCookieStr); + // emit the string String cookieToStr = Cookie.toString(jsonObject); + // create a final JSONObject from the string JSONObject finalJsonObject = Cookie.toJSONObject(cookieToStr); + // JSONObject should contain the nonstandard string Util.compareActualVsExpectedJsonObjects(jsonObject,expectedDirectCompareJsonObject); + // JSONObject -> string -> JSONObject should not contain the nonstandard string Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } @Test public void convertEncodedCookieToString() { + /** + * A string may be URL-encoded when converting to JSONObject. + * If found, '+' is converted to ' ', and %hh hex strings are converted + * to their ascii char equivalents. This test confirms the decoding + * behavior. + */ String cookieStr = - "PH=deleted; "+ - " expires=Wed,+19-Mar-2014+17:53:53+GMT;"+ - "path=/%2Bthis/is%26/a/spec%3Bsegment%3D; "+ - " domain=.yahoo.com;"+ - "secure"; - String expectedCookieStr = - "{\"path\":\"/+this/is&/a/spec;segment=\","+ - "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ - "\"domain\":\".yahoo.com\","+ - "\"name\":\"PH\","+ - "\"secure\":true,"+ - "\"value\":\"deleted\"}"; + "PH=deleted; "+ + " expires=Wed,+19-Mar-2014+17:53:53+GMT;"+ + "path=/%2Bthis/is%26/a/spec%3Bsegment%3D; "+ + " domain=.yahoo.com;"+ + "secure"; + String expectedCookieStr = + "{\"path\":\"/+this/is&/a/spec;segment=\","+ + "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ + "\"domain\":\".yahoo.com\","+ + "\"name\":\"PH\","+ + "\"secure\":true,"+ + "\"value\":\"deleted\"}"; JSONObject jsonObject = Cookie.toJSONObject(cookieStr); JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); String cookieToStr = Cookie.toString(jsonObject); @@ -121,4 +167,33 @@ public class CookieTest { Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } + @Test + public void escapeString() { + /** + * A public API method performs a URL encoding for selected chars + * in a string. Control chars, '+', '%', '=', ';' are all encoded + * as %hh hex strings. The string is also trimmed. + * This test confirms that behavior. + */ + String str = " +%\r\n\t\b%=;;; "; + String expectedStr = "%2b%25%0d%0a%09%08%25%3d%3b%3b%3b"; + String actualStr = Cookie.escape(str); + assertTrue("expect escape() to encode correctly. Actual: " +actualStr+ + " expected: " +expectedStr, expectedStr.equals(actualStr)); + } + + @Test + public void unescapeString() { + /** + * A public API method performs URL decoding for strings. + * '+' is converted to space and %hh hex strings are converted to + * their ascii equivalent values. The string is not trimmed. + * This test confirms that behavior. + */ + String str = " +%2b%25%0d%0a%09%08%25%3d%3b%3b%3b+ "; + String expectedStr = " +%\r\n\t\b%=;;; "; + String actualStr = Cookie.unescape(str); + assertTrue("expect unescape() to decode correctly. Actual: " +actualStr+ + " expected: " +expectedStr, expectedStr.equals(actualStr)); + } } From ee06176ab2be22d2e09228d0a6ba5e534f7e726b Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sun, 26 Apr 2015 17:49:04 -0500 Subject: [PATCH 098/451] Update README.md --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index b22295e..73c3259 100644 --- a/README.md +++ b/README.md @@ -40,22 +40,22 @@ A unit test has the following stages: | ------------- | ------------- | ---- | | Total coverage | 88.6% | | | | | | | -| CDLTest.java | 98% | Reasonable test cases. | -| CookieTest.java | 97.5% | Coverage > 90% | -| CookieListTest.java |96.5% | Coverage > 90% | -| HTTPTest.java | 98.7%| Coverage > 90% | +| CDL.java | 98% | Reasonable test cases. | +| Cookie.java | 98.9% | Reasonable test cases. | +| CookieList.java |96.5% | Coverage > 90% | +| HTTP.java | 98.7%| Coverage > 90% | | HTTPTokener.java |93.2% | No test | -| JSONArrayTest.java |95.9% | Coverage > 90% | +| JSONArray.java |95.9% | Coverage > 90% | | JSONException.java | 26.7% | No test | -| JSONMLTest.java | 83.2%| In progress | -| JSONObjectTest | 90.9% | Coverage > 90% | +| JSONML.java | 83.2%| In progress | +| JSONObject | 90.9% | Coverage > 90% | | JSONObject.Null | 87.5% | No test | | JSONString.java | | No test | -| JSONStringerTest.java | 93.8%| Coverage > 90% | -| JSONTokenerTest.java | 72.1% | In progress | +| JSONStringer.java | 93.8%| Coverage > 90% | +| JSONTokener.java | 72.1% | In progress | | JSONWriter.java | 88.9% | No test | -| PropertyTest.java | 94.8% | Coverage > 90% | -| XMLTest.java | 85.1% | In progress | +| Property.java | 94.8% | Coverage > 90% | +| XML.java | 85.1% | In progress | | XMLTokener.java| 82.7%| No test | | Files used in test | From f115d6a3b8b797091584171ecab6eafaf3eeaf1c Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sun, 26 Apr 2015 17:53:39 -0500 Subject: [PATCH 099/451] Update README.md --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 73c3259..49d912a 100644 --- a/README.md +++ b/README.md @@ -26,14 +26,14 @@ When you start working on a test, add the empty file to the repository and updat A unit test has the following stages: -| Test phase | -|----| -| No test | -| In progress | -| Coverage > 90% | -| Reasonable test cases | -| Checked against previous unit tests | -| Completed | +| Test phase |Description | +|----|----| +| No test | No test specifically for this class has been written, or the class contains no executable code. | +| In progress | Unit tests have been started for this class. | +| Coverage > 90% | Initial goal of 90% coverage has been reached. Test quality may be questionable | +| Reasonable test cases | 90% coverage. Functionality and behavior has been confirmed | +| Checked against previous unit tests | Historical unit tests have been checked in case something important was missed | +| Completed | The unit test is completed | | Test file name | Coverage | Comments | From 65ae3e663fcf9c2d7d93b492594f2eef0ab89f6b Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 27 Apr 2015 10:04:41 -0500 Subject: [PATCH 100/451] Improving test case quality --- CookieListTest.java | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/CookieListTest.java b/CookieListTest.java index d8b4a5b..9edc9ad 100644 --- a/CookieListTest.java +++ b/CookieListTest.java @@ -7,23 +7,37 @@ import static org.junit.Assert.*; import org.json.*; import org.junit.Test; - /** - * Tests for JSON-Java CookieList.java - * The main differences between Cookie and CookieList appears to be that - * CookieList does not treat the initial name/value pair different than - * the other segments, and does not handle "secure". - * Therefore the tests will be similar, but not identical. + * HTTP cookie specification: RFC6265 + * + * A cookie list is a JSONObject whose members are cookie name/value pairs. + * Entries are unescaped while being added, and escaped in the toString() + * method. Unescaping means to convert %hh hex strings to the ascii equivalent + * and converting '+' to ' '. Escaping converts '+', '%', '=', ';', + * and ascii control chars to %hh hex strings. + * + * CookieList should not be considered as just a list of Cookie objects: + * - CookieList stores a cookie name/value pair as a single entry; Cookie stores + * it as 2 entries. + * - CookieList expects multiple name/value pairs as input; Cookie allows the + * 'secure' name with no associated value */ public class CookieListTest { + @Test(expected=NullPointerException.class) public void nullCookieListException() { + /** + * Attempts to create a CookieList from a null string + */ String cookieStr = null; CookieList.toJSONObject(cookieStr); } @Test(expected=JSONException.class) public void malFormedCookieListException() { + /** + * Attempts to create a CookieList from a malformed string + */ String cookieStr = "thisCookieHasNoEqualsChar"; CookieList.toJSONObject(cookieStr); } @@ -31,6 +45,7 @@ public class CookieListTest { @Test(expected=JSONException.class) public void emptyStringCookieList() { /** + * Creates a CookieList from an empty string. * Cookie throws an exception, but CookieList does not */ String cookieStr = ""; @@ -42,6 +57,9 @@ public class CookieListTest { @Test public void simpleCookieList() { + /** + * The simplest cookie is a name/value pair with no delimiter + */ String cookieStr = "SID=31d4d96e407aad42"; String expectedCookieStr = "{\"SID\":\"31d4d96e407aad42\"}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); From 912350ec7526c848f022cb4fb1d48e262fe3ad7f Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 27 Apr 2015 14:56:01 -0500 Subject: [PATCH 101/451] 96.5% coverage --- CookieListTest.java | 114 +++++++++++++++++++++++++++++--------------- 1 file changed, 75 insertions(+), 39 deletions(-) diff --git a/CookieListTest.java b/CookieListTest.java index 9edc9ad..0eaef71 100644 --- a/CookieListTest.java +++ b/CookieListTest.java @@ -1,7 +1,5 @@ package org.json.junit; -import java.util.*; - import static org.junit.Assert.*; import org.json.*; @@ -10,17 +8,19 @@ import org.junit.Test; /** * HTTP cookie specification: RFC6265 * - * A cookie list is a JSONObject whose members are cookie name/value pairs. - * Entries are unescaped while being added, and escaped in the toString() - * method. Unescaping means to convert %hh hex strings to the ascii equivalent - * and converting '+' to ' '. Escaping converts '+', '%', '=', ';', - * and ascii control chars to %hh hex strings. + * A cookie list is a JSONObject whose members are presumed to be cookie + * name/value pairs. Entries are unescaped while being added, and escaped in + * the toString() output. + * Unescaping means to convert %hh hex strings to the ascii equivalent + * and converting '+' to ' '. + * Escaping converts '+', '%', '=', ';' and ascii control chars to %hh hex strings. * * CookieList should not be considered as just a list of Cookie objects: * - CookieList stores a cookie name/value pair as a single entry; Cookie stores - * it as 2 entries. - * - CookieList expects multiple name/value pairs as input; Cookie allows the + * it as 2 entries (key="name" and key="value"). + * - CookieList requires multiple name/value pairs as input; Cookie allows the * 'secure' name with no associated value + * - CookieList has no special handling for attribute name/value pairs. */ public class CookieListTest { @@ -68,36 +68,66 @@ public class CookieListTest { } @Test - public void multiPartCookieList() { - String cookieStr = - "PH=deleted; "+ - " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ - "path=/; "+ - " domain=.yahoo.com;"; - String expectedCookieStr = - "{\"path\":\"/\","+ - "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ - "\"domain\":\".yahoo.com\","+ - "\"PH\":\"deleted\"}"; + public void simpleCookieListWithDelimiter() { + /** + * The simplest cookie is a name/value pair with a delimiter + */ + String cookieStr = "SID=31d4d96e407aad42;"; + String expectedCookieStr = "{\"SID\":\"31d4d96e407aad42\"}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + @Test + public void multiPartCookieList() { + String cookieStr = + "name1=myCookieValue1; "+ + " name2=myCookieValue2;"+ + "name3=myCookieValue3;"+ + " name4=myCookieValue4; "+ + "name5=myCookieValue5;"+ + " name6=myCookieValue6;"; + String expectedCookieStr = + "{"+ + "\"name1\":\"myCookieValue1\","+ + "\"name2\":\"myCookieValue2\","+ + "\"name3\":\"myCookieValue3\","+ + "\"name4\":\"myCookieValue4\","+ + "\"name5\":\"myCookieValue5\","+ + "\"name6\":\"myCookieValue6\""+ + "}"; + JSONObject jsonObject = CookieList.toJSONObject(cookieStr); + JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + @Test + public void convertCookieListWithNullValueToString() { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("key", JSONObject.NULL); + String cookieToStr = CookieList.toString(jsonObject); + assertTrue("toString() should be empty", "".equals(cookieToStr)); + } + @Test public void convertCookieListToString() { String cookieStr = - "PH=deleted; "+ - " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ - "path=/; "+ - " domain=.yahoo.com;"+ - "thisWont=beIncluded;"; + "name1=myCookieValue1; "+ + " name2=myCookieValue2;"+ + "name3=myCookieValue3;"+ + " name4=myCookieValue4; "+ + "name5=myCookieValue5;"+ + " name6=myCookieValue6;"; String expectedCookieStr = - "{\"path\":\"/\","+ - "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ - "\"domain\":\".yahoo.com\","+ - "\"thisWont\":\"beIncluded\","+ - "\"PH\":\"deleted\"}"; + "{"+ + "\"name1\":\"myCookieValue1\","+ + "\"name2\":\"myCookieValue2\","+ + "\"name3\":\"myCookieValue3\","+ + "\"name4\":\"myCookieValue4\","+ + "\"name5\":\"myCookieValue5\","+ + "\"name6\":\"myCookieValue6\""+ + "}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); String cookieToStr = CookieList.toString(jsonObject); @@ -106,18 +136,24 @@ public class CookieListTest { Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } - @Test + @Test public void convertEncodedCookieListToString() { String cookieStr = - "PH=deleted; "+ - " expires=Wed,+19-Mar-2014+17:53:53+GMT;"+ - "path=/%2Bthis/is%26/a/spec%3Bsegment%3D; "+ - " domain=.yahoo.com;"; + "name1=myCookieValue1; "+ + " name2=my+Cookie+Value+2;"+ + "name3=my%2BCookie%26Value%3B3%3D;"+ + " name4=my%25CookieValue4; "+ + "name5=myCookieValue5;"+ + " name6=myCookieValue6;"; String expectedCookieStr = - "{\"path\":\"/+this/is&/a/spec;segment=\","+ - "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ - "\"domain\":\".yahoo.com\","+ - "\"PH\":\"deleted\"}"; + "{"+ + "\"name1\":\"myCookieValue1\","+ + "\"name2\":\"my Cookie Value 2\","+ + "\"name3\":\"my+Cookie&Value;3=\","+ + "\"name4\":\"my%CookieValue4\","+ + "\"name5\":\"myCookieValue5\","+ + "\"name6\":\"myCookieValue6\""+ + "}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); String cookieToStr = CookieList.toString(jsonObject); From 31614fe8264b0c0ef5825c0ecc44b2c9660cbe01 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 27 Apr 2015 15:01:27 -0500 Subject: [PATCH 102/451] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 49d912a..f92e029 100644 --- a/README.md +++ b/README.md @@ -38,11 +38,11 @@ A unit test has the following stages: | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 88.6% | | | +| Total coverage | 88.9% | | | | | | | | CDL.java | 98% | Reasonable test cases. | | Cookie.java | 98.9% | Reasonable test cases. | -| CookieList.java |96.5% | Coverage > 90% | +| CookieList.java |96.5% | Reasonable test cases. | | HTTP.java | 98.7%| Coverage > 90% | | HTTPTokener.java |93.2% | No test | | JSONArray.java |95.9% | Coverage > 90% | From 6195bd248b50d8691f8b2e7c80a88464ad2f4b88 Mon Sep 17 00:00:00 2001 From: stleary Date: Tue, 5 May 2015 21:53:51 -0500 Subject: [PATCH 103/451] added unit tests for suppress warning coverage --- JSONObjectTest.java | 56 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 824a674..86c6b1d 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -552,6 +552,62 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + @Test + public void jsonObjectToStringSuppressWarningOnCastToMap() { + JSONObject jsonObject = new JSONObject(); + Map map = new HashMap(); + map.put("abc", "def"); + jsonObject.put("key", map); + String toStr = jsonObject.toString(); + JSONObject expectedJsonObject = new JSONObject(toStr); + assertTrue("keys should be equal", + jsonObject.keySet().iterator().next().equals( + expectedJsonObject.keySet().iterator().next())); + /** + * Can't do a Util compare because although they look the same + * in the debugger, one is a map and the other is a JSONObject. + */ + // TODO: fix warnings + map = (Map)jsonObject.get("key"); + JSONObject mapJsonObject = expectedJsonObject.getJSONObject("key"); + assertTrue("value size should be equal", + map.size() == mapJsonObject.length() && map.size() == 1); + assertTrue("keys should be equal for key: "+map.keySet().iterator().next(), + mapJsonObject.keys().next().equals(map.keySet().iterator().next())); + assertTrue("values should be equal for key: "+map.keySet().iterator().next(), + mapJsonObject.get(mapJsonObject.keys().next()).toString().equals( + map.get(map.keySet().iterator().next()))); + } + + @Test + public void jsonObjectToStringSuppressWarningOnCastToCollection() { + JSONObject jsonObject = new JSONObject(); + Collection collection = new ArrayList(); + collection.add("abc"); + // ArrayList will be added as an object + jsonObject.put("key", collection); + String toStr = jsonObject.toString(); + // [abc] will be added as a JSONArray + JSONObject expectedJsonObject = new JSONObject(toStr); + /** + * Can't do a Util compare because although they look the same + * in the debugger, one is a collection and the other is a JSONArray. + */ + assertTrue("keys should be equal", + jsonObject.keySet().iterator().next().equals( + expectedJsonObject.keySet().iterator().next())); + // TODO: fix warnings + collection = (Collection)jsonObject.get("key"); + JSONArray jsonArray = expectedJsonObject.getJSONArray("key"); + assertTrue("value size should be equal", + collection.size() == jsonArray.length()); + Iterator it = collection.iterator(); + for (int i = 0; i < collection.size(); ++i) { + assertTrue("items should be equal for index: "+i, + jsonArray.get(i).toString().equals(it.next().toString())); + } + } + @Test public void valueToString() { From fbd07da05a71d6d8b710c3554a68ae6ebb2b0aa9 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Wed, 6 May 2015 14:37:52 -0500 Subject: [PATCH 104/451] Update README.md --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f92e029..d91f7c2 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,13 @@ The fundamental issues with JSON-Java testing are: * JSONObjects are unordered, making simple string comparison ineffective. * Comparisons via **equals()** is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. * Access to the JSONArray and JSONObject internal containers for comparison is not currently available. -* JSONObject sometimes wraps entries in quotes, other times does not, complicating comparisons. + +General issues with unit testing are: +* Just writing tests to make coverage goals tends to result in poor tests. +* Unit tests are a form of documentation - how a given method actually works is demonstrated by the test. So for a code reviewer or future developer looking at code a good test helps explain how a function is supposed to work according to the original author. This can be difficult if you are not the original developer. +* It is difficult to evaluate unit tests in a vacuum. You also need to see the code being tested to understand if a test is good. +* Without unit tests it is hard to feel confident about the quality of the code, especially when fixing bugs or refactoring. Good tests prevents regressions and keeps the intent of the code correct. +* If you have unit test results along with pull requests, the reviewer has an easier time understanding your code and determining if the it works as intended. When you start working on a test, add the empty file to the repository and update the readme, so that others will know that test is taken. From 95b8cd5b0393922c64fd0ff30f3c1a93568f46cf Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 6 May 2015 22:16:08 -0500 Subject: [PATCH 105/451] test improvements, in progress --- JSONObjectTest.java | 1894 +++++++++++++++++++++++-------------------- 1 file changed, 995 insertions(+), 899 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 86c6b1d..1aa19d7 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -1,899 +1,995 @@ -package org.json.junit; - -import static org.junit.Assert.*; - -import java.io.*; -import java.util.*; - -import org.json.*; -import org.junit.*; - -class MyJsonString implements JSONString { - - @Override - public String toJSONString() { - return "my string"; - } -} - -public class JSONObjectTest { - - - @Test - public void jsonObjectByNames() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"nullKey\":null,"+ - "\"stringKey\":\"hello world!\","+ - "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ - "\"intKey\":42,"+ - "\"doubleKey\":-23.45e67"+ - "}"; - String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"}; - String expectedStr = - "{"+ - "\"falseKey\":false,"+ - "\"nullKey\":null,"+ - "\"stringKey\":\"hello world!\","+ - "\"doubleKey\":-23.45e67"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - JSONObject copyJsonObject = new JSONObject(jsonObject, keys); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(copyJsonObject, expectedJsonObject); - } - - @Test - public void jsonObjectByMap() { - String expectedStr = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ - "\"intKey\":42,"+ - "\"doubleKey\":-23.45e67"+ - "}"; - Map jsonMap = new HashMap(); - jsonMap.put("trueKey", new Boolean(true)); - jsonMap.put("falseKey", new Boolean(false)); - jsonMap.put("stringKey", "hello world!"); - jsonMap.put("complexStringKey", "h\be\tllo w\u1234orld!"); - jsonMap.put("intKey", new Long(42)); - jsonMap.put("doubleKey", new Double(-23.45e67)); - - JSONObject jsonObject = new JSONObject(jsonMap); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - } - - @Test - public void jsonObjectByBean() { - String expectedStr = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ - "\"intKey\":42,"+ - "\"doubleKey\":-23.45e7"+ - "}"; - MyBean myBean = new MyBean(); - JSONObject jsonObject = new JSONObject(myBean); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - } - - @Test - public void jsonObjectByBeanAndNames() { - String expectedStr = - "{"+ - "\"trueKey\":true,"+ - "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ - "\"doubleKey\":-23.45e7"+ - "}"; - String[] keys = {"trueKey", "complexStringKey", "doubleKey"}; - MyBean myBean = new MyBean(); - JSONObject jsonObject = new JSONObject(myBean, keys); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - } - - @Test - public void jsonObjectByResourceBundle() { - String expectedStr = - "{"+ - "\"greetings\": {"+ - "\"hello\":\"Hello, \","+ - "\"world\":\"World!\""+ - "},"+ - "\"farewells\": {"+ - "\"later\":\"Later, \","+ - "\"gator\":\"Alligator!\""+ - "}"+ - "}"; - JSONObject jsonObject = new - JSONObject("org.json.junit.StringsResourceBundle", - Locale.getDefault()); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - } - - @Test - public void jsonObjectAccumulate() { - String expectedStr = - "{"+ - "\"myArray\": ["+ - "true,"+ - "false,"+ - "\"hello world!\","+ - "\"h\be\tllo w\u1234orld!\","+ - "42,"+ - "-23.45e7"+ - "]"+ - "}"; - JSONObject jsonObject = new JSONObject(); - jsonObject.accumulate("myArray", true); - jsonObject.accumulate("myArray", false); - jsonObject.accumulate("myArray", "hello world!"); - jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); - jsonObject.accumulate("myArray", 42); - jsonObject.accumulate("myArray", -23.45e7); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - } - - @Test - public void jsonObjectAppend() { - String expectedStr = - "{"+ - "\"myArray\": ["+ - "true,"+ - "false,"+ - "\"hello world!\","+ - "\"h\be\tllo w\u1234orld!\","+ - "42,"+ - "-23.45e7"+ - "]"+ - "}"; - JSONObject jsonObject = new JSONObject(); - jsonObject.append("myArray", true); - jsonObject.append("myArray", false); - jsonObject.append("myArray", "hello world!"); - jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); - jsonObject.append("myArray", 42); - jsonObject.append("myArray", -23.45e7); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - } - - @Test - public void jsonObjectDoubleToString() { - String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68" }; - Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67 }; - for (int i = 0; i < expectedStrs.length; ++i) { - String actualStr = JSONObject.doubleToString(doubles[i]); - assertTrue("value expected ["+expectedStrs[i]+ - "] found ["+actualStr+ "]", - expectedStrs[i].equals(actualStr)); - } - } - - @Test - public void jsonObjectValues() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"trueStrKey\":\"true\","+ - "\"falseStrKey\":\"false\","+ - "\"stringKey\":\"hello world!\","+ - "\"intKey\":42,"+ - "\"intStrKey\":\"43\","+ - "\"longKey\":1234567890123456789,"+ - "\"longStrKey\":\"987654321098765432\","+ - "\"doubleKey\":-23.45e7,"+ - "\"doubleStrKey\":\"00001.000\","+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{\"myKey\":\"myVal\"}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); - assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); - assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); - assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); - assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); - assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); - assertTrue("stringKey should be string", - jsonObject.getString("stringKey").equals("hello world!")); - assertTrue("doubleKey should be double", - jsonObject.getDouble("doubleKey") == -23.45e7); - assertTrue("doubleStrKey should be double", - jsonObject.getDouble("doubleStrKey") == 1); - assertTrue("opt doubleKey should be double", - jsonObject.optDouble("doubleKey") == -23.45e7); - assertTrue("opt doubleKey with Default should be double", - jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); - assertTrue("intKey should be int", - jsonObject.optInt("intKey") == 42); - assertTrue("opt intKey should be int", - jsonObject.optInt("intKey", 0) == 42); - assertTrue("opt intKey with default should be int", - jsonObject.getInt("intKey") == 42); - assertTrue("intStrKey should be int", - jsonObject.getInt("intStrKey") == 43); - assertTrue("longKey should be long", - jsonObject.getLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey should be long", - jsonObject.optLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey with default should be long", - jsonObject.optLong("longKey", 0) == 1234567890123456789L); - assertTrue("longStrKey should be long", - jsonObject.getLong("longStrKey") == 987654321098765432L); - assertTrue("xKey should not exist", - jsonObject.isNull("xKey")); - assertTrue("stringKey should exist", - jsonObject.has("stringKey")); - assertTrue("opt stringKey should string", - jsonObject.optString("stringKey").equals("hello world!")); - assertTrue("opt stringKey with default should string", - jsonObject.optString("stringKey", "not found").equals("hello world!")); - JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); - assertTrue("arrayKey should be JSONArray", - jsonArray.getInt(0) == 0 && - jsonArray.getInt(1) == 1 && - jsonArray.getInt(2) == 2); - jsonArray = jsonObject.optJSONArray("arrayKey"); - assertTrue("opt arrayKey should be JSONArray", - jsonArray.getInt(0) == 0 && - jsonArray.getInt(1) == 1 && - jsonArray.getInt(2) == 2); - JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); - assertTrue("objectKey should be JSONObject", - jsonObjectInner.get("myKey").equals("myVal")); - } - - @Test - public void jsonObjectNonAndWrongValues() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"trueStrKey\":\"true\","+ - "\"falseStrKey\":\"false\","+ - "\"stringKey\":\"hello world!\","+ - "\"intKey\":42,"+ - "\"intStrKey\":\"43\","+ - "\"longKey\":1234567890123456789,"+ - "\"longStrKey\":\"987654321098765432\","+ - "\"doubleKey\":-23.45e7,"+ - "\"doubleStrKey\":\"00001.000\","+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{\"myKey\":\"myVal\"}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - int tryCount = 0; - int exceptionCount = 0; - try { - ++tryCount; - jsonObject.getBoolean("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getBoolean("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getString("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getString("trueKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getDouble("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getDouble("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getInt("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getInt("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getLong("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getLong("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getJSONArray("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getJSONArray("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getJSONObject("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } - try { - ++tryCount; - jsonObject.getJSONObject("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } - assertTrue("all get calls should have failed", - exceptionCount == tryCount); - } - - @Test - public void jsonObjectNames() { - - // getNames() from null JSONObject - assertTrue("null names from null Object", - null == JSONObject.getNames((Object)null)); - - // getNames() from object with no fields - assertTrue("null names from Object with no fields", - null == JSONObject.getNames(new MyJsonString())); - - // getNames() from empty JSONObject - String emptyStr = "{}"; - JSONObject emptyJsonObject = new JSONObject(emptyStr); - assertTrue("empty JSONObject should have null names", - null == JSONObject.getNames(emptyJsonObject)); - - // getNames() from JSONObject - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "}"; - String [] expectedNames = {"trueKey", "falseKey", "stringKey"}; - JSONObject jsonObject = new JSONObject(str); - String [] names = JSONObject.getNames(jsonObject); - Util.compareActualVsExpectedStringArrays(names, expectedNames); - } - - @Test - public void jsonObjectNamesToJsonAray() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "}"; - String [] expectedNames = {"trueKey", "falseKey", "stringKey" }; - - JSONObject jsonObject = new JSONObject(str); - JSONArray jsonArray = jsonObject.names(); - /** - * Cannot really compare to an expected JSONArray because the ordering - * of the JSONObject keys is not fixed, and JSONArray comparisons - * presume fixed. Since this test is limited to key strings, a - * string comparison will have to suffice. - */ - String namesStr = jsonArray.toString(); - // remove square brackets, commas, and spaces - namesStr = namesStr.replaceAll("[\\]|\\[|\"]", ""); - String [] names = namesStr.split(","); - - Util.compareActualVsExpectedStringArrays(names, expectedNames); - } - - @Test - public void objectNames() { - MyBean myBean = new MyBean(); - String [] expectedNames = {"intKey", "doubleKey", "stringKey", - "complexStringKey", "trueKey", "falseKey"}; - String [] names = JSONObject.getNames(myBean); - Util.compareActualVsExpectedStringArrays(names, expectedNames); - } - - @Test - public void jsonObjectIncrement() { - String str = - "{"+ - "\"keyLong\":9999999991,"+ - "\"keyDouble\":1.1,"+ - "}"; - String expectedStr = - "{"+ - "\"keyInt\":3,"+ - "\"keyLong\":9999999993,"+ - "\"keyDouble\":3.1,"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.increment("keyInt"); - jsonObject.increment("keyInt"); - jsonObject.increment("keyLong"); - jsonObject.increment("keyDouble"); - jsonObject.increment("keyInt"); - jsonObject.increment("keyLong"); - jsonObject.increment("keyDouble"); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - } - - @Test - public void jsonObjectNamesToArray() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "}"; - String [] expectedNames = {"trueKey", "falseKey", "stringKey"}; - JSONObject jsonObject = new JSONObject(str); - String [] names = JSONObject.getNames(jsonObject); - Util.compareActualVsExpectedStringArrays(names, expectedNames); - } - - @Test - public void jsonObjectNumberToString() { - String str; - Double dVal; - Integer iVal = 1; - str = JSONObject.numberToString(iVal); - assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); - dVal = 12.34; - str = JSONObject.numberToString(dVal); - assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); - dVal = 12.34e27; - str = JSONObject.numberToString(dVal); - assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); - // trailing .0 is truncated, so it doesn't quite match toString() - dVal = 5000000.0000000; - str = JSONObject.numberToString(dVal); - assertTrue("expected 5000000 actual "+str, str.equals("5000000")); - } - - @Test - public void jsonObjectPut() { - String expectedStr = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{"+ - "\"myKey1\":\"myVal1\","+ - "\"myKey2\":\"myVal2\","+ - "\"myKey3\":\"myVal3\","+ - "\"myKey4\":\"myVal4\""+ - "}"+ - "}"; - String expectedStrAfterRemoval = - "{"+ - "\"falseKey\":false,"+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{"+ - "\"myKey1\":\"myVal1\","+ - "\"myKey2\":\"myVal2\","+ - "\"myKey3\":\"myVal3\","+ - "\"myKey4\":\"myVal4\""+ - "}"+ - "}"; - JSONObject jsonObject = new JSONObject(); - jsonObject.put("trueKey", true); - jsonObject.put("falseKey", false); - Integer [] intArray = { 0, 1, 2 }; - jsonObject.put("arrayKey", Arrays.asList(intArray)); - Map myMap = new HashMap(); - myMap.put("myKey1", "myVal1"); - myMap.put("myKey2", "myVal2"); - myMap.put("myKey3", "myVal3"); - myMap.put("myKey4", "myVal4"); - jsonObject.put("objectKey", myMap); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - assertTrue("equal jsonObjects should be similar", - jsonObject.similar(expectedJsonObject)); - - jsonObject.remove("trueKey"); - JSONObject expectedJsonObjectAfterRemoval = - new JSONObject(expectedStrAfterRemoval); - Util.compareActualVsExpectedJsonObjects(jsonObject, - expectedJsonObjectAfterRemoval); - assertTrue("unequal jsonObjects should not be similar", - !jsonObject.similar(expectedJsonObject)); - assertTrue("unequal Objects should not be similar", - !jsonObject.similar(new JSONArray())); - - String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; - String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; - JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); - JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); - assertTrue("different values should not be similar", - !aCompareValueJsonObject.similar(bCompareValueJsonObject)); - - String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; - String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; - JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); - JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); - assertTrue("different nested JSONObjects should not be similar", - !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); - - String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; - String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; - JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); - JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); - assertTrue("different nested JSONArrays should not be similar", - !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); - } - - @Test - public void jsonObjectToString() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{"+ - "\"myKey1\":\"myVal1\","+ - "\"myKey2\":\"myVal2\","+ - "\"myKey3\":\"myVal3\","+ - "\"myKey4\":\"myVal4\""+ - "}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - String toStr = jsonObject.toString(); - JSONObject expectedJsonObject = new JSONObject(toStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - } - - @Test - public void jsonObjectToStringSuppressWarningOnCastToMap() { - JSONObject jsonObject = new JSONObject(); - Map map = new HashMap(); - map.put("abc", "def"); - jsonObject.put("key", map); - String toStr = jsonObject.toString(); - JSONObject expectedJsonObject = new JSONObject(toStr); - assertTrue("keys should be equal", - jsonObject.keySet().iterator().next().equals( - expectedJsonObject.keySet().iterator().next())); - /** - * Can't do a Util compare because although they look the same - * in the debugger, one is a map and the other is a JSONObject. - */ - // TODO: fix warnings - map = (Map)jsonObject.get("key"); - JSONObject mapJsonObject = expectedJsonObject.getJSONObject("key"); - assertTrue("value size should be equal", - map.size() == mapJsonObject.length() && map.size() == 1); - assertTrue("keys should be equal for key: "+map.keySet().iterator().next(), - mapJsonObject.keys().next().equals(map.keySet().iterator().next())); - assertTrue("values should be equal for key: "+map.keySet().iterator().next(), - mapJsonObject.get(mapJsonObject.keys().next()).toString().equals( - map.get(map.keySet().iterator().next()))); - } - - @Test - public void jsonObjectToStringSuppressWarningOnCastToCollection() { - JSONObject jsonObject = new JSONObject(); - Collection collection = new ArrayList(); - collection.add("abc"); - // ArrayList will be added as an object - jsonObject.put("key", collection); - String toStr = jsonObject.toString(); - // [abc] will be added as a JSONArray - JSONObject expectedJsonObject = new JSONObject(toStr); - /** - * Can't do a Util compare because although they look the same - * in the debugger, one is a collection and the other is a JSONArray. - */ - assertTrue("keys should be equal", - jsonObject.keySet().iterator().next().equals( - expectedJsonObject.keySet().iterator().next())); - // TODO: fix warnings - collection = (Collection)jsonObject.get("key"); - JSONArray jsonArray = expectedJsonObject.getJSONArray("key"); - assertTrue("value size should be equal", - collection.size() == jsonArray.length()); - Iterator it = collection.iterator(); - for (int i = 0; i < collection.size(); ++i) { - assertTrue("items should be equal for index: "+i, - jsonArray.get(i).toString().equals(it.next().toString())); - } - } - - @Test - public void valueToString() { - - assertTrue("null valueToString() incorrect", - "null".equals(JSONObject.valueToString(null))); - MyJsonString jsonString = new MyJsonString(); - assertTrue("jsonstring valueToString() incorrect", - "my string".equals(JSONObject.valueToString(jsonString))); - assertTrue("boolean valueToString() incorrect", - "true".equals(JSONObject.valueToString(Boolean.TRUE))); - assertTrue("non-numeric double", - "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); - String jsonObjectStr = - "{"+ - "\"key1\":\"val1\","+ - "\"key2\":\"val2\","+ - "\"key3\":\"val3\""+ - "}"; - JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("jsonObject valueToString() incorrect", - JSONObject.valueToString(jsonObject).equals(jsonObject.toString())); - String jsonArrayStr = - "[1,2,3]"; - JSONArray jsonArray = new JSONArray(jsonArrayStr); - assertTrue("jsonArra valueToString() incorrect", - JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); - Map map = new HashMap(); - map.put("key1", "val1"); - map.put("key2", "val2"); - map.put("key3", "val3"); - assertTrue("map valueToString() incorrect", - jsonObject.toString().equals(JSONObject.valueToString(map))); - Collection collection = new ArrayList(); - collection.add(new Integer(1)); - collection.add(new Integer(2)); - collection.add(new Integer(3)); - assertTrue("collection valueToString() expected: "+ - jsonArray.toString()+ " actual: "+ - JSONObject.valueToString(collection), - jsonArray.toString().equals(JSONObject.valueToString(collection))); - Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; - assertTrue("array valueToString() incorrect", - jsonArray.toString().equals(JSONObject.valueToString(array))); - } - - @Test - public void wrapObject() { - // wrap(null) returns NULL - assertTrue("null wrap() incorrect", - JSONObject.NULL == JSONObject.wrap(null)); - - // wrap(Integer) returns Integer - Integer in = new Integer(1); - assertTrue("Integer wrap() incorrect", - in == JSONObject.wrap(in)); - - // wrap JSONObject returns JSONObject - String jsonObjectStr = - "{"+ - "\"key1\":\"val1\","+ - "\"key2\":\"val2\","+ - "\"key3\":\"val3\""+ - "}"; - JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("JSONObject wrap() incorrect", - jsonObject == JSONObject.wrap(jsonObject)); - - // wrap collection returns JSONArray - Collection collection = new ArrayList(); - collection.add(new Integer(1)); - collection.add(new Integer(2)); - collection.add(new Integer(3)); - JSONArray jsonArray = (JSONArray)(JSONObject.wrap(collection)); - String expectedCollectionJsonArrayStr = - "[1,2,3]"; - JSONArray expectedCollectionJsonArray = - new JSONArray(expectedCollectionJsonArrayStr); - Util.compareActualVsExpectedJsonArrays(jsonArray, - expectedCollectionJsonArray); - - // wrap Array returns JSONArray - Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; - JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); - JSONArray expectedIntegerArrayJsonArray = new JSONArray("[1,2,3]"); - Util.compareActualVsExpectedJsonArrays(integerArrayJsonArray, - expectedIntegerArrayJsonArray); - - // wrap map returns JSONObject - Map map = new HashMap(); - map.put("key1", "val1"); - map.put("key2", "val2"); - map.put("key3", "val3"); - JSONObject mapJsonObject = (JSONObject)(JSONObject.wrap(map)); - Util.compareActualVsExpectedJsonObjects(jsonObject, mapJsonObject); - - // TODO test wrap(package) - } - - @Test - public void jsonObjectParsingErrors() { - int tryCount = 0; - int exceptionCount = 0; - try { - // does not start with '{' - ++tryCount; - String str = "abc"; - new JSONObject(str); - } catch (JSONException ignore) {++exceptionCount; } - try { - // does not end with '}' - ++tryCount; - String str = "{"; - new JSONObject(str); - } catch (JSONException ignore) {++exceptionCount; } - try { - // key with no ':' - ++tryCount; - String str = "{\"myKey\" = true}"; - new JSONObject(str); - } catch (JSONException ignore) {++exceptionCount; } - try { - // entries with no ',' separator - ++tryCount; - String str = "{\"myKey\":true \"myOtherKey\":false}"; - new JSONObject(str); - } catch (JSONException ignore) {++exceptionCount; } - try { - // append to wrong key - ++tryCount; - String str = "{\"myKey\":true, \"myOtherKey\":false}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.append("myKey", "hello"); - } catch (JSONException ignore) {++exceptionCount; } - try { - // increment wrong key - ++tryCount; - String str = "{\"myKey\":true, \"myOtherKey\":false}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.increment("myKey"); - } catch (JSONException ignore) {++exceptionCount; } - try { - // invalid key - ++tryCount; - String str = "{\"myKey\":true, \"myOtherKey\":false}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.get(null); - } catch (JSONException ignore) {++exceptionCount; } - try { - // invalid numberToString() - ++tryCount; - JSONObject.numberToString((Number)null); - } catch (JSONException ignore) {++exceptionCount; } - try { - // null put key - ++tryCount; - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, 0); - } catch (NullPointerException ignore) {++exceptionCount; } - try { - // multiple putOnce key - ++tryCount; - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.putOnce("hello", "world"); - jsonObject.putOnce("hello", "world!"); - } catch (JSONException ignore) {++exceptionCount; } - try { - // test validity of invalid double - ++tryCount; - JSONObject.testValidity(Double.NaN); - } catch (JSONException ignore) {++exceptionCount; } - try { - // test validity of invalid float - ++tryCount; - JSONObject.testValidity(Float.NEGATIVE_INFINITY); - } catch (JSONException ignore) {++exceptionCount; } - - assertTrue("all tries should have failed", - exceptionCount == tryCount); - } - - @Test - public void jsonObjectOptDefault() { - - String str = "{\"myKey\": \"myval\"}"; - JSONObject jsonObject = new JSONObject(str); - - assertTrue("optBoolean() should return default boolean", - Boolean.TRUE == jsonObject.optBoolean("myKey", Boolean.TRUE)); - assertTrue("optInt() should return default int", - 42 == jsonObject.optInt("myKey", 42)); - assertTrue("optInt() should return default int", - 42 == jsonObject.optInt("myKey", 42)); - assertTrue("optLong() should return default long", - 42 == jsonObject.optLong("myKey", 42)); - assertTrue("optDouble() should return default double", - 42.3 == jsonObject.optDouble("myKey", 42.3)); - assertTrue("optString() should return default string", - "hi".equals(jsonObject.optString("hiKey", "hi"))); - } - - @Test - public void jsonObjectputNull() { - - // put null should remove the item. - String str = "{\"myKey\": \"myval\"}"; - JSONObject jsonObjectRemove = new JSONObject(str); - JSONObject jsonObjectPutNull = new JSONObject(str); - jsonObjectRemove.remove("myKey"); - jsonObjectPutNull.put("myKey", (Object)null); - Util.compareActualVsExpectedJsonObjects(jsonObjectRemove, jsonObjectPutNull); - assertTrue("jsonObject should be empty", - jsonObjectRemove.length() == 0 && - jsonObjectPutNull.length() == 0); - } - - @Test - public void jsonObjectQuote() { - String str; - str = ""; - String quotedStr; - quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found "+quotedStr, - "\"\"".equals(quotedStr)); - str = "\"\""; - quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found "+quotedStr, - "\"\\\"\\\"\"".equals(quotedStr)); - str = ". + * In this test the map is null. + */ + Map map = null; + JSONObject jsonObject = new JSONObject(map); + JSONObject expectedJsonObject = new JSONObject(); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectByMap() { + /** + * JSONObjects can be built from a Map. + * In this test all of the map entries are valid JSON types. + * TODO: test with map values that are not valid JSON types + */ + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"intKey\":42,"+ + "\"doubleKey\":-23.45e67"+ + "}"; + Map jsonMap = new HashMap(); + jsonMap.put("trueKey", new Boolean(true)); + jsonMap.put("falseKey", new Boolean(false)); + jsonMap.put("stringKey", "hello world!"); + jsonMap.put("complexStringKey", "h\be\tllo w\u1234orld!"); + jsonMap.put("intKey", new Long(42)); + jsonMap.put("doubleKey", new Double(-23.45e67)); + + JSONObject jsonObject = new JSONObject(jsonMap); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectByMapWithNullValue() { + /** + * JSONObjects can be built from a Map. + * In this test one of the map values is null + */ + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"intKey\":42,"+ + "\"doubleKey\":-23.45e67"+ + "}"; + Map jsonMap = new HashMap(); + jsonMap.put("trueKey", new Boolean(true)); + jsonMap.put("falseKey", new Boolean(false)); + jsonMap.put("stringKey", "hello world!"); + jsonMap.put("nullKey", null); + jsonMap.put("complexStringKey", "h\be\tllo w\u1234orld!"); + jsonMap.put("intKey", new Long(42)); + jsonMap.put("doubleKey", new Double(-23.45e67)); + + JSONObject jsonObject = new JSONObject(jsonMap); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test(expected=NullPointerException.class) + public void jsonObjectByNullBean() { + /** + * JSONObject built from a bean, but only using a null value. + * Nothing good is expected to happen. + */ + MyBean myBean = null; + new JSONObject(myBean); + } + + @Test + public void jsonObjectByBean() { + /** + * JSONObject built from a bean. In this case all of the + * bean properties are valid JSON types + * TODO: test with bean fields that are not valid JSON types + */ + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"intKey\":42,"+ + "\"doubleKey\":-23.45e7"+ + "}"; + MyBean myBean = new MyBean(); + JSONObject jsonObject = new JSONObject(myBean); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectByObjectAndNames() { + /** + * A bean is also an object. But in order to test the JSONObject + * ctor that takes an object and a list of names, + * this particular bean needs some public + * data members, which have been added to the class. + */ + String expectedStr = + "{"+ + "\"publicStr\":\"abc\","+ + "\"publicInt\":42"+ + "}"; + String[] keys = {"publicStr", "publicInt"}; + + MyBean myBean = new MyBean(); + JSONObject jsonObject = new JSONObject(myBean, keys); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + // this is where I left off + + @Test + public void jsonObjectByResourceBundle() { + String expectedStr = + "{"+ + "\"greetings\": {"+ + "\"hello\":\"Hello, \","+ + "\"world\":\"World!\""+ + "},"+ + "\"farewells\": {"+ + "\"later\":\"Later, \","+ + "\"gator\":\"Alligator!\""+ + "}"+ + "}"; + JSONObject jsonObject = new + JSONObject("org.json.junit.StringsResourceBundle", + Locale.getDefault()); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectAccumulate() { + String expectedStr = + "{"+ + "\"myArray\": ["+ + "true,"+ + "false,"+ + "\"hello world!\","+ + "\"h\be\tllo w\u1234orld!\","+ + "42,"+ + "-23.45e7"+ + "]"+ + "}"; + JSONObject jsonObject = new JSONObject(); + jsonObject.accumulate("myArray", true); + jsonObject.accumulate("myArray", false); + jsonObject.accumulate("myArray", "hello world!"); + jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); + jsonObject.accumulate("myArray", 42); + jsonObject.accumulate("myArray", -23.45e7); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectAppend() { + String expectedStr = + "{"+ + "\"myArray\": ["+ + "true,"+ + "false,"+ + "\"hello world!\","+ + "\"h\be\tllo w\u1234orld!\","+ + "42,"+ + "-23.45e7"+ + "]"+ + "}"; + JSONObject jsonObject = new JSONObject(); + jsonObject.append("myArray", true); + jsonObject.append("myArray", false); + jsonObject.append("myArray", "hello world!"); + jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); + jsonObject.append("myArray", 42); + jsonObject.append("myArray", -23.45e7); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectDoubleToString() { + String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68" }; + Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67 }; + for (int i = 0; i < expectedStrs.length; ++i) { + String actualStr = JSONObject.doubleToString(doubles[i]); + assertTrue("value expected ["+expectedStrs[i]+ + "] found ["+actualStr+ "]", + expectedStrs[i].equals(actualStr)); + } + } + + @Test + public void jsonObjectValues() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"trueStrKey\":\"true\","+ + "\"falseStrKey\":\"false\","+ + "\"stringKey\":\"hello world!\","+ + "\"intKey\":42,"+ + "\"intStrKey\":\"43\","+ + "\"longKey\":1234567890123456789,"+ + "\"longStrKey\":\"987654321098765432\","+ + "\"doubleKey\":-23.45e7,"+ + "\"doubleStrKey\":\"00001.000\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{\"myKey\":\"myVal\"}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); + assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); + assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); + assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); + assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); + assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); + assertTrue("stringKey should be string", + jsonObject.getString("stringKey").equals("hello world!")); + assertTrue("doubleKey should be double", + jsonObject.getDouble("doubleKey") == -23.45e7); + assertTrue("doubleStrKey should be double", + jsonObject.getDouble("doubleStrKey") == 1); + assertTrue("opt doubleKey should be double", + jsonObject.optDouble("doubleKey") == -23.45e7); + assertTrue("opt doubleKey with Default should be double", + jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); + assertTrue("intKey should be int", + jsonObject.optInt("intKey") == 42); + assertTrue("opt intKey should be int", + jsonObject.optInt("intKey", 0) == 42); + assertTrue("opt intKey with default should be int", + jsonObject.getInt("intKey") == 42); + assertTrue("intStrKey should be int", + jsonObject.getInt("intStrKey") == 43); + assertTrue("longKey should be long", + jsonObject.getLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey should be long", + jsonObject.optLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey with default should be long", + jsonObject.optLong("longKey", 0) == 1234567890123456789L); + assertTrue("longStrKey should be long", + jsonObject.getLong("longStrKey") == 987654321098765432L); + assertTrue("xKey should not exist", + jsonObject.isNull("xKey")); + assertTrue("stringKey should exist", + jsonObject.has("stringKey")); + assertTrue("opt stringKey should string", + jsonObject.optString("stringKey").equals("hello world!")); + assertTrue("opt stringKey with default should string", + jsonObject.optString("stringKey", "not found").equals("hello world!")); + JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); + assertTrue("arrayKey should be JSONArray", + jsonArray.getInt(0) == 0 && + jsonArray.getInt(1) == 1 && + jsonArray.getInt(2) == 2); + jsonArray = jsonObject.optJSONArray("arrayKey"); + assertTrue("opt arrayKey should be JSONArray", + jsonArray.getInt(0) == 0 && + jsonArray.getInt(1) == 1 && + jsonArray.getInt(2) == 2); + JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); + assertTrue("objectKey should be JSONObject", + jsonObjectInner.get("myKey").equals("myVal")); + } + + @Test + public void jsonObjectNonAndWrongValues() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"trueStrKey\":\"true\","+ + "\"falseStrKey\":\"false\","+ + "\"stringKey\":\"hello world!\","+ + "\"intKey\":42,"+ + "\"intStrKey\":\"43\","+ + "\"longKey\":1234567890123456789,"+ + "\"longStrKey\":\"987654321098765432\","+ + "\"doubleKey\":-23.45e7,"+ + "\"doubleStrKey\":\"00001.000\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{\"myKey\":\"myVal\"}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + int tryCount = 0; + int exceptionCount = 0; + try { + ++tryCount; + jsonObject.getBoolean("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getBoolean("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getString("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getString("trueKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getDouble("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getDouble("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getInt("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getInt("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getLong("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getLong("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getJSONArray("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getJSONArray("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getJSONObject("nonKey"); + } catch (JSONException ignore) { ++exceptionCount; } + try { + ++tryCount; + jsonObject.getJSONObject("stringKey"); + } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("all get calls should have failed", + exceptionCount == tryCount); + } + + @Test + public void jsonObjectNames() { + + // getNames() from null JSONObject + assertTrue("null names from null Object", + null == JSONObject.getNames((Object)null)); + + // getNames() from object with no fields + assertTrue("null names from Object with no fields", + null == JSONObject.getNames(new MyJsonString())); + + // getNames() from empty JSONObject + String emptyStr = "{}"; + JSONObject emptyJsonObject = new JSONObject(emptyStr); + assertTrue("empty JSONObject should have null names", + null == JSONObject.getNames(emptyJsonObject)); + + // getNames() from JSONObject + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; + String [] expectedNames = {"trueKey", "falseKey", "stringKey"}; + JSONObject jsonObject = new JSONObject(str); + String [] names = JSONObject.getNames(jsonObject); + Util.compareActualVsExpectedStringArrays(names, expectedNames); + } + + @Test + public void jsonObjectNamesToJsonAray() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; + String [] expectedNames = {"trueKey", "falseKey", "stringKey" }; + + JSONObject jsonObject = new JSONObject(str); + JSONArray jsonArray = jsonObject.names(); + /** + * Cannot really compare to an expected JSONArray because the ordering + * of the JSONObject keys is not fixed, and JSONArray comparisons + * presume fixed. Since this test is limited to key strings, a + * string comparison will have to suffice. + */ + String namesStr = jsonArray.toString(); + // remove square brackets, commas, and spaces + namesStr = namesStr.replaceAll("[\\]|\\[|\"]", ""); + String [] names = namesStr.split(","); + + Util.compareActualVsExpectedStringArrays(names, expectedNames); + } + + @Test + public void objectNames() { + /** + * A bean is also an object. But in order to test the static + * method getNames(), this particular bean needs some public + * data members, which have been added to the class. + */ + MyBean myBean = new MyBean(); + String [] expectedNames = {"publicStr", "publicInt"}; + String [] names = JSONObject.getNames(myBean); + Util.compareActualVsExpectedStringArrays(names, expectedNames); + } + + @Test + public void jsonObjectIncrement() { + String str = + "{"+ + "\"keyLong\":9999999991,"+ + "\"keyDouble\":1.1,"+ + "}"; + String expectedStr = + "{"+ + "\"keyInt\":3,"+ + "\"keyLong\":9999999993,"+ + "\"keyDouble\":3.1,"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("keyInt"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectNamesToArray() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; + String [] expectedNames = {"trueKey", "falseKey", "stringKey"}; + JSONObject jsonObject = new JSONObject(str); + String [] names = JSONObject.getNames(jsonObject); + Util.compareActualVsExpectedStringArrays(names, expectedNames); + } + + @Test + public void jsonObjectNumberToString() { + String str; + Double dVal; + Integer iVal = 1; + str = JSONObject.numberToString(iVal); + assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); + dVal = 12.34; + str = JSONObject.numberToString(dVal); + assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + dVal = 12.34e27; + str = JSONObject.numberToString(dVal); + assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + // trailing .0 is truncated, so it doesn't quite match toString() + dVal = 5000000.0000000; + str = JSONObject.numberToString(dVal); + assertTrue("expected 5000000 actual "+str, str.equals("5000000")); + } + + @Test + public void jsonObjectPut() { + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + String expectedStrAfterRemoval = + "{"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("trueKey", true); + jsonObject.put("falseKey", false); + Integer [] intArray = { 0, 1, 2 }; + jsonObject.put("arrayKey", Arrays.asList(intArray)); + Map myMap = new HashMap(); + myMap.put("myKey1", "myVal1"); + myMap.put("myKey2", "myVal2"); + myMap.put("myKey3", "myVal3"); + myMap.put("myKey4", "myVal4"); + jsonObject.put("objectKey", myMap); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + assertTrue("equal jsonObjects should be similar", + jsonObject.similar(expectedJsonObject)); + + jsonObject.remove("trueKey"); + JSONObject expectedJsonObjectAfterRemoval = + new JSONObject(expectedStrAfterRemoval); + Util.compareActualVsExpectedJsonObjects(jsonObject, + expectedJsonObjectAfterRemoval); + assertTrue("unequal jsonObjects should not be similar", + !jsonObject.similar(expectedJsonObject)); + assertTrue("unequal Objects should not be similar", + !jsonObject.similar(new JSONArray())); + + String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; + String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; + JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); + JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); + assertTrue("different values should not be similar", + !aCompareValueJsonObject.similar(bCompareValueJsonObject)); + + String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; + String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; + JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); + JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); + assertTrue("different nested JSONObjects should not be similar", + !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); + + String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; + String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; + JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); + JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); + assertTrue("different nested JSONArrays should not be similar", + !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); + } + + @Test + public void jsonObjectToString() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + String toStr = jsonObject.toString(); + JSONObject expectedJsonObject = new JSONObject(toStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void jsonObjectToStringSuppressWarningOnCastToMap() { + JSONObject jsonObject = new JSONObject(); + Map map = new HashMap(); + map.put("abc", "def"); + jsonObject.put("key", map); + String toStr = jsonObject.toString(); + JSONObject expectedJsonObject = new JSONObject(toStr); + assertTrue("keys should be equal", + jsonObject.keySet().iterator().next().equals( + expectedJsonObject.keySet().iterator().next())); + /** + * Can't do a Util compare because although they look the same + * in the debugger, one is a map and the other is a JSONObject. + */ + // TODO: fix warnings + map = (Map)jsonObject.get("key"); + JSONObject mapJsonObject = expectedJsonObject.getJSONObject("key"); + assertTrue("value size should be equal", + map.size() == mapJsonObject.length() && map.size() == 1); + assertTrue("keys should be equal for key: "+map.keySet().iterator().next(), + mapJsonObject.keys().next().equals(map.keySet().iterator().next())); + assertTrue("values should be equal for key: "+map.keySet().iterator().next(), + mapJsonObject.get(mapJsonObject.keys().next()).toString().equals( + map.get(map.keySet().iterator().next()))); + } + + @Test + public void jsonObjectToStringSuppressWarningOnCastToCollection() { + JSONObject jsonObject = new JSONObject(); + Collection collection = new ArrayList(); + collection.add("abc"); + // ArrayList will be added as an object + jsonObject.put("key", collection); + String toStr = jsonObject.toString(); + // [abc] will be added as a JSONArray + JSONObject expectedJsonObject = new JSONObject(toStr); + /** + * Can't do a Util compare because although they look the same + * in the debugger, one is a collection and the other is a JSONArray. + */ + assertTrue("keys should be equal", + jsonObject.keySet().iterator().next().equals( + expectedJsonObject.keySet().iterator().next())); + // TODO: fix warnings + collection = (Collection)jsonObject.get("key"); + JSONArray jsonArray = expectedJsonObject.getJSONArray("key"); + assertTrue("value size should be equal", + collection.size() == jsonArray.length()); + Iterator it = collection.iterator(); + for (int i = 0; i < collection.size(); ++i) { + assertTrue("items should be equal for index: "+i, + jsonArray.get(i).toString().equals(it.next().toString())); + } + } + + @Test + public void valueToString() { + + assertTrue("null valueToString() incorrect", + "null".equals(JSONObject.valueToString(null))); + MyJsonString jsonString = new MyJsonString(); + assertTrue("jsonstring valueToString() incorrect", + "my string".equals(JSONObject.valueToString(jsonString))); + assertTrue("boolean valueToString() incorrect", + "true".equals(JSONObject.valueToString(Boolean.TRUE))); + assertTrue("non-numeric double", + "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); + String jsonObjectStr = + "{"+ + "\"key1\":\"val1\","+ + "\"key2\":\"val2\","+ + "\"key3\":\"val3\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("jsonObject valueToString() incorrect", + JSONObject.valueToString(jsonObject).equals(jsonObject.toString())); + String jsonArrayStr = + "[1,2,3]"; + JSONArray jsonArray = new JSONArray(jsonArrayStr); + assertTrue("jsonArra valueToString() incorrect", + JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); + Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + assertTrue("map valueToString() incorrect", + jsonObject.toString().equals(JSONObject.valueToString(map))); + Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + assertTrue("collection valueToString() expected: "+ + jsonArray.toString()+ " actual: "+ + JSONObject.valueToString(collection), + jsonArray.toString().equals(JSONObject.valueToString(collection))); + Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; + assertTrue("array valueToString() incorrect", + jsonArray.toString().equals(JSONObject.valueToString(array))); + } + + @Test + public void wrapObject() { + // wrap(null) returns NULL + assertTrue("null wrap() incorrect", + JSONObject.NULL == JSONObject.wrap(null)); + + // wrap(Integer) returns Integer + Integer in = new Integer(1); + assertTrue("Integer wrap() incorrect", + in == JSONObject.wrap(in)); + + // wrap JSONObject returns JSONObject + String jsonObjectStr = + "{"+ + "\"key1\":\"val1\","+ + "\"key2\":\"val2\","+ + "\"key3\":\"val3\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("JSONObject wrap() incorrect", + jsonObject == JSONObject.wrap(jsonObject)); + + // wrap collection returns JSONArray + Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + JSONArray jsonArray = (JSONArray)(JSONObject.wrap(collection)); + String expectedCollectionJsonArrayStr = + "[1,2,3]"; + JSONArray expectedCollectionJsonArray = + new JSONArray(expectedCollectionJsonArrayStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, + expectedCollectionJsonArray); + + // wrap Array returns JSONArray + Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; + JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); + JSONArray expectedIntegerArrayJsonArray = new JSONArray("[1,2,3]"); + Util.compareActualVsExpectedJsonArrays(integerArrayJsonArray, + expectedIntegerArrayJsonArray); + + // wrap map returns JSONObject + Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + JSONObject mapJsonObject = (JSONObject)(JSONObject.wrap(map)); + Util.compareActualVsExpectedJsonObjects(jsonObject, mapJsonObject); + + // TODO test wrap(package) + } + + @Test + public void jsonObjectParsingErrors() { + int tryCount = 0; + int exceptionCount = 0; + try { + // does not start with '{' + ++tryCount; + String str = "abc"; + new JSONObject(str); + } catch (JSONException ignore) {++exceptionCount; } + try { + // does not end with '}' + ++tryCount; + String str = "{"; + new JSONObject(str); + } catch (JSONException ignore) {++exceptionCount; } + try { + // key with no ':' + ++tryCount; + String str = "{\"myKey\" = true}"; + new JSONObject(str); + } catch (JSONException ignore) {++exceptionCount; } + try { + // entries with no ',' separator + ++tryCount; + String str = "{\"myKey\":true \"myOtherKey\":false}"; + new JSONObject(str); + } catch (JSONException ignore) {++exceptionCount; } + try { + // append to wrong key + ++tryCount; + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.append("myKey", "hello"); + } catch (JSONException ignore) {++exceptionCount; } + try { + // increment wrong key + ++tryCount; + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("myKey"); + } catch (JSONException ignore) {++exceptionCount; } + try { + // invalid key + ++tryCount; + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.get(null); + } catch (JSONException ignore) {++exceptionCount; } + try { + // invalid numberToString() + ++tryCount; + JSONObject.numberToString((Number)null); + } catch (JSONException ignore) {++exceptionCount; } + try { + // null put key + ++tryCount; + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0); + } catch (NullPointerException ignore) {++exceptionCount; } + try { + // multiple putOnce key + ++tryCount; + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.putOnce("hello", "world"); + jsonObject.putOnce("hello", "world!"); + } catch (JSONException ignore) {++exceptionCount; } + try { + // test validity of invalid double + ++tryCount; + JSONObject.testValidity(Double.NaN); + } catch (JSONException ignore) {++exceptionCount; } + try { + // test validity of invalid float + ++tryCount; + JSONObject.testValidity(Float.NEGATIVE_INFINITY); + } catch (JSONException ignore) {++exceptionCount; } + + assertTrue("all tries should have failed", + exceptionCount == tryCount); + } + + @Test + public void jsonObjectOptDefault() { + + String str = "{\"myKey\": \"myval\"}"; + JSONObject jsonObject = new JSONObject(str); + + assertTrue("optBoolean() should return default boolean", + Boolean.TRUE == jsonObject.optBoolean("myKey", Boolean.TRUE)); + assertTrue("optInt() should return default int", + 42 == jsonObject.optInt("myKey", 42)); + assertTrue("optInt() should return default int", + 42 == jsonObject.optInt("myKey", 42)); + assertTrue("optLong() should return default long", + 42 == jsonObject.optLong("myKey", 42)); + assertTrue("optDouble() should return default double", + 42.3 == jsonObject.optDouble("myKey", 42.3)); + assertTrue("optString() should return default string", + "hi".equals(jsonObject.optString("hiKey", "hi"))); + } + + @Test + public void jsonObjectputNull() { + + // put null should remove the item. + String str = "{\"myKey\": \"myval\"}"; + JSONObject jsonObjectRemove = new JSONObject(str); + JSONObject jsonObjectPutNull = new JSONObject(str); + jsonObjectRemove.remove("myKey"); + jsonObjectPutNull.put("myKey", (Object)null); + Util.compareActualVsExpectedJsonObjects(jsonObjectRemove, jsonObjectPutNull); + assertTrue("jsonObject should be empty", + jsonObjectRemove.length() == 0 && + jsonObjectPutNull.length() == 0); + } + + @Test + public void jsonObjectQuote() { + String str; + str = ""; + String quotedStr; + quotedStr = JSONObject.quote(str); + assertTrue("quote() expected escaped quotes, found "+quotedStr, + "\"\"".equals(quotedStr)); + str = "\"\""; + quotedStr = JSONObject.quote(str); + assertTrue("quote() expected escaped quotes, found "+quotedStr, + "\"\\\"\\\"\"".equals(quotedStr)); + str = " Date: Thu, 7 May 2015 23:04:26 -0500 Subject: [PATCH 106/451] More trickery from the bean --- MyBean.java | 57 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/MyBean.java b/MyBean.java index 6477fde..1b9e6f0 100644 --- a/MyBean.java +++ b/MyBean.java @@ -1,13 +1,26 @@ package org.json.junit; -public class MyBean { - public int intKey; - public double doubleKey; - public String stringKey; - public String complexStringKey; - public boolean trueKey; - public boolean falseKey; +import java.io.*; +// bean must be serializable +public class MyBean implements Serializable { + // bean properties should be private + private static final long serialVersionUID = 1L; + private int intKey; + private double doubleKey; + private String stringKey; + private String complexStringKey; + private boolean trueKey; + private boolean falseKey; + + /** + * Throw in a few public properties in order to test building + * from an Object. + */ + public String publicStr; + public int publicInt; + + // bean needs a default ctor public MyBean() { intKey = 42; doubleKey = -23.45e7; @@ -15,7 +28,12 @@ public class MyBean { complexStringKey = "h\be\tllo w\u1234orld!"; trueKey = true; falseKey = false; + + publicStr = "abc"; + publicInt = 42; } + + // need getters, but don't need setters public int getIntKey() { return intKey; } @@ -34,4 +52,29 @@ public class MyBean { public boolean isFalseKey() { return falseKey; } + + /** + * Just a random invalid JSON getter, not even backed up by a property + */ + public StringReader getStringReaderKey() { + return (new StringReader("") { + /** + * TODO: Need to understand why returning a string + * turns this into an empty JSONObject, + * but not overriding turns this into a string. + */ + @Override + public String toString(){ + return "Whatever"; + } + }); + } + // bean hashcode is recommended + public int hashCode() { + return super.hashCode(); + } + // bean equals is recommended + public boolean equals(Object obj) { + return super.equals(obj); + } } From fcb8048038a31bc9683d777d36c0ef3c114a44fd Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 7 May 2015 23:04:44 -0500 Subject: [PATCH 107/451] deepened the testing a little bit, slow going --- JSONObjectTest.java | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 1aa19d7..6ef9b02 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -85,7 +85,6 @@ public class JSONObjectTest { /** * JSONObjects can be built from a Map. * In this test all of the map entries are valid JSON types. - * TODO: test with map values that are not valid JSON types */ String expectedStr = "{"+ @@ -109,6 +108,28 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + @Test + public void jsonObjectByMapWithUnsupportedValues() { + /** + * JSONObjects can be built from a Map. + * In this test the map entries are not valid JSON types. + * The actual conversion is kind of interesting. + */ + String expectedStr = + "{"+ + "\"key1\":{},"+ + "\"key2\":\"java.lang.Exception\""+ + "}"; + Map jsonMap = new HashMap(); + // Just insert some random objects + jsonMap.put("key1", new CDL()); + jsonMap.put("key2", new Exception()); + + JSONObject jsonObject = new JSONObject(jsonMap); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + @Test public void jsonObjectByMapWithNullValue() { /** @@ -151,9 +172,8 @@ public class JSONObjectTest { @Test public void jsonObjectByBean() { /** - * JSONObject built from a bean. In this case all of the - * bean properties are valid JSON types - * TODO: test with bean fields that are not valid JSON types + * JSONObject built from a bean. In this case all but one of the + * bean getters return valid JSON types */ String expectedStr = "{"+ @@ -162,7 +182,8 @@ public class JSONObjectTest { "\"stringKey\":\"hello world!\","+ "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ "\"intKey\":42,"+ - "\"doubleKey\":-23.45e7"+ + "\"doubleKey\":-23.45e7,"+ + "\"stringReaderKey\":{}"+ "}"; MyBean myBean = new MyBean(); JSONObject jsonObject = new JSONObject(myBean); From fb36918d854d5561d90bb8728ef1698bc545f42f Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 8 May 2015 23:30:41 -0500 Subject: [PATCH 108/451] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index d91f7c2..64c0014 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,10 @@ https://github.com/douglascrockford/JSON-java
*These tests are a work in progress. Help from interested developers is welcome.*
More coverage is needed, but more importantly, improvements to test quality is needed.
+You will need the following libraries for testing: Test harness: http://junit.org
Coverage: http://www.eclemma.org/
+Mockery: https://github.com/mockito/mockito Eclipse is the recommended development environment. Run individual tests or JunitTestSuite using *EclEmma Coverage*, or execute the TestRunner application directly.
From 0a995318e7faad8835d11ad73f47004bcbff3d64 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 9 May 2015 15:24:21 -0500 Subject: [PATCH 109/451] Delete MyBean.java --- MyBean.java | 80 ----------------------------------------------------- 1 file changed, 80 deletions(-) delete mode 100644 MyBean.java diff --git a/MyBean.java b/MyBean.java deleted file mode 100644 index 1b9e6f0..0000000 --- a/MyBean.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.json.junit; - -import java.io.*; - -// bean must be serializable -public class MyBean implements Serializable { - // bean properties should be private - private static final long serialVersionUID = 1L; - private int intKey; - private double doubleKey; - private String stringKey; - private String complexStringKey; - private boolean trueKey; - private boolean falseKey; - - /** - * Throw in a few public properties in order to test building - * from an Object. - */ - public String publicStr; - public int publicInt; - - // bean needs a default ctor - public MyBean() { - intKey = 42; - doubleKey = -23.45e7; - stringKey = "hello world!"; - complexStringKey = "h\be\tllo w\u1234orld!"; - trueKey = true; - falseKey = false; - - publicStr = "abc"; - publicInt = 42; - } - - // need getters, but don't need setters - public int getIntKey() { - return intKey; - } - public double getDoubleKey() { - return doubleKey; - } - public String getStringKey() { - return stringKey; - } - public String getComplexStringKey() { - return complexStringKey; - } - public boolean isTrueKey() { - return trueKey; - } - public boolean isFalseKey() { - return falseKey; - } - - /** - * Just a random invalid JSON getter, not even backed up by a property - */ - public StringReader getStringReaderKey() { - return (new StringReader("") { - /** - * TODO: Need to understand why returning a string - * turns this into an empty JSONObject, - * but not overriding turns this into a string. - */ - @Override - public String toString(){ - return "Whatever"; - } - }); - } - // bean hashcode is recommended - public int hashCode() { - return super.hashCode(); - } - // bean equals is recommended - public boolean equals(Object obj) { - return super.equals(obj); - } -} From f2ef541c2d62441d1b90febedf15209ec6053bc4 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 9 May 2015 15:25:06 -0500 Subject: [PATCH 110/451] still in progress, 94% coverage --- JSONObjectTest.java | 119 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 98 insertions(+), 21 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 6ef9b02..1903543 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -1,6 +1,7 @@ package org.json.junit; import static org.junit.Assert.*; +import static org.mockito.Mockito.*; import java.io.*; import java.util.*; @@ -8,13 +9,26 @@ import java.util.*; import org.json.*; import org.junit.*; +/** + * These classes will be used for testing + */ class MyJsonString implements JSONString { @Override public String toJSONString() { return "my string"; } -} +}; + +interface MyBean { + public Integer getIntKey(); + public Double getDoubleKey(); + public String getStringKey(); + public String getEscapeStringKey(); + public Boolean isTrueKey(); + public Boolean isFalseKey(); + public StringReader getStringReaderKey(); +}; /** * JSONObject, along with JSONArray, are the central classes of the reference app. @@ -22,6 +36,13 @@ class MyJsonString implements JSONString { * impossible without it. */ public class JSONObjectTest { + /** + * Need a class with some public data members for testing, so + * JSONObjectTest is chosen. + */ + public Integer publicInt = 42; + public String publicString = "abc"; + @Test public void emptyJsonObject() { @@ -45,7 +66,7 @@ public class JSONObjectTest { "\"falseKey\":false,"+ "\"nullKey\":null,"+ "\"stringKey\":\"hello world!\","+ - "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ "\"intKey\":42,"+ "\"doubleKey\":-23.45e67"+ "}"; @@ -91,7 +112,7 @@ public class JSONObjectTest { "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ - "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ "\"intKey\":42,"+ "\"doubleKey\":-23.45e67"+ "}"; @@ -99,7 +120,7 @@ public class JSONObjectTest { jsonMap.put("trueKey", new Boolean(true)); jsonMap.put("falseKey", new Boolean(false)); jsonMap.put("stringKey", "hello world!"); - jsonMap.put("complexStringKey", "h\be\tllo w\u1234orld!"); + jsonMap.put("escapeStringKey", "h\be\tllo w\u1234orld!"); jsonMap.put("intKey", new Long(42)); jsonMap.put("doubleKey", new Double(-23.45e67)); @@ -141,7 +162,7 @@ public class JSONObjectTest { "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ - "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ "\"intKey\":42,"+ "\"doubleKey\":-23.45e67"+ "}"; @@ -150,7 +171,7 @@ public class JSONObjectTest { jsonMap.put("falseKey", new Boolean(false)); jsonMap.put("stringKey", "hello world!"); jsonMap.put("nullKey", null); - jsonMap.put("complexStringKey", "h\be\tllo w\u1234orld!"); + jsonMap.put("escapeStringKey", "h\be\tllo w\u1234orld!"); jsonMap.put("intKey", new Long(42)); jsonMap.put("doubleKey", new Double(-23.45e67)); @@ -180,12 +201,37 @@ public class JSONObjectTest { "\"trueKey\":true,"+ "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ - "\"complexStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ "\"intKey\":42,"+ "\"doubleKey\":-23.45e7,"+ - "\"stringReaderKey\":{}"+ + "\"stringReaderKey\":{},"+ + "\"callbacks\":[{\"handler\":{}},{}]"+ // sorry, mockito artifact "}"; - MyBean myBean = new MyBean(); + + /** + * Default access classes have to be mocked since JSONObject, which is + * not in the same package, cannot call MyBean methods by reflection. + */ + MyBean myBean = mock(MyBean.class); + when(myBean.getDoubleKey()).thenReturn(-23.45e7); + when(myBean.getIntKey()).thenReturn(42); + when(myBean.getStringKey()).thenReturn("hello world!"); + when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!"); + when(myBean.isTrueKey()).thenReturn(true); + when(myBean.isFalseKey()).thenReturn(false); + when(myBean.getStringReaderKey()).thenReturn( + new StringReader("") { + /** + * TODO: Need to understand why returning a string + * turns "this" into an empty JSONObject, + * but not overriding turns "this" into a string. + */ + @Override + public String toString(){ + return "Whatever"; + } + }); + JSONObject jsonObject = new JSONObject(myBean); JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); @@ -201,21 +247,20 @@ public class JSONObjectTest { */ String expectedStr = "{"+ - "\"publicStr\":\"abc\","+ + "\"publicString\":\"abc\","+ "\"publicInt\":42"+ "}"; - String[] keys = {"publicStr", "publicInt"}; - - MyBean myBean = new MyBean(); - JSONObject jsonObject = new JSONObject(myBean, keys); + String[] keys = {"publicString", "publicInt"}; + // just need a class that has public data members + JSONObjectTest jsonObjectTest = new JSONObjectTest(); + JSONObject jsonObject = new JSONObject(jsonObjectTest, keys); JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } - // this is where I left off - @Test public void jsonObjectByResourceBundle() { + // TODO: how to improve resource bundle testing? String expectedStr = "{"+ "\"greetings\": {"+ @@ -236,6 +281,7 @@ public class JSONObjectTest { @Test public void jsonObjectAccumulate() { + // TODO: should include an unsupported object String expectedStr = "{"+ "\"myArray\": ["+ @@ -260,6 +306,7 @@ public class JSONObjectTest { @Test public void jsonObjectAppend() { + // TODO: should include an unsupported object String expectedStr = "{"+ "\"myArray\": ["+ @@ -284,8 +331,9 @@ public class JSONObjectTest { @Test public void jsonObjectDoubleToString() { - String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68" }; - Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67 }; + String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; + Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, + Double.NaN, Double.NEGATIVE_INFINITY }; for (int i = 0; i < expectedStrs.length; ++i) { String actualStr = JSONObject.doubleToString(doubles[i]); assertTrue("value expected ["+expectedStrs[i]+ @@ -368,6 +416,8 @@ public class JSONObjectTest { jsonObjectInner.get("myKey").equals("myVal")); } + // improving unit tests left off here + @Test public void jsonObjectNonAndWrongValues() { String str = @@ -479,6 +529,13 @@ public class JSONObjectTest { Util.compareActualVsExpectedStringArrays(names, expectedNames); } + @Test + public void emptyJsonObjectNamesToJsonAray() { + JSONObject jsonObject = new JSONObject(); + JSONArray jsonArray = jsonObject.names(); + assertTrue("jsonArray should be null", jsonArray == null); + } + @Test public void jsonObjectNamesToJsonAray() { String str = @@ -512,9 +569,9 @@ public class JSONObjectTest { * method getNames(), this particular bean needs some public * data members, which have been added to the class. */ - MyBean myBean = new MyBean(); - String [] expectedNames = {"publicStr", "publicInt"}; - String [] names = JSONObject.getNames(myBean); + JSONObjectTest jsonObjectTest = new JSONObjectTest(); + String [] expectedNames = {"publicString", "publicInt"}; + String [] names = JSONObject.getNames(jsonObjectTest); Util.compareActualVsExpectedStringArrays(names, expectedNames); } @@ -530,6 +587,8 @@ public class JSONObjectTest { "\"keyInt\":3,"+ "\"keyLong\":9999999993,"+ "\"keyDouble\":3.1,"+ + // TODO: not sure if this will work on other platforms + "\"keyFloat\":3.0999999046325684,"+ "}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("keyInt"); @@ -539,10 +598,20 @@ public class JSONObjectTest { jsonObject.increment("keyInt"); jsonObject.increment("keyLong"); jsonObject.increment("keyDouble"); + jsonObject.put("keyFloat", new Float(1.1)); + jsonObject.increment("keyFloat"); + jsonObject.increment("keyFloat"); JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + @Test + public void emptyJsonObjectNamesToArray() { + JSONObject jsonObject = new JSONObject(); + String [] names = JSONObject.getNames(jsonObject); + assertTrue("names should be null", names == null); + } + @Test public void jsonObjectNamesToArray() { String str = @@ -905,6 +974,13 @@ public class JSONObjectTest { exceptionCount == tryCount); } + @Test + public void jsonObjectPutOnceNull() { + JSONObject jsonObject = new JSONObject(); + jsonObject.putOnce(null, null); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + @Test public void jsonObjectOptDefault() { @@ -1014,3 +1090,4 @@ public class JSONObjectTest { } } + From a9dd8e7b1d8547c3ba46e13d75443c2920c486e8 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 9 May 2015 15:26:15 -0500 Subject: [PATCH 111/451] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 64c0014..18c20d0 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,6 @@ A unit test has the following stages: | Files used in test | | ------------- | | JunitTestSuite.java | -| MyBean.java | | StringsResourceBundle.java | |TestRunner.java | | Util.java | From 327c0e177eb0d593d49063a656c840f25d8c4693 Mon Sep 17 00:00:00 2001 From: dieter Date: Fri, 22 May 2015 12:47:28 +0200 Subject: [PATCH 112/451] Playing numbers --- JSONObjectTest.java | 94 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 92 insertions(+), 2 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 1903543..ed3f374 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -2,10 +2,10 @@ package org.json.junit; import static org.junit.Assert.*; import static org.mockito.Mockito.*; - import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; import java.util.*; - import org.json.*; import org.junit.*; @@ -418,6 +418,91 @@ public class JSONObjectTest { // improving unit tests left off here + @Test + public void stringToValueNumbersTest() { + // Check if library handles large or high precision numbers correctly + assertTrue( "0.2 should be a Double!", + JSONObject.stringToValue( "0.2" ) instanceof Double ); + assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", + JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double ); + assertTrue( "299792.457999999984 should be a BigDecimal!", + JSONObject.stringToValue( "299792.457999999984" ) instanceof BigDecimal ); + assertTrue( "1 should be an Integer!", + JSONObject.stringToValue( "1" ) instanceof Integer ); + assertTrue( "Integer.MAX_VALUE should still be an Integer!", + JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); + assertTrue( "Large integers should be a Long!", + JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); + assertTrue( "Long.MAX_VALUE should still be an Integer!", + JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); + assertTrue( "Really large integers should be a BigInteger!", + JSONObject.stringToValue( + new BigInteger( new Long( Long.MAX_VALUE ).toString() ) + .add( BigInteger.ONE ).toString() ) instanceof BigInteger ); + } + + @Test + public void jsonValidNumberValuesNeitherLongNorIEE754Compatible() { + // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects + String str = + "{"+ + "\"someNumber\":299792.457999999984,"+ + "\"largeNumber\":12345678901234567890,"+ + "\"preciseNumber\":0.2000000000000000111,"+ + "\"largeExponent\":-23.45e2327"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + assertFalse( "someNumber certainly was not 299792.458!", + jsonObject.get( "someNumber" ).equals( new Double( "299792.458" ) ) ); + assertTrue( "someNumber must be a number", + jsonObject.get( "someNumber" ) instanceof Number ); + assertTrue( "largeNumber must be a number", + jsonObject.get( "largeNumber" ) instanceof Number ); + assertTrue( "preciseNumber must be a number", + jsonObject.get( "preciseNumber" ) instanceof Number ); + assertTrue( "largeExponent must be a number", + jsonObject.get( "largeExponent" ) instanceof Number ); + } + + @Test + public void jsonInvalidNumberValues() { + // Number-notations supported by Java and invalid as JSON + String str = + "{"+ + "\"hexNumber\":-0x123,"+ + "\"tooManyZeros\":00,"+ + "\"negativeInfinite\":-Infinity,"+ + "\"negativeNaN\":-NaN,"+ + "\"negativeFraction\":-.01,"+ + "\"tooManyZerosFraction\":00.001,"+ + "\"negativeHexFloat\":-0x1.fffp1,"+ + "\"hexFloat\":0x1.0P-1074,"+ + "\"floatIdentifier\":0.1f,"+ + "\"doubleIdentifier\":0.1d,"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + assertFalse( "hexNumber must not be a number (should throw exception!?)", + jsonObject.get( "hexNumber" ) instanceof Number ); + assertFalse( "tooManyZeros must not be a number (should throw exception!?)", + jsonObject.get( "tooManyZeros" ) instanceof Number ); + assertFalse( "negativeInfinite must not be a number (should throw exception!?)", + jsonObject.get( "negativeInfinite" ) instanceof Number ); + assertFalse( "negativeNaN must not be a number (should throw exception!?)", + jsonObject.get( "negativeNaN" ) instanceof Number ); + assertFalse( "tooManyZerosFraction must not be a number (should throw exception!?)", + jsonObject.get( "tooManyZerosFraction" ) instanceof Number ); + assertFalse( "negativeFraction must not be a number (should throw exception!?)", + jsonObject.get( "negativeFraction" ) instanceof Number ); + assertFalse( "negativeHexFloat must not be a number (should throw exception!?)", + jsonObject.get( "negativeHexFloat" ) instanceof Number ); + assertFalse( "hexFloat must not be a number (should throw exception!?)", + jsonObject.get( "hexFloat" ) instanceof Number ); + assertFalse( "floatIdentifier must not be a number (should throw exception!?)", + jsonObject.get( "floatIdentifier" ) instanceof Number ); + assertFalse( "doubleIdentifier must not be a number (should throw exception!?)", + jsonObject.get( "doubleIdentifier" ) instanceof Number ); + } + @Test public void jsonObjectNonAndWrongValues() { String str = @@ -850,6 +935,11 @@ public class JSONObjectTest { assertTrue("Integer wrap() incorrect", in == JSONObject.wrap(in)); + // wrap(BigDecimal) returns BigDecimal + BigDecimal bd = BigDecimal.ONE; + assertTrue("BigDecimal wrap() incorrect", + bd == JSONObject.wrap(bd)); + // wrap JSONObject returns JSONObject String jsonObjectStr = "{"+ From 60e84bff922ab6022a3cfbd9e5ddb0c420efe6b0 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 24 May 2015 23:36:48 -0500 Subject: [PATCH 113/451] fix so numeric behavior is documented but tests succeed --- JSONObjectTest.java | 107 +++++++++++++++++++++++++++----------------- 1 file changed, 66 insertions(+), 41 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index ed3f374..de36c01 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -419,14 +419,19 @@ public class JSONObjectTest { // improving unit tests left off here @Test + public void stringToValueNumbersTest() { // Check if library handles large or high precision numbers correctly assertTrue( "0.2 should be a Double!", JSONObject.stringToValue( "0.2" ) instanceof Double ); assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double ); - assertTrue( "299792.457999999984 should be a BigDecimal!", - JSONObject.stringToValue( "299792.457999999984" ) instanceof BigDecimal ); + /** + * This test documents a need for BigDecimal conversion. + */ + Object obj = JSONObject.stringToValue( "299792.457999999984" ); + assertTrue( "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!", + obj.equals(new Double(299792.458)) ); assertTrue( "1 should be an Integer!", JSONObject.stringToValue( "1" ) instanceof Integer ); assertTrue( "Integer.MAX_VALUE should still be an Integer!", @@ -435,35 +440,45 @@ public class JSONObjectTest { JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); assertTrue( "Long.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); - assertTrue( "Really large integers should be a BigInteger!", - JSONObject.stringToValue( - new BigInteger( new Long( Long.MAX_VALUE ).toString() ) - .add( BigInteger.ONE ).toString() ) instanceof BigInteger ); + + String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString(); + assertTrue( "Really large integers currently evaluate to string", + JSONObject.stringToValue(str).equals("9223372036854775808")); } @Test - public void jsonValidNumberValuesNeitherLongNorIEE754Compatible() { + /** + * This test documents numeric values which could be numerically + * handled as BigDecimal or BigInteger. It helps determine what outputs + * will change if those types are supported. + */ + public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects String str = "{"+ - "\"someNumber\":299792.457999999984,"+ + "\"numberWithDecimals\":299792.457999999984,"+ "\"largeNumber\":12345678901234567890,"+ "\"preciseNumber\":0.2000000000000000111,"+ "\"largeExponent\":-23.45e2327"+ "}"; JSONObject jsonObject = new JSONObject(str); - assertFalse( "someNumber certainly was not 299792.458!", - jsonObject.get( "someNumber" ).equals( new Double( "299792.458" ) ) ); - assertTrue( "someNumber must be a number", - jsonObject.get( "someNumber" ) instanceof Number ); - assertTrue( "largeNumber must be a number", - jsonObject.get( "largeNumber" ) instanceof Number ); - assertTrue( "preciseNumber must be a number", - jsonObject.get( "preciseNumber" ) instanceof Number ); - assertTrue( "largeExponent must be a number", - jsonObject.get( "largeExponent" ) instanceof Number ); + // Comes back as a double, but loses precision + assertTrue( "numberWithDecimals currently evaluates to double 299792.458", + jsonObject.get( "numberWithDecimals" ).equals( new Double( "299792.458" ) ) ); + Object obj = jsonObject.get( "largeNumber" ); + assertTrue("largeNumber currently evaluates to string", + "12345678901234567890".equals(obj)); + // comes back as a double but loses precision + assertTrue( "preciseNumber currently evaluates to double 0.2", + jsonObject.get( "preciseNumber" ).equals(new Double(0.2))); + obj = jsonObject.get( "largeExponent" ); + assertTrue("largeExponent should currently evaluates as a string", + "-23.45e2327".equals(obj)); } + /** + * This test documents how JSON-Java handles invalid numeric input. + */ @Test public void jsonInvalidNumberValues() { // Number-notations supported by Java and invalid as JSON @@ -481,26 +496,32 @@ public class JSONObjectTest { "\"doubleIdentifier\":0.1d,"+ "}"; JSONObject jsonObject = new JSONObject(str); + Object obj; + obj = jsonObject.get( "hexNumber" ); assertFalse( "hexNumber must not be a number (should throw exception!?)", - jsonObject.get( "hexNumber" ) instanceof Number ); - assertFalse( "tooManyZeros must not be a number (should throw exception!?)", - jsonObject.get( "tooManyZeros" ) instanceof Number ); - assertFalse( "negativeInfinite must not be a number (should throw exception!?)", - jsonObject.get( "negativeInfinite" ) instanceof Number ); - assertFalse( "negativeNaN must not be a number (should throw exception!?)", - jsonObject.get( "negativeNaN" ) instanceof Number ); - assertFalse( "tooManyZerosFraction must not be a number (should throw exception!?)", - jsonObject.get( "tooManyZerosFraction" ) instanceof Number ); - assertFalse( "negativeFraction must not be a number (should throw exception!?)", - jsonObject.get( "negativeFraction" ) instanceof Number ); - assertFalse( "negativeHexFloat must not be a number (should throw exception!?)", - jsonObject.get( "negativeHexFloat" ) instanceof Number ); - assertFalse( "hexFloat must not be a number (should throw exception!?)", - jsonObject.get( "hexFloat" ) instanceof Number ); - assertFalse( "floatIdentifier must not be a number (should throw exception!?)", - jsonObject.get( "floatIdentifier" ) instanceof Number ); - assertFalse( "doubleIdentifier must not be a number (should throw exception!?)", - jsonObject.get( "doubleIdentifier" ) instanceof Number ); + obj instanceof Number ); + assertTrue("hexNumber currently evaluates to string", + obj.equals("-0x123")); + assertTrue( "tooManyZeros currently evaluates to string", + jsonObject.get( "tooManyZeros" ).equals("00")); + obj = jsonObject.get("negativeInfinite"); + assertTrue( "negativeInfinite currently evaluates to string", + obj.equals("-Infinity")); + obj = jsonObject.get("negativeNaN"); + assertTrue( "negativeNaN currently evaluates to string", + obj.equals("-NaN")); + assertTrue( "negativeFraction currently evaluates to double -0.01", + jsonObject.get( "negativeFraction" ).equals(new Double(-0.01))); + assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", + jsonObject.get( "tooManyZerosFraction" ).equals(new Double(0.001))); + assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875", + jsonObject.get( "negativeHexFloat" ).equals(new Double(-3.99951171875))); + assertTrue("hexFloat currently evaluates to double 4.9E-324", + jsonObject.get("hexFloat").equals(new Double(4.9E-324))); + assertTrue("floatIdentifier currently evaluates to double 0.1", + jsonObject.get("floatIdentifier").equals(new Double(0.1))); + assertTrue("doubleIdentifier currently evaluates to double 0.1", + jsonObject.get("doubleIdentifier").equals(new Double(0.1))); } @Test @@ -935,10 +956,14 @@ public class JSONObjectTest { assertTrue("Integer wrap() incorrect", in == JSONObject.wrap(in)); - // wrap(BigDecimal) returns BigDecimal - BigDecimal bd = BigDecimal.ONE; - assertTrue("BigDecimal wrap() incorrect", - bd == JSONObject.wrap(bd)); + /** + * This test is to document the preferred behavior if BigDecimal is + * supported. At the present time, bd returns as a string, since it + * is recognized as being a Java package class. + */ + Object bdWrap = JSONObject.wrap(BigDecimal.ONE); + assertTrue("BigDecimal.ONE currently evaluates to string", + bdWrap.equals("1")); // wrap JSONObject returns JSONObject String jsonObjectStr = From 88756c04908d5137bf570e2c399587e222169f92 Mon Sep 17 00:00:00 2001 From: dieter Date: Wed, 27 May 2015 15:51:30 +0200 Subject: [PATCH 114/451] Hidden typecast for Float objects in JSONobject.increment(String key) --- JSONObjectTest.java | 60 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index de36c01..c02ebd1 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -493,7 +493,7 @@ public class JSONObjectTest { "\"negativeHexFloat\":-0x1.fffp1,"+ "\"hexFloat\":0x1.0P-1074,"+ "\"floatIdentifier\":0.1f,"+ - "\"doubleIdentifier\":0.1d,"+ + "\"doubleIdentifier\":0.1d"+ "}"; JSONObject jsonObject = new JSONObject(str); Object obj; @@ -694,6 +694,17 @@ public class JSONObjectTest { "\"keyLong\":9999999993,"+ "\"keyDouble\":3.1,"+ // TODO: not sure if this will work on other platforms + + // Should work the same way on any platform, this the effect of a float to double conversion and happens because + // java type-casts float to double. A 32 bit float is type-casted to 64 bit double by simply appending zero-bits to the + // mantissa (and extended the signed exponent by 3 bits.) + + // Like 1/3 cannot be represented as base10 number because it is periodically, 1/5 cannot be represented as base2 number + // since it is periodically in base2 (take a look at http://www.h-schmidt.net/FloatConverter/) + // The same happens to 3.1, that decimal number (base10 representation) is periodic in base2 representation, therefore + // appending zero-bits is inaccurate only repeating the periodically repeating bits (0110) would be a proper conversion. + // However one cannot detect from a 32 bit IEE754 representation which bits would "repeat infinitely", since the missing + // bits would not fit into the 32 bit float, i.e. the information needed is not there! ;) "\"keyFloat\":3.0999999046325684,"+ "}"; JSONObject jsonObject = new JSONObject(str); @@ -709,6 +720,53 @@ public class JSONObjectTest { jsonObject.increment("keyFloat"); JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + /* + float f = 3.1f; + double df = (double) f; + double d = 3.1d; + System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f))); + System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(df))); + System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d))); + + - Float: + seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm + 1000000010001100110011001100110 + - Double + seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + 10000000 10001100110011001100110 + 100000000001000110011001100110011000000000000000000000000000000 + 100000000001000110011001100110011001100110011001100110011001101 + */ + assertTrue( "Correctly converting float to double via base10 (string) representation!", new Double( 3.1d ).equals( new Double( new Float( 3.1f ).toString() ) ) ); + + // Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject + JSONObject jo = new JSONObject(); + jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double + assertFalse( "The java-compiler did add some zero bits for you (probably unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); + + JSONObject inc = new JSONObject(); + inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) + assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); + inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! + // this.put(key, (Float) value + 1); + // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. + // 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects! + // 3. A float+float operation will be performed and results into a float primitive. + // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method + // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa + assertTrue( "JSONObject increment unexpected behaviour, Float will not stay Float!", jo.get( "bug" ) instanceof Float ); + // correct implementation (with change of behaviour) would be: + // this.put(key, new Float((Float) value + 1)); + // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not + // really in the the scope of a JSON-library (IMHO.) + + // Some more examples of well documented unexpeced "numbercrunching" ;) + assertTrue("Stumbled over explicitly type-casting float as double!", (double)0.2f == 0.2d ); + assertTrue("Stumbled over comparing float with double any implicit type-cast!", 0.2f == 0.2d ); + Double d1 = new Double( 1.1f ); + Double d2 = new Double( "1.1f" ); + assertTrue( "Stumbled again over implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); } @Test From fa79826f0c429cdfc3d060697c6790b7d4b31ee6 Mon Sep 17 00:00:00 2001 From: dieter Date: Wed, 27 May 2015 16:33:42 +0200 Subject: [PATCH 115/451] Better show what has to be expected and what goes wrong --- JSONObjectTest.java | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index c02ebd1..06f96e5 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -695,16 +695,19 @@ public class JSONObjectTest { "\"keyDouble\":3.1,"+ // TODO: not sure if this will work on other platforms - // Should work the same way on any platform, this the effect of a float to double conversion and happens because - // java type-casts float to double. A 32 bit float is type-casted to 64 bit double by simply appending zero-bits to the - // mantissa (and extended the signed exponent by 3 bits.) + // Should work the same way on any platform! @see https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 + // This is the effect of a float to double conversion and is inherent to the shortcomings of the IEEE 754 format, when + // converting 32-bit into double-precision 64-bit. + // Java type-casts float to double. A 32 bit float is type-casted to 64 bit double by simply appending zero-bits to the + // mantissa (and extended the signed exponent by 3 bits.) and there is no way to obtain more information than it is + // stored in the 32-bits float. - // Like 1/3 cannot be represented as base10 number because it is periodically, 1/5 cannot be represented as base2 number - // since it is periodically in base2 (take a look at http://www.h-schmidt.net/FloatConverter/) + // Like 1/3 cannot be represented as base10 number because it is periodically, 1/5 (for example) cannot be represented + // as base2 number since it is periodically in base2 (take a look at http://www.h-schmidt.net/FloatConverter/) // The same happens to 3.1, that decimal number (base10 representation) is periodic in base2 representation, therefore - // appending zero-bits is inaccurate only repeating the periodically repeating bits (0110) would be a proper conversion. + // appending zero-bits is inaccurate. Only repeating the periodically occuring bits (0110) would be a proper conversion. // However one cannot detect from a 32 bit IEE754 representation which bits would "repeat infinitely", since the missing - // bits would not fit into the 32 bit float, i.e. the information needed is not there! ;) + // bits would not fit into the 32 bit float, i.e. the information needed simply is not there! "\"keyFloat\":3.0999999046325684,"+ "}"; JSONObject jsonObject = new JSONObject(str); @@ -738,12 +741,19 @@ public class JSONObjectTest { 100000000001000110011001100110011000000000000000000000000000000 100000000001000110011001100110011001100110011001100110011001101 */ + // Examples of well documented but probably unexpected behavior in java / with 32-bit float to 64-bit float conversion. + assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d ); + assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d ); + Double d1 = new Double( 1.1f ); + Double d2 = new Double( "1.1f" ); + assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); + assertTrue( "Correctly converting float to double via base10 (string) representation!", new Double( 3.1d ).equals( new Double( new Float( 3.1f ).toString() ) ) ); // Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject JSONObject jo = new JSONObject(); jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double - assertFalse( "The java-compiler did add some zero bits for you (probably unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); + assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); JSONObject inc = new JSONObject(); inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) @@ -755,18 +765,12 @@ public class JSONObjectTest { // 3. A float+float operation will be performed and results into a float primitive. // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa - assertTrue( "JSONObject increment unexpected behaviour, Float will not stay Float!", jo.get( "bug" ) instanceof Float ); - // correct implementation (with change of behaviour) would be: + assertTrue( "JSONObject increment unexpected behavior, Float will not stay Float!", jo.get( "bug" ) instanceof Float ); + // correct implementation (with change of behavior) would be: // this.put(key, new Float((Float) value + 1)); // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not // really in the the scope of a JSON-library (IMHO.) - // Some more examples of well documented unexpeced "numbercrunching" ;) - assertTrue("Stumbled over explicitly type-casting float as double!", (double)0.2f == 0.2d ); - assertTrue("Stumbled over comparing float with double any implicit type-cast!", 0.2f == 0.2d ); - Double d1 = new Double( 1.1f ); - Double d2 = new Double( "1.1f" ); - assertTrue( "Stumbled again over implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); } @Test From 32ea7e0ba3f66fc542f0cbd66588cc3f4f2542df Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 28 May 2015 20:43:47 -0500 Subject: [PATCH 116/451] tests should succeed --- JSONObjectTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 06f96e5..e044c8c 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -765,7 +765,7 @@ public class JSONObjectTest { // 3. A float+float operation will be performed and results into a float primitive. // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa - assertTrue( "JSONObject increment unexpected behavior, Float will not stay Float!", jo.get( "bug" ) instanceof Float ); + assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Double ); // correct implementation (with change of behavior) would be: // this.put(key, new Float((Float) value + 1)); // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not From 6b03f1bbe745a8574ca8ca3d71b02e05c3b5a151 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 3 Jun 2015 22:50:08 -0500 Subject: [PATCH 117/451] support enum testing --- EnumTest.java | 80 +++++++++++++++++++++++++++++++++++++++++++++ JunitTestSuite.java | 3 +- MyEnum.java | 7 ++++ MyEnumClass.java | 22 +++++++++++++ MyEnumField.java | 20 ++++++++++++ 5 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 EnumTest.java create mode 100644 MyEnum.java create mode 100644 MyEnumClass.java create mode 100644 MyEnumField.java diff --git a/EnumTest.java b/EnumTest.java new file mode 100644 index 0000000..6b2a4bc --- /dev/null +++ b/EnumTest.java @@ -0,0 +1,80 @@ +package org.json.junit; + +import static org.junit.Assert.*; + +import org.json.*; +import org.junit.*; + +/** + * Documents how enum is handled by JSON-Java. + */ +public class EnumTest { + + @Test + public void simpleEnum() { + /** + * Nothing happens when a simple enum is parsed to JSONObject + */ + MyEnum myEnum = MyEnum.VAL2; + JSONObject jsonObject = new JSONObject(myEnum); + assertTrue("simple enum is not processed by JSONObject", jsonObject.length() == 0); + /** + * Nothing good happens when a simple enum is parsed to JSONArray + */ + try { + new JSONArray(myEnum); + } catch (JSONException e) { + assertTrue("JSONArray throws exception when passed enum", true); + } + } + + @Test + public void enumWithField() { + /** + * enum with a getters is handled like a bean + */ + String expectedStr = "{\"value\":\"val 2\", \"intVal\":2}"; + MyEnumField myEnum = MyEnumField.VAL2; + JSONObject jsonObject = new JSONObject(myEnum); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void enumInClass() { + /** + * class which contains enum instances. + * The enum values in MyEnum are lost. + * The string values in MyEnumFild are extracted and wrapped. + */ + String expectedStr = "{\"myEnumField\":{\"intVal\":3,\"value\":\"val 3\"},\"myEnum\":{}}"; + MyEnumClass myEnumClass = new MyEnumClass(); + myEnumClass.setMyEnum(MyEnum.VAL1); + myEnumClass.setMyEnumField(MyEnumField.VAL3); + JSONObject jsonObject = new JSONObject(myEnumClass); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } + + @Test + public void enumValueToString() { + String expectedStr1 = "\"VAL1\""; + String expectedStr2 = "\"VAL1\""; + String expectedStr3 = "\"org.json.junit.MyEnumClass@"; + MyEnum myEnum = MyEnum.VAL1; + MyEnumField myEnumField = MyEnumField.VAL1; + MyEnumClass myEnumClass = new MyEnumClass(); + myEnumClass.setMyEnum(MyEnum.VAL1); + myEnumClass.setMyEnumField(MyEnumField.VAL1); + + String str1 = JSONObject.valueToString(myEnum); + assertTrue("actual myEnum: "+str1+" expected: "+expectedStr1, + str1.equals(expectedStr1)); + String str2 = JSONObject.valueToString(myEnumField); + assertTrue("actual myEnumField: "+str2+" expected: "+expectedStr2, + str2.equals(expectedStr2)); + String str3 = JSONObject.valueToString(myEnumClass); + assertTrue("actual myEnumClass: "+str3+" expected: "+expectedStr3, + str3.startsWith(expectedStr3)); + } +} diff --git a/JunitTestSuite.java b/JunitTestSuite.java index a91426d..ceff6f1 100644 --- a/JunitTestSuite.java +++ b/JunitTestSuite.java @@ -13,7 +13,8 @@ import org.junit.runners.Suite; HTTPTest.class, JSONStringerTest.class, JSONObjectTest.class, - JSONArrayTest.class + JSONArrayTest.class, + EnumTest.class }) public class JunitTestSuite { } \ No newline at end of file diff --git a/MyEnum.java b/MyEnum.java new file mode 100644 index 0000000..d2fe08d --- /dev/null +++ b/MyEnum.java @@ -0,0 +1,7 @@ +package org.json.junit; + +public enum MyEnum { + VAL1, + VAL2, + VAL3; +} diff --git a/MyEnumClass.java b/MyEnumClass.java new file mode 100644 index 0000000..8e71663 --- /dev/null +++ b/MyEnumClass.java @@ -0,0 +1,22 @@ +package org.json.junit; + +/** + * this is simply a class that contains some enum instances + */ +public class MyEnumClass { + private MyEnum myEnum; + private MyEnumField myEnumField; + + public MyEnum getMyEnum() { + return myEnum; + } + public void setMyEnum(MyEnum myEnum) { + this.myEnum = myEnum; + } + public MyEnumField getMyEnumField() { + return myEnumField; + } + public void setMyEnumField(MyEnumField myEnumField) { + this.myEnumField = myEnumField; + } +} diff --git a/MyEnumField.java b/MyEnumField.java new file mode 100644 index 0000000..7efec54 --- /dev/null +++ b/MyEnumField.java @@ -0,0 +1,20 @@ +package org.json.junit; + +public enum MyEnumField { + VAL1(1, "val 1"), + VAL2(2, "val 2"), + VAL3(3, "val 3"); + + private String value; + private Integer intVal; + private MyEnumField(Integer intVal, String value) { + this.value = value; + this.intVal = intVal; + } + public String getValue() { + return value; + } + public Integer getIntVal() { + return intVal; + } +} From 67a0c734b6137aa26f2b8cc63e019e895b2822f4 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Wed, 3 Jun 2015 22:54:12 -0500 Subject: [PATCH 118/451] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 18c20d0..fa0792a 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ A unit test has the following stages: | CDL.java | 98% | Reasonable test cases. | | Cookie.java | 98.9% | Reasonable test cases. | | CookieList.java |96.5% | Reasonable test cases. | +| EnumTest.java | n/a | Just documenting how enums are handled. | | HTTP.java | 98.7%| Coverage > 90% | | HTTPTokener.java |93.2% | No test | | JSONArray.java |95.9% | Coverage > 90% | From f6bdc908d818cabdba0c52d1598d64341e673d2c Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Wed, 3 Jun 2015 22:55:35 -0500 Subject: [PATCH 119/451] Update README.md --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fa0792a..bd36d85 100644 --- a/README.md +++ b/README.md @@ -69,9 +69,12 @@ A unit test has the following stages: | Files used in test | | ------------- | +| MyEnum.java | +| MyEnumClass.java | +| MyEnumField.java | | JunitTestSuite.java | | StringsResourceBundle.java | -|TestRunner.java | +| TestRunner.java | | Util.java | From 969e2d4fd52a503d8f4a7fe81b8758c13a9180e4 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 4 Jun 2015 22:29:55 -0500 Subject: [PATCH 120/451] test iterable --- JSONArrayTest.java | 43 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/JSONArrayTest.java b/JSONArrayTest.java index 78b194e..b033a60 100644 --- a/JSONArrayTest.java +++ b/JSONArrayTest.java @@ -2,10 +2,7 @@ package org.json.junit; import static org.junit.Assert.*; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import org.json.*; import org.junit.Test; @@ -464,4 +461,42 @@ public class JSONArrayTest { JSONArray expectedJsonArray = new JSONArray(expectedStr); Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } + + @Test + public void iterator() { + JSONArray jsonArray = new JSONArray(arrayStr); + Iterator it = jsonArray.iterator(); + assertTrue("Array true", + Boolean.TRUE.equals(it.next())); + assertTrue("Array false", + Boolean.FALSE.equals(it.next())); + assertTrue("Array string true", + "true".equals(it.next())); + assertTrue("Array string false", + "false".equals(it.next())); + assertTrue("Array string", + "hello".equals(it.next())); + + assertTrue("Array double", + new Double(23.45e-4).equals(it.next())); + assertTrue("Array string double", + new Double(23.45).equals(Double.parseDouble((String)it.next()))); + + assertTrue("Array value int", + new Integer(42).equals(it.next())); + assertTrue("Array value string int", + new Integer(43).equals(Integer.parseInt((String)it.next()))); + + JSONArray nestedJsonArray = (JSONArray)it.next(); + assertTrue("Array value JSONArray", nestedJsonArray != null); + + JSONObject nestedJsonObject = (JSONObject)it.next(); + assertTrue("Array value JSONObject", nestedJsonObject != null); + + assertTrue("Array value long", + new Long(0).equals(((Number) it.next()).longValue())); + assertTrue("Array value string long", + new Long(-1).equals(Long.parseLong((String) it.next()))); + assertTrue("should be at end of array", !it.hasNext()); + } } From 9cf532828d11a00bf60e082cade9e12d2e573cd9 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 7 Jun 2015 22:22:14 -0500 Subject: [PATCH 121/451] confirm current behavior --- EnumTest.java | 207 ++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 174 insertions(+), 33 deletions(-) diff --git a/EnumTest.java b/EnumTest.java index 6b2a4bc..14605b1 100644 --- a/EnumTest.java +++ b/EnumTest.java @@ -6,66 +6,117 @@ import org.json.*; import org.junit.*; /** - * Documents how enum is handled by JSON-Java. + * Enums are not explicitly supported in JSON-Java. But because enums act like + * classes, all required behavior is already be present in some form. + * These tests explore how enum serialization works with JSON-Java. */ public class EnumTest { - @Test - public void simpleEnum() { + public void jsonObjectFromEnum() { /** - * Nothing happens when a simple enum is parsed to JSONObject + * To serialize an enum by its getters, use the JSONObject Object constructor. + * The JSONObject ctor handles enum like any other bean. A JSONobject + * is created whose entries are the getter name/value pairs. */ + + // If there are no getters then the object is empty. MyEnum myEnum = MyEnum.VAL2; JSONObject jsonObject = new JSONObject(myEnum); - assertTrue("simple enum is not processed by JSONObject", jsonObject.length() == 0); - /** - * Nothing good happens when a simple enum is parsed to JSONArray - */ - try { - new JSONArray(myEnum); - } catch (JSONException e) { - assertTrue("JSONArray throws exception when passed enum", true); - } - } + assertTrue("simple enum has no getters", jsonObject.length() == 0); - @Test - public void enumWithField() { - /** - * enum with a getters is handled like a bean - */ + // enum with a getters should create a non-empty object String expectedStr = "{\"value\":\"val 2\", \"intVal\":2}"; - MyEnumField myEnum = MyEnumField.VAL2; - JSONObject jsonObject = new JSONObject(myEnum); + MyEnumField myEnumField = MyEnumField.VAL2; + jsonObject = new JSONObject(myEnumField); JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - } - @Test - public void enumInClass() { /** - * class which contains enum instances. - * The enum values in MyEnum are lost. - * The string values in MyEnumFild are extracted and wrapped. + * class which contains enum instances. Each enum should be stored + * in its own JSONObject */ - String expectedStr = "{\"myEnumField\":{\"intVal\":3,\"value\":\"val 3\"},\"myEnum\":{}}"; + expectedStr = "{\"myEnumField\":{\"intVal\":3,\"value\":\"val 3\"},\"myEnum\":{}}"; MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); myEnumClass.setMyEnumField(MyEnumField.VAL3); - JSONObject jsonObject = new JSONObject(myEnumClass); - JSONObject expectedJsonObject = new JSONObject(expectedStr); + jsonObject = new JSONObject(myEnumClass); + expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + @Test + public void jsonObjectFromEnumWithNames() { + /** + * To serialize an enum by its set of allowed values, use getNames() + * and the the JSONObject Object with names constructor. + */ + String [] names; + String expectedStr; + JSONObject jsonObject; + JSONObject finalJsonObject; + JSONObject expectedJsonObject; + + expectedStr = "{\"VAL1\":\"VAL1\",\"VAL2\":\"VAL2\",\"VAL3\":\"VAL3\"}"; + MyEnum myEnum = MyEnum.VAL1; + names = JSONObject.getNames(myEnum); + // The values will be MyEnmField fields, so need to convert back to string for comparison + jsonObject = new JSONObject(myEnum, names); + finalJsonObject = new JSONObject(jsonObject.toString()); + expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedJsonObject); + + expectedStr = "{\"VAL1\":\"VAL1\",\"VAL2\":\"VAL2\",\"VAL3\":\"VAL3\"}"; + MyEnumField myEnumField = MyEnumField.VAL3; + names = JSONObject.getNames(myEnumField); + // The values will be MyEnmField fields, so need to convert back to string for comparison + jsonObject = new JSONObject(myEnumField, names); + finalJsonObject = new JSONObject(jsonObject.toString()); + expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedJsonObject); + } + @Test + public void enumPut() { + /** + * To serialize by assigned value, use the put() methods. The value + * will be stored as a enum type. + */ + String expectedFinalStr = "{\"myEnum\":\"VAL2\", \"myEnumField\":\"VAL1\"}"; + JSONObject jsonObject = new JSONObject(); + MyEnum myEnum = MyEnum.VAL2; + jsonObject.put("myEnum", myEnum); + assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonObject.get("myEnum"))); + assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonObject.opt("myEnum"))); + MyEnumField myEnumField = MyEnumField.VAL1; + jsonObject.putOnce("myEnumField", myEnumField); + assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonObject.get("myEnumField"))); + assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonObject.opt("myEnumField"))); + JSONObject finalJsonObject = new JSONObject(jsonObject.toString()); + JSONObject expectedFinalJsonObject = new JSONObject(expectedFinalStr); + Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedFinalJsonObject); + + JSONArray jsonArray = new JSONArray(); + jsonArray.put(myEnum); + jsonArray.put(1, myEnumField); + assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonArray.get(0))); + assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.opt(1))); + JSONArray expectedJsonArray = new JSONArray(); + expectedJsonArray.put(MyEnum.VAL2); + expectedJsonArray.put(MyEnumField.VAL1); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.remove(1))); + } + @Test public void enumValueToString() { + /** + * The default action of valueToString() is to call object.toString(). + * For enums, this means the assigned value will be returned as a string. + */ String expectedStr1 = "\"VAL1\""; String expectedStr2 = "\"VAL1\""; - String expectedStr3 = "\"org.json.junit.MyEnumClass@"; MyEnum myEnum = MyEnum.VAL1; MyEnumField myEnumField = MyEnumField.VAL1; MyEnumClass myEnumClass = new MyEnumClass(); - myEnumClass.setMyEnum(MyEnum.VAL1); - myEnumClass.setMyEnumField(MyEnumField.VAL1); String str1 = JSONObject.valueToString(myEnum); assertTrue("actual myEnum: "+str1+" expected: "+expectedStr1, @@ -73,8 +124,98 @@ public class EnumTest { String str2 = JSONObject.valueToString(myEnumField); assertTrue("actual myEnumField: "+str2+" expected: "+expectedStr2, str2.equals(expectedStr2)); + + /** + * However, an enum within another class will not be rendered + * unless that class overrides default toString() + */ + String expectedStr3 = "\"org.json.junit.MyEnumClass@"; + myEnumClass.setMyEnum(MyEnum.VAL1); + myEnumClass.setMyEnumField(MyEnumField.VAL1); String str3 = JSONObject.valueToString(myEnumClass); assertTrue("actual myEnumClass: "+str3+" expected: "+expectedStr3, str3.startsWith(expectedStr3)); } + + @Test + public void enumToString() { + /** + * In whatever form the enum was added to the JSONObject or JSONArray, + * json[Object|Array].toString should serialize it in a reasonable way. + */ + MyEnum myEnum = MyEnum.VAL2; + JSONObject jsonObject = new JSONObject(myEnum); + String expectedStr = "{}"; + assertTrue("myEnum toString() should be empty", expectedStr.equals(jsonObject.toString())); + + MyEnumField myEnumField = MyEnumField.VAL2; + jsonObject = new JSONObject(myEnumField); + expectedStr = "{\"value\":\"val 2\", \"intVal\":2}"; + JSONObject actualJsonObject = new JSONObject(jsonObject.toString()); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); + + expectedStr = "{\"myEnumField\":{\"intVal\":3,\"value\":\"val 3\"},\"myEnum\":{}}"; + MyEnumClass myEnumClass = new MyEnumClass(); + myEnumClass.setMyEnum(MyEnum.VAL1); + myEnumClass.setMyEnumField(MyEnumField.VAL3); + jsonObject = new JSONObject(myEnumClass); + actualJsonObject = new JSONObject(jsonObject.toString()); + expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); + + expectedStr = "{\"VAL1\":\"VAL1\",\"VAL2\":\"VAL2\",\"VAL3\":\"VAL3\"}"; + String [] names = JSONObject.getNames(myEnum); + jsonObject = new JSONObject(myEnum, names); + actualJsonObject = new JSONObject(jsonObject.toString()); + expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); + + expectedStr = "{\"VAL1\":\"VAL1\",\"VAL2\":\"VAL2\",\"VAL3\":\"VAL3\"}"; + names = JSONObject.getNames(myEnumField); + jsonObject = new JSONObject(myEnumField, names); + actualJsonObject = new JSONObject(jsonObject.toString()); + expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); + + expectedStr = "{\"myEnum\":\"VAL2\", \"myEnumField\":\"VAL2\"}"; + jsonObject = new JSONObject(); + jsonObject.putOpt("myEnum", myEnum); + jsonObject.putOnce("myEnumField", myEnumField); + actualJsonObject = new JSONObject(jsonObject.toString()); + expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); + + expectedStr = "[\"VAL2\", \"VAL2\"]"; + JSONArray jsonArray = new JSONArray(); + jsonArray.put(myEnum); + jsonArray.put(1, myEnumField); + JSONArray actualJsonArray = new JSONArray(jsonArray.toString()); + JSONArray expectedJsonArray = new JSONArray(expectedStr); + Util.compareActualVsExpectedJsonArrays(actualJsonArray, expectedJsonArray); + } + + public void wrap() { + /** + * Wrap should handle enums exactly the same way as the JSONObject(Object) + * constructor. + */ + MyEnum myEnum = MyEnum.VAL2; + JSONObject jsonObject = (JSONObject)JSONObject.wrap(myEnum); + assertTrue("simple enum has no getters", jsonObject.length() == 0); + + String expectedStr = "{\"value\":\"val 2\", \"intVal\":2}"; + MyEnumField myEnumField = MyEnumField.VAL2; + jsonObject = (JSONObject)JSONObject.wrap(myEnumField); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + expectedStr = "{\"myEnumField\":{\"intVal\":3,\"value\":\"val 3\"},\"myEnum\":{}}"; + MyEnumClass myEnumClass = new MyEnumClass(); + myEnumClass.setMyEnum(MyEnum.VAL1); + myEnumClass.setMyEnumField(MyEnumField.VAL3); + jsonObject = (JSONObject)JSONObject.wrap(myEnumClass); + expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + } } From 56aa2f86079738f0945abb5728d0954a2b9904bc Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 7 Jun 2015 22:22:42 -0500 Subject: [PATCH 122/451] ongoing unit test improvement --- JSONObjectTest.java | 93 ++++++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 48 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index e044c8c..827049e 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -2,10 +2,12 @@ package org.json.junit; import static org.junit.Assert.*; import static org.mockito.Mockito.*; + import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; + import org.json.*; import org.junit.*; @@ -416,10 +418,7 @@ public class JSONObjectTest { jsonObjectInner.get("myKey").equals("myVal")); } - // improving unit tests left off here - @Test - public void stringToValueNumbersTest() { // Check if library handles large or high precision numbers correctly assertTrue( "0.2 should be a Double!", @@ -446,12 +445,12 @@ public class JSONObjectTest { JSONObject.stringToValue(str).equals("9223372036854775808")); } - @Test /** * This test documents numeric values which could be numerically * handled as BigDecimal or BigInteger. It helps determine what outputs * will change if those types are supported. */ + @Test public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects String str = @@ -605,8 +604,16 @@ public class JSONObjectTest { exceptionCount == tryCount); } + /** + * The purpose for the static method getNames() methods are not clear. + * This method is not called from within JSON-Java. Most likely + * uses are to prep names arrays for: + * JSONObject(JSONObject jo, String[] names) + * JSONObject(Object object, String names[]), + */ @Test public void jsonObjectNames() { + JSONObject jsonObject; // getNames() from null JSONObject assertTrue("null names from null Object", @@ -616,11 +623,17 @@ public class JSONObjectTest { assertTrue("null names from Object with no fields", null == JSONObject.getNames(new MyJsonString())); + // getNames from new JSONOjbect + jsonObject = new JSONObject(); + String [] names = JSONObject.getNames(jsonObject); + assertTrue("names should be null", names == null); + + // getNames() from empty JSONObject String emptyStr = "{}"; - JSONObject emptyJsonObject = new JSONObject(emptyStr); + jsonObject = new JSONObject(emptyStr); assertTrue("empty JSONObject should have null names", - null == JSONObject.getNames(emptyJsonObject)); + null == JSONObject.getNames(jsonObject)); // getNames() from JSONObject String str = @@ -630,9 +643,28 @@ public class JSONObjectTest { "\"stringKey\":\"hello world!\","+ "}"; String [] expectedNames = {"trueKey", "falseKey", "stringKey"}; - JSONObject jsonObject = new JSONObject(str); - String [] names = JSONObject.getNames(jsonObject); + jsonObject = new JSONObject(str); + names = JSONObject.getNames(jsonObject); Util.compareActualVsExpectedStringArrays(names, expectedNames); + + /** + * getNames() from an enum with properties has an interesting result. + * It returns the enum values, not the selected enum properties + */ + MyEnumField myEnumField = MyEnumField.VAL1; + String[] enumExpectedNames = {"VAL1", "VAL2", "VAL3"}; + names = JSONObject.getNames(myEnumField); + Util.compareActualVsExpectedStringArrays(names, enumExpectedNames); + + /** + * A bean is also an object. But in order to test the static + * method getNames(), this particular bean needs some public + * data members, which have been added to the class. + */ + JSONObjectTest jsonObjectTest = new JSONObjectTest(); + String [] jsonObjectTestExpectedNames = {"publicString", "publicInt"}; + names = JSONObject.getNames(jsonObjectTest); + Util.compareActualVsExpectedStringArrays(names, jsonObjectTestExpectedNames); } @Test @@ -668,19 +700,6 @@ public class JSONObjectTest { Util.compareActualVsExpectedStringArrays(names, expectedNames); } - @Test - public void objectNames() { - /** - * A bean is also an object. But in order to test the static - * method getNames(), this particular bean needs some public - * data members, which have been added to the class. - */ - JSONObjectTest jsonObjectTest = new JSONObjectTest(); - String [] expectedNames = {"publicString", "publicInt"}; - String [] names = JSONObject.getNames(jsonObjectTest); - Util.compareActualVsExpectedStringArrays(names, expectedNames); - } - @Test public void jsonObjectIncrement() { String str = @@ -693,8 +712,6 @@ public class JSONObjectTest { "\"keyInt\":3,"+ "\"keyLong\":9999999993,"+ "\"keyDouble\":3.1,"+ - // TODO: not sure if this will work on other platforms - // Should work the same way on any platform! @see https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 // This is the effect of a float to double conversion and is inherent to the shortcomings of the IEEE 754 format, when // converting 32-bit into double-precision 64-bit. @@ -773,26 +790,6 @@ public class JSONObjectTest { } - @Test - public void emptyJsonObjectNamesToArray() { - JSONObject jsonObject = new JSONObject(); - String [] names = JSONObject.getNames(jsonObject); - assertTrue("names should be null", names == null); - } - - @Test - public void jsonObjectNamesToArray() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "}"; - String [] expectedNames = {"trueKey", "falseKey", "stringKey"}; - JSONObject jsonObject = new JSONObject(str); - String [] names = JSONObject.getNames(jsonObject); - Util.compareActualVsExpectedStringArrays(names, expectedNames); - } @Test public void jsonObjectNumberToString() { @@ -907,6 +904,7 @@ public class JSONObjectTest { } @Test + @SuppressWarnings("unchecked") public void jsonObjectToStringSuppressWarningOnCastToMap() { JSONObject jsonObject = new JSONObject(); Map map = new HashMap(); @@ -921,8 +919,7 @@ public class JSONObjectTest { * Can't do a Util compare because although they look the same * in the debugger, one is a map and the other is a JSONObject. */ - // TODO: fix warnings - map = (Map)jsonObject.get("key"); + map = (Map)jsonObject.get("key"); JSONObject mapJsonObject = expectedJsonObject.getJSONObject("key"); assertTrue("value size should be equal", map.size() == mapJsonObject.length() && map.size() == 1); @@ -934,6 +931,7 @@ public class JSONObjectTest { } @Test + @SuppressWarnings("unchecked") public void jsonObjectToStringSuppressWarningOnCastToCollection() { JSONObject jsonObject = new JSONObject(); Collection collection = new ArrayList(); @@ -950,12 +948,11 @@ public class JSONObjectTest { assertTrue("keys should be equal", jsonObject.keySet().iterator().next().equals( expectedJsonObject.keySet().iterator().next())); - // TODO: fix warnings - collection = (Collection)jsonObject.get("key"); + collection = (Collection)jsonObject.get("key"); JSONArray jsonArray = expectedJsonObject.getJSONArray("key"); assertTrue("value size should be equal", collection.size() == jsonArray.length()); - Iterator it = collection.iterator(); + Iterator it = collection.iterator(); for (int i = 0; i < collection.size(); ++i) { assertTrue("items should be equal for index: "+i, jsonArray.get(i).toString().equals(it.next().toString())); From 44f98e6a132a2148545b330e8cd3abd4658d182c Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 13 Jun 2015 13:30:06 -0500 Subject: [PATCH 123/451] Update README.md --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index bd36d85..80e73ef 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,16 @@ More coverage is needed, but more importantly, improvements to test quality is n You will need the following libraries for testing: Test harness: http://junit.org
Coverage: http://www.eclemma.org/
+JsonPath: https://github.com/jayway/JsonPath Mockery: https://github.com/mockito/mockito +Include these libraries in your project: +JSON-Java.jar (make this jar of the files to be tested yourself) +hamcrest-core-1.3.jar (for Junit) +junit-4.12.jar +mockito-all-1.9.5.jar + + Eclipse is the recommended development environment. Run individual tests or JunitTestSuite using *EclEmma Coverage*, or execute the TestRunner application directly.
From cb7b602f35aadca7a9fef910997784eda464a9a7 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 13 Jun 2015 14:53:43 -0500 Subject: [PATCH 124/451] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 80e73ef..b683c13 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,6 @@ More coverage is needed, but more importantly, improvements to test quality is n You will need the following libraries for testing: Test harness: http://junit.org
Coverage: http://www.eclemma.org/
-JsonPath: https://github.com/jayway/JsonPath Mockery: https://github.com/mockito/mockito Include these libraries in your project: From 0640856462f25623487435dac728d42ca12a09d6 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 17 Jun 2015 02:59:43 -0500 Subject: [PATCH 125/451] unexpected double behavior --- JSONObjectTest.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 827049e..f7672a2 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -604,6 +604,33 @@ public class JSONObjectTest { exceptionCount == tryCount); } + @Test + public void unexpectedDoubleToIntConversion() { + /** + * This test documents an unexpected numeric behavior. + * A double that ends with .0 is parsed, serialized, then + * parsed again. On the second parse, it has become an int. + */ + String key30 = "key30"; + String key31 = "key31"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put(key30, new Double(3.0)); + jsonObject.put(key31, new Double(3.1)); + + assertTrue("3.0 should remain a double", + jsonObject.getDouble(key30) == 3); + assertTrue("3.1 should remain a double", + jsonObject.getDouble(key31) == 3.1); + + // turns 3.0 into 3. + String serializedString = jsonObject.toString(); + JSONObject deserialized = new JSONObject(serializedString); + assertTrue("3.0 is now an int", deserialized.get(key30) instanceof Integer); + assertTrue("3.0 can still be interpreted as a double", + deserialized.getDouble(key30) == 3.0); + assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); + } + /** * The purpose for the static method getNames() methods are not clear. * This method is not called from within JSON-Java. Most likely From c5173e7cc3a7b6b8d736563e10f4fc94df6ce7d7 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 17 Jun 2015 20:09:31 -0500 Subject: [PATCH 126/451] ip --- JSONObjectTest.java | 84 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index f7672a2..e791179 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -631,6 +631,90 @@ public class JSONObjectTest { assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); } + @Test + public void bigNumberOperations() { + /** + * JSONObject tries to parse BigInteger as a bean, but it only has + * one getter, getLowestBitSet(). The value is lost and an unhelpful + * value is stored. This should be fixed. + */ + BigInteger bigInteger = new BigInteger("123456789012345678901234567890"); + JSONObject jsonObject = new JSONObject(bigInteger); + Object obj = jsonObject.get("lowestSetBit"); + assertTrue("JSONObject only has 1 value", jsonObject.length() == 1); + assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet", + obj instanceof Integer); + assertTrue("this bigInteger lowestBitSet happens to be 1", + obj.equals(1)); + + /** + * JSONObject put(String, Object) method stores and serializesbigInt and bigDec + * correctly. Nothing needs to change. + */ + BigDecimal bigDecimal = new BigDecimal( + "123456789012345678901234567890.12345678901234567890123456789"); + jsonObject = new JSONObject(bigDecimal); + assertTrue("large bigDecimal is not stored", jsonObject.length() == 0); + + /** + * JSONObject put(String, Object) method stores and serializes + * bigInt and bigDec correctly. Nothing needs to change. + */ + jsonObject = new JSONObject(); + jsonObject.put("bigInt", bigInteger); + assertTrue("jsonObject.put() handles bigInt correctly", + jsonObject.get("bigInt").equals(bigInteger)); + assertTrue("jsonObject serializes bigInt correctly", + jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); + jsonObject = new JSONObject(); + jsonObject.put("bigDec", bigDecimal); + assertTrue("jsonObject.put() handles bigDec correctly", + jsonObject.get("bigDec").equals(bigDecimal)); + assertTrue("jsonObject serializes bigDec correctly", + jsonObject.toString().equals( + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + + /** + * There is no way to get bigInt or bigDec by type. + * This should be fixed. E.G. jsonObject.getBigInteger(key); + */ + + /** + * JSONObject.numberToString() works correctly, nothing to change. + */ + String str = JSONObject.numberToString(bigInteger); + assertTrue("numberToString() handles bigInteger correctly", + str.equals("123456789012345678901234567890")); + str = JSONObject.numberToString(bigDecimal); + assertTrue("numberToString() handles bigDecimal correctly", + str.equals("123456789012345678901234567890.12345678901234567890123456789")); + + /** + * JSONObject.stringToValue() turns bigInt into an accurate string, + * and rounds bigDec. This incorrect, but users may have come to + * expect this behavior. Change would be marginally better, but + * might inconvenience users. + */ + obj = JSONObject.stringToValue(bigInteger.toString()); + assertTrue("stringToValue() turns bigInteger string into string", + obj instanceof String); + obj = JSONObject.stringToValue(bigDecimal.toString()); + assertTrue("stringToValue() changes bigDecimal string", + !obj.toString().equals(bigDecimal.toString())); + + /** + * JSONObject.wrap() performs the advertised behavior, + * which is to turn Java classes into strings. + * Probably not a bug + */ + obj = JSONObject.wrap(bigInteger); + assertTrue("wrap() turns bigInt into a string", + obj.equals(bigInteger.toString())); + obj = JSONObject.wrap(bigDecimal); + assertTrue("wrap() turns bigDec into a string", + obj.equals(bigDecimal.toString())); + } + /** * The purpose for the static method getNames() methods are not clear. * This method is not called from within JSON-Java. Most likely From 8c1a0c47b7000bebdf8362f3d817d8b93aba84e8 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 17 Jun 2015 20:18:51 -0500 Subject: [PATCH 127/451] fixed test comment --- JSONObjectTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index e791179..5b98aae 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -648,8 +648,9 @@ public class JSONObjectTest { obj.equals(1)); /** - * JSONObject put(String, Object) method stores and serializesbigInt and bigDec - * correctly. Nothing needs to change. + * JSONObject tries to parse BigDecimal as a bean, but it has + * no getters, The value is lost and no value is stored. + * This should be fixed. */ BigDecimal bigDecimal = new BigDecimal( "123456789012345678901234567890.12345678901234567890123456789"); From 6c48db010f06c63b13c99d92a2932e9379155047 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 20 Jun 2015 23:35:48 -0500 Subject: [PATCH 128/451] bigInt and bigDec behavior --- JSONObjectTest.java | 108 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 91 insertions(+), 17 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 5b98aae..ccef775 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -20,7 +20,7 @@ class MyJsonString implements JSONString { public String toJSONString() { return "my string"; } -}; +} interface MyBean { public Integer getIntKey(); @@ -32,6 +32,11 @@ interface MyBean { public StringReader getStringReaderKey(); }; +interface MyBigNumberBean { + public BigInteger getBigInteger(); + public BigDecimal getBigDecimal(); +} + /** * JSONObject, along with JSONArray, are the central classes of the reference app. * All of the other classes interact with it and JSON functionality would be @@ -659,26 +664,32 @@ public class JSONObjectTest { /** * JSONObject put(String, Object) method stores and serializes - * bigInt and bigDec correctly. Nothing needs to change. + * bigInt and bigDec correctly. Nothing needs to change. + * TODO: New methods + * get|optBigInteger|BigDecimal() should work like other supported + * objects. Uncomment the get/opt methods after JSONObject is updated. */ jsonObject = new JSONObject(); jsonObject.put("bigInt", bigInteger); assertTrue("jsonObject.put() handles bigInt correctly", jsonObject.get("bigInt").equals(bigInteger)); + // assertTrue("jsonObject.getBigInteger() handles bigInt correctly", + // jsonObject.getBigInteger("bigInt").equals(bigInteger)); + // assertTrue("jsonObject.optBigInteger() handles bigInt correctly", + // jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); assertTrue("jsonObject serializes bigInt correctly", jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); jsonObject = new JSONObject(); jsonObject.put("bigDec", bigDecimal); assertTrue("jsonObject.put() handles bigDec correctly", jsonObject.get("bigDec").equals(bigDecimal)); + // assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", + // jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); + // assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", + // jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); assertTrue("jsonObject serializes bigDec correctly", jsonObject.toString().equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - - /** - * There is no way to get bigInt or bigDec by type. - * This should be fixed. E.G. jsonObject.getBigInteger(key); - */ + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); /** * JSONObject.numberToString() works correctly, nothing to change. @@ -704,16 +715,79 @@ public class JSONObjectTest { !obj.toString().equals(bigDecimal.toString())); /** - * JSONObject.wrap() performs the advertised behavior, - * which is to turn Java classes into strings. - * Probably not a bug + * wrap() vs put() big number behavior changes serialization + * This is a bug. + * TODO: Updated expected wrap() test results after JSONObject is updated. */ + // bigInt map ctor + Map map = new HashMap(); + map.put("bigInt", bigInteger); + jsonObject = new JSONObject(map); + String actualFromMapStr = jsonObject.toString(); + assertTrue("bigInt in map (or array or bean) is a string", + actualFromMapStr.equals( + "{\"bigInt\":\"123456789012345678901234567890\"}")); + // bigInt put + jsonObject = new JSONObject(); + jsonObject.put("bigInt", bigInteger); + String actualFromPutStr = jsonObject.toString(); + assertTrue("bigInt from put is a number", + actualFromPutStr.equals( + "{\"bigInt\":123456789012345678901234567890}")); + // bigDec map ctor + map = new HashMap(); + map.put("bigDec", bigDecimal); + jsonObject = new JSONObject(map); + actualFromMapStr = jsonObject.toString(); + assertTrue("bigDec in map (or array or bean) is a string", + actualFromMapStr.equals( + "{\"bigDec\":\"123456789012345678901234567890.12345678901234567890123456789\"}")); + // bigDec put + jsonObject = new JSONObject(); + jsonObject.put("bigDec", bigDecimal); + actualFromPutStr = jsonObject.toString(); + assertTrue("bigDec from put is a number", + actualFromPutStr.equals( + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + // bigInt,bigDec put + JSONArray jsonArray = new JSONArray(); + jsonArray.put(bigInteger); + jsonArray.put(bigDecimal); + actualFromPutStr = jsonArray.toString(); + assertTrue("bigInt, bigDec from put is a number", + actualFromPutStr.equals( + "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); + // bigInt,bigDec list ctor + List list = new ArrayList(); + list.add(bigInteger); + list.add(bigDecimal); + jsonArray = new JSONArray(list); + String actualFromListStr = jsonArray.toString(); + assertTrue("bigInt, bigDec in list is a string", + actualFromListStr.equals( + "[\"123456789012345678901234567890\",\"123456789012345678901234567890.12345678901234567890123456789\"]")); + // bigInt bean ctor + MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); + when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); + jsonObject = new JSONObject(myBigNumberBean); + String actualFromBeanStr = jsonObject.toString(); + // can't do a full string compare because mockery adds an extra key/value + assertTrue("bigInt from bean ctor is a string", + actualFromBeanStr.contains("\"123456789012345678901234567890\"")); + // bigDec bean ctor + myBigNumberBean = mock(MyBigNumberBean.class); + when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); + jsonObject = new JSONObject(myBigNumberBean); + actualFromBeanStr = jsonObject.toString(); + // can't do a full string compare because mockery adds an extra key/value + assertTrue("bigDec from bean ctor is a string", + actualFromBeanStr.contains("\"123456789012345678901234567890.12345678901234567890123456789\"")); + // bigInt,bigDec wrap() obj = JSONObject.wrap(bigInteger); - assertTrue("wrap() turns bigInt into a string", - obj.equals(bigInteger.toString())); + assertTrue("wrap() returns string",obj.equals(bigInteger.toString())); obj = JSONObject.wrap(bigDecimal); - assertTrue("wrap() turns bigDec into a string", - obj.equals(bigDecimal.toString())); + assertTrue("wrap() returns string",obj.equals(bigDecimal.toString())); + } /** @@ -1133,8 +1207,8 @@ public class JSONObjectTest { * is recognized as being a Java package class. */ Object bdWrap = JSONObject.wrap(BigDecimal.ONE); - assertTrue("BigDecimal.ONE currently evaluates to string", - bdWrap.equals("1")); + assertTrue("BigDecimal.ONE evaluates to string", + bdWrap.equals(BigDecimal.ONE.toString())); // wrap JSONObject returns JSONObject String jsonObjectStr = From 355e8323377c1a9104fc8e122573d57f617dbe2e Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 6 Jul 2015 22:31:48 -0500 Subject: [PATCH 129/451] latest --- JSONObjectTest.java | 55 +++++++++++++++++++++++++++++++-------------- 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index ccef775..a661312 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -637,6 +637,10 @@ public class JSONObjectTest { } @Test + /** + * Important behaviors of big numbers. Includes both JSONObject + * and JSONArray tests + */ public void bigNumberOperations() { /** * JSONObject tries to parse BigInteger as a bean, but it only has @@ -691,6 +695,9 @@ public class JSONObjectTest { jsonObject.toString().equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + JSONArray jsonArray = new JSONArray(); + + /** * JSONObject.numberToString() works correctly, nothing to change. */ @@ -715,9 +722,7 @@ public class JSONObjectTest { !obj.toString().equals(bigDecimal.toString())); /** - * wrap() vs put() big number behavior changes serialization - * This is a bug. - * TODO: Updated expected wrap() test results after JSONObject is updated. + * wrap() vs put() big number behavior is now the same. */ // bigInt map ctor Map map = new HashMap(); @@ -726,7 +731,7 @@ public class JSONObjectTest { String actualFromMapStr = jsonObject.toString(); assertTrue("bigInt in map (or array or bean) is a string", actualFromMapStr.equals( - "{\"bigInt\":\"123456789012345678901234567890\"}")); + "{\"bigInt\":123456789012345678901234567890}")); // bigInt put jsonObject = new JSONObject(); jsonObject.put("bigInt", bigInteger); @@ -739,9 +744,9 @@ public class JSONObjectTest { map.put("bigDec", bigDecimal); jsonObject = new JSONObject(map); actualFromMapStr = jsonObject.toString(); - assertTrue("bigDec in map (or array or bean) is a string", + assertTrue("bigDec in map (or array or bean) is a bigDec", actualFromMapStr.equals( - "{\"bigDec\":\"123456789012345678901234567890.12345678901234567890123456789\"}")); + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); // bigDec put jsonObject = new JSONObject(); jsonObject.put("bigDec", bigDecimal); @@ -750,43 +755,59 @@ public class JSONObjectTest { actualFromPutStr.equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); // bigInt,bigDec put - JSONArray jsonArray = new JSONArray(); + jsonArray = new JSONArray(); jsonArray.put(bigInteger); jsonArray.put(bigDecimal); actualFromPutStr = jsonArray.toString(); assertTrue("bigInt, bigDec from put is a number", actualFromPutStr.equals( "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); + assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger)); + assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal)); + assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); + assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); + jsonArray.put(Boolean.TRUE); + try { + jsonArray.getBigInteger(2); + assertTrue("should not be able to get big int", false); + } catch (Exception ignored) {} + try { + jsonArray.getBigDecimal(2); + assertTrue("should not be able to get big dec", false); + } catch (Exception ignored) {} + assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); + assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); + // bigInt,bigDec list ctor List list = new ArrayList(); list.add(bigInteger); list.add(bigDecimal); jsonArray = new JSONArray(list); String actualFromListStr = jsonArray.toString(); - assertTrue("bigInt, bigDec in list is a string", + assertTrue("bigInt, bigDec in list is a bigInt, bigDec", actualFromListStr.equals( - "[\"123456789012345678901234567890\",\"123456789012345678901234567890.12345678901234567890123456789\"]")); + "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); // bigInt bean ctor MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); jsonObject = new JSONObject(myBigNumberBean); String actualFromBeanStr = jsonObject.toString(); // can't do a full string compare because mockery adds an extra key/value - assertTrue("bigInt from bean ctor is a string", - actualFromBeanStr.contains("\"123456789012345678901234567890\"")); + assertTrue("bigInt from bean ctor is a bigInt", + actualFromBeanStr.contains("123456789012345678901234567890")); // bigDec bean ctor myBigNumberBean = mock(MyBigNumberBean.class); when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); jsonObject = new JSONObject(myBigNumberBean); actualFromBeanStr = jsonObject.toString(); // can't do a full string compare because mockery adds an extra key/value - assertTrue("bigDec from bean ctor is a string", - actualFromBeanStr.contains("\"123456789012345678901234567890.12345678901234567890123456789\"")); + assertTrue("bigDec from bean ctor is a bigDec", + actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789")); // bigInt,bigDec wrap() obj = JSONObject.wrap(bigInteger); - assertTrue("wrap() returns string",obj.equals(bigInteger.toString())); + assertTrue("wrap() returns big num",obj.equals(bigInteger)); obj = JSONObject.wrap(bigDecimal); - assertTrue("wrap() returns string",obj.equals(bigDecimal.toString())); + assertTrue("wrap() returns string",obj.equals(bigDecimal)); } @@ -1207,8 +1228,8 @@ public class JSONObjectTest { * is recognized as being a Java package class. */ Object bdWrap = JSONObject.wrap(BigDecimal.ONE); - assertTrue("BigDecimal.ONE evaluates to string", - bdWrap.equals(BigDecimal.ONE.toString())); + assertTrue("BigDecimal.ONE evaluates to ONE", + bdWrap.equals(BigDecimal.ONE)); // wrap JSONObject returns JSONObject String jsonObjectStr = From e056fc0881d4fcc7dca2aaeb12a3b029998ae7de Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 6 Jul 2015 22:33:52 -0500 Subject: [PATCH 130/451] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index b683c13..f05db81 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # JSON-Java-unit-test +*Tests are broken until bigint/bigdec changes are committed in JsonJava*
+ Unit tests to validate the JSON-Java GitHub project code
https://github.com/douglascrockford/JSON-java
From 3de0a0a70e96ac3ba0c82cd19553db0515eda57f Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 7 Jul 2015 23:13:59 -0500 Subject: [PATCH 131/451] Update README.md --- README.md | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index f05db81..fda6f2e 100644 --- a/README.md +++ b/README.md @@ -8,26 +8,24 @@ https://github.com/douglascrockford/JSON-java
*These tests are a work in progress. Help from interested developers is welcome.*
More coverage is needed, but more importantly, improvements to test quality is needed.
-You will need the following libraries for testing: -Test harness: http://junit.org
-Coverage: http://www.eclemma.org/
-Mockery: https://github.com/mockito/mockito - -Include these libraries in your project: -JSON-Java.jar (make this jar of the files to be tested yourself) -hamcrest-core-1.3.jar (for Junit) -junit-4.12.jar -mockito-all-1.9.5.jar - - Eclipse is the recommended development environment. Run individual tests or JunitTestSuite using *EclEmma Coverage*, or execute the TestRunner application directly.
+You will need the following libraries for testing: +Test harness: http://junit.org
+* hamcrest-core-1.3.jar (for Junit) +* junit-4.12.jar +Mockery: https://github.com/mockito/mockito +* mockito-all-1.9.5.jar +Coverage: http://www.eclemma.org/ (just install the latest in Eclipse)
+JSON-Java.jar (make this jar of the files to be tested yourself) + +*Conventions* Test filenames should consist of the name of the module being tested, with the suffix "Test". For example, Cookie.java is tested by CookieTest.java. When adding a new unit test, don't forget to update JunitTestSuite.java. -The fundamental issues with JSON-Java testing are: +*The fundamental issues with JSON-Java testing are:* * JSONObjects are unordered, making simple string comparison ineffective. * Comparisons via **equals()** is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. * Access to the JSONArray and JSONObject internal containers for comparison is not currently available. From 99927c55162beff1869f377e8ffb10dbf965303a Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 7 Jul 2015 23:15:06 -0500 Subject: [PATCH 132/451] Update README.md --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index fda6f2e..b7be9be 100644 --- a/README.md +++ b/README.md @@ -8,19 +8,19 @@ https://github.com/douglascrockford/JSON-java
*These tests are a work in progress. Help from interested developers is welcome.*
More coverage is needed, but more importantly, improvements to test quality is needed.
-Eclipse is the recommended development environment. +Eclipse is the recommended development environment.
Run individual tests or JunitTestSuite using *EclEmma Coverage*, or execute the TestRunner application directly.
-You will need the following libraries for testing: +You will need the following libraries for testing:
Test harness: http://junit.org
* hamcrest-core-1.3.jar (for Junit) * junit-4.12.jar -Mockery: https://github.com/mockito/mockito +Mockery: https://github.com/mockito/mockito
* mockito-all-1.9.5.jar Coverage: http://www.eclemma.org/ (just install the latest in Eclipse)
-JSON-Java.jar (make this jar of the files to be tested yourself) +JSON-Java.jar (make this jar of the files to be tested yourself)
-*Conventions* +*Conventions*
Test filenames should consist of the name of the module being tested, with the suffix "Test". For example, Cookie.java is tested by CookieTest.java. When adding a new unit test, don't forget to update JunitTestSuite.java. From 6dd85ad5b6bc04031d8fe8c42402c27402fe5a5b Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 7 Jul 2015 23:16:18 -0500 Subject: [PATCH 133/451] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b7be9be..9c27a4f 100644 --- a/README.md +++ b/README.md @@ -20,17 +20,17 @@ Mockery: https://github.com/mockito/mockito
Coverage: http://www.eclemma.org/ (just install the latest in Eclipse)
JSON-Java.jar (make this jar of the files to be tested yourself)
-*Conventions*
+Conventions
Test filenames should consist of the name of the module being tested, with the suffix "Test". For example, Cookie.java is tested by CookieTest.java. When adding a new unit test, don't forget to update JunitTestSuite.java. -*The fundamental issues with JSON-Java testing are:* +The fundamental issues with JSON-Java testing are:
* JSONObjects are unordered, making simple string comparison ineffective. * Comparisons via **equals()** is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. * Access to the JSONArray and JSONObject internal containers for comparison is not currently available. -General issues with unit testing are: +General issues with unit testing are:
* Just writing tests to make coverage goals tends to result in poor tests. * Unit tests are a form of documentation - how a given method actually works is demonstrated by the test. So for a code reviewer or future developer looking at code a good test helps explain how a function is supposed to work according to the original author. This can be difficult if you are not the original developer. * It is difficult to evaluate unit tests in a vacuum. You also need to see the code being tested to understand if a test is good. From 7ed1f78f5f6347ac0102d858eba9eb22c9530bf4 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 7 Jul 2015 23:18:31 -0500 Subject: [PATCH 134/451] Update README.md --- README.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 9c27a4f..758ce72 100644 --- a/README.md +++ b/README.md @@ -9,15 +9,18 @@ https://github.com/douglascrockford/JSON-java
More coverage is needed, but more importantly, improvements to test quality is needed.
Eclipse is the recommended development environment.
-Run individual tests or JunitTestSuite using *EclEmma Coverage*, or execute the TestRunner application directly.
+Run individual tests or JunitTestSuite using EclEmma Coverage, or execute the TestRunner application directly.
-You will need the following libraries for testing:
+**You will need the following libraries for testing:**
Test harness: http://junit.org
-* hamcrest-core-1.3.jar (for Junit) -* junit-4.12.jar +* hamcrest-core-1.3.jar (for Junit)
+* junit-4.12.jar
+ Mockery: https://github.com/mockito/mockito
-* mockito-all-1.9.5.jar +* mockito-all-1.9.5.jar
+ Coverage: http://www.eclemma.org/ (just install the latest in Eclipse)
+ JSON-Java.jar (make this jar of the files to be tested yourself)
Conventions
From 27b22b472471f4b95863ec947fc8d6dcf7564729 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 7 Jul 2015 23:19:37 -0500 Subject: [PATCH 135/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 758ce72..706d80e 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ https://github.com/douglascrockford/JSON-java
More coverage is needed, but more importantly, improvements to test quality is needed.
Eclipse is the recommended development environment.
-Run individual tests or JunitTestSuite using EclEmma Coverage, or execute the TestRunner application directly.
+Run individual tests or JunitTestSuite using EclEmma Coverage, or execute the **TestRunner** application directly.
**You will need the following libraries for testing:**
Test harness: http://junit.org
From ab143af1463383ffffa6699850dd60623f37e4ad Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 7 Jul 2015 23:20:55 -0500 Subject: [PATCH 136/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 706d80e..bd83341 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # JSON-Java-unit-test -*Tests are broken until bigint/bigdec changes are committed in JsonJava*
+**Tests are broken until bigint/bigdec changes are committed in JsonJava** [ETA for go-nogo decision is 9 Jul 2015]
Unit tests to validate the JSON-Java GitHub project code
https://github.com/douglascrockford/JSON-java
From 6cca29202034a9c9fa518b6ac9feffffae00c6e2 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 17 Jul 2015 21:55:50 -0500 Subject: [PATCH 137/451] investigate XML.toString() behavior with null JSONObject values --- JSONObjectTest.java | 83 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index a661312..8557678 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -1469,6 +1469,89 @@ public class JSONObjectTest { assertTrue("Same JSONObject should be equal to itself", aJsonObject.equals(aJsonObject)); } + + @Test + public void jsonObjectNullOperations() { + /** + * The Javadoc for JSONObject.NULL states: + * "JSONObject.NULL is equivalent to the value that JavaScript calls null, + * whilst Java's null is equivalent to the value that JavaScript calls + * undefined." + * + * Standard ECMA-262 6th Edition / June 2015 (included to help explain the javadoc): + * undefined value: primitive value used when a variable has not been assigned a value + * Undefined type: type whose sole value is the undefined value + * null value: primitive value that represents the intentional absence of any object value + * Null type: type whose sole value is the null value + * Java SE8 language spec (included to help explain the javadoc): + * The Kinds of Types and Values ... + * There is also a special null type, the type of the expression null, which has no name. + * Because the null type has no name, it is impossible to declare a variable of the null + * type or to cast to the null type. The null reference is the only possible value of an + * expression of null type. The null reference can always be assigned or cast to any reference type. + * In practice, the programmer can ignore the null type and just pretend that null is merely + * a special literal that can be of any reference type. + * Extensible Markup Language (XML) 1.0 Fifth Edition / 26 November 2008 + * No mention of null + * ECMA-404 1st Edition / October 2013: + * JSON Text ... + * These are three literal name tokens: ... + * null + * + * There seems to be no best practice, it's all about what we want the code to do. + * In the code we see that JSONObject.NULL is tranformed into null + */ + + // add JSONObject.NULL then convert to string in the manner of XML.toString() + JSONObject jsonObjectJONull = new JSONObject(); + Object obj = JSONObject.NULL; + jsonObjectJONull.put("key", obj); + Object value = jsonObjectJONull.opt("key"); + assertTrue("opt() JSONObject.NULL should find JSONObject.NULL", obj.equals(value)); + value = jsonObjectJONull.get("key"); + assertTrue("get() JSONObject.NULL should find JSONObject.NULL", obj.equals(value)); + if (value == null) { + value = ""; + } + String string = value instanceof String ? (String)value : null; + assertTrue("XML toString() should convert JSONObject.NULL to null", string == null); + + // now try it with null + JSONObject jsonObjectNull = new JSONObject(); + obj = null; + jsonObjectNull.put("key", obj); + value = jsonObjectNull.opt("key"); + assertTrue("opt() null should find null", value == null);; + if (value == null) { + value = ""; + } + string = value instanceof String ? (String)value : null; + assertTrue("should convert null to empty string", "".equals(string)); + try { + value = jsonObjectNull.get("key"); + assertTrue("get() null should throw exception", false); + } catch (Exception ignored) {} + + /** + * XML.toString() then goes on to do something with the value + * if the key val is "content", then value.toString() will be + * called. This will evaluate to "null" for JSONObject.NULL, + * and the empty string for null. + * But if the key is anything else, then JSONObject.NULL will be emitted as null + * and null will be emitted as "" + */ + String sJONull = XML.toString(jsonObjectJONull); + assertTrue("JSONObject.NULL should emit a null value", "null".equals(sJONull)); + String sNull = XML.toString(jsonObjectNull); + assertTrue("null should emit an empty string", "".equals(sNull)); + } + + /** + * + */ + private void nullOperations(Object value) { + } + } From 0056b1af94e4e3a128280d70d8c185377c601e96 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 17 Jul 2015 21:58:42 -0500 Subject: [PATCH 138/451] investigate XML.toString() behavior with null JSONObject values --- JSONObjectTest.java | 7 ------- 1 file changed, 7 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 8557678..69b6f0c 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -1545,13 +1545,6 @@ public class JSONObjectTest { String sNull = XML.toString(jsonObjectNull); assertTrue("null should emit an empty string", "".equals(sNull)); } - - /** - * - */ - private void nullOperations(Object value) { - } - } From b06182cb734eb3acbaedc0af2e2421adfe3559d9 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 17 Jul 2015 22:01:52 -0500 Subject: [PATCH 139/451] investigate XML.toString() behavior with null JSONObject values --- JSONObjectTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 69b6f0c..7efd2d8 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -1498,8 +1498,7 @@ public class JSONObjectTest { * These are three literal name tokens: ... * null * - * There seems to be no best practice, it's all about what we want the code to do. - * In the code we see that JSONObject.NULL is tranformed into null + * There seems to be no best practice to follow, it's all about what we want the code to do. */ // add JSONObject.NULL then convert to string in the manner of XML.toString() From 16fa69c0f60d13c371aa0fd42d4bd493b503ff61 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 17 Jul 2015 22:04:01 -0500 Subject: [PATCH 140/451] investigate XML.toString() behavior with null JSONObject values --- JSONObjectTest.java | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 7efd2d8..b818a9e 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -1498,7 +1498,8 @@ public class JSONObjectTest { * These are three literal name tokens: ... * null * - * There seems to be no best practice to follow, it's all about what we want the code to do. + * There seems to be no best practice to follow, it's all about what we + * want the code to do. */ // add JSONObject.NULL then convert to string in the manner of XML.toString() @@ -1506,14 +1507,17 @@ public class JSONObjectTest { Object obj = JSONObject.NULL; jsonObjectJONull.put("key", obj); Object value = jsonObjectJONull.opt("key"); - assertTrue("opt() JSONObject.NULL should find JSONObject.NULL", obj.equals(value)); + assertTrue("opt() JSONObject.NULL should find JSONObject.NULL", + obj.equals(value)); value = jsonObjectJONull.get("key"); - assertTrue("get() JSONObject.NULL should find JSONObject.NULL", obj.equals(value)); + assertTrue("get() JSONObject.NULL should find JSONObject.NULL", + obj.equals(value)); if (value == null) { value = ""; } String string = value instanceof String ? (String)value : null; - assertTrue("XML toString() should convert JSONObject.NULL to null", string == null); + assertTrue("XML toString() should convert JSONObject.NULL to null", + string == null); // now try it with null JSONObject jsonObjectNull = new JSONObject(); @@ -1536,11 +1540,12 @@ public class JSONObjectTest { * if the key val is "content", then value.toString() will be * called. This will evaluate to "null" for JSONObject.NULL, * and the empty string for null. - * But if the key is anything else, then JSONObject.NULL will be emitted as null - * and null will be emitted as "" + * But if the key is anything else, then JSONObject.NULL will be emitted + * as null and null will be emitted as "" */ String sJONull = XML.toString(jsonObjectJONull); - assertTrue("JSONObject.NULL should emit a null value", "null".equals(sJONull)); + assertTrue("JSONObject.NULL should emit a null value", + "null".equals(sJONull)); String sNull = XML.toString(jsonObjectNull); assertTrue("null should emit an empty string", "".equals(sNull)); } From 5eadebb797c761d58ebf73d337566cd3745995e8 Mon Sep 17 00:00:00 2001 From: JaXt0r Date: Sun, 19 Jul 2015 14:24:06 +0200 Subject: [PATCH 141/451] Showing issue of illegal node names with possible underscore-replacement. (Will currently assterted to an Exception). --- XMLTest.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/XMLTest.java b/XMLTest.java index 0c86eeb..1c04c1b 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -294,4 +294,25 @@ public class XMLTest { JSONObject expectedJsonObject = XML.toJSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } + + + /** + * Illegal node-names must be converted to legal XML-node-names. + * The given example shows 2 nodes which are valid for JSON, but not for XML. + * Therefore illegal arguments should be converted to e.g. an underscore (_). + * + */ + @Test + public void shouldHandleIllegalJSONNodeNames() + { + JSONObject inputJSON = new JSONObject(); + inputJSON.append("123IllegalNode", "someValue1"); + inputJSON.append("Illegal@node", "someValue2"); + + String result = XML.toString(inputJSON); + + String expected = "<___IllegalNode>someValue1someValue3"; + + assertEquals(expected, result); + } } From 2c026eb5f8fdf10285cb4505d95b6dce0d99143d Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 19 Jul 2015 08:56:20 -0500 Subject: [PATCH 142/451] Fixed test shouldHandleIllegalJSONNodeNames --- XMLTest.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/XMLTest.java b/XMLTest.java index 1c04c1b..ac17508 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -311,7 +311,13 @@ public class XMLTest { String result = XML.toString(inputJSON); - String expected = "<___IllegalNode>someValue1someValue3"; + /** + * This is invalid XML. Names should not begin with digits or contain + * certain values, including '@'. One possible solution is to replace + * illegal chars with '_', in which case the expected output would be: + * <___IllegalNode>someValue1someValue2 + */ + String expected = "<123IllegalNode>someValue1someValue2"; assertEquals(expected, result); } From f48b6439f682f9941a3bf0516a3ece472bf2f696 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 19 Jul 2015 09:02:27 -0500 Subject: [PATCH 143/451] manual merge of pull request #18 --- XMLTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/XMLTest.java b/XMLTest.java index ac17508..8a56407 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -321,4 +321,20 @@ public class XMLTest { assertEquals(expected, result); } + + @Test + public void shouldHandleNullNodeValue() + { + JSONObject inputJSON = new JSONObject(); + inputJSON.put("nullValue", JSONObject.NULL); + // This is a possible preferred result + String expectedXML = ""; + String actualXML = "null"; + /** + * This is the current behavior. JSONObject.NULL is emitted as + * the string, "null". + */ + String resultXML = XML.toString(inputJSON); + assertEquals(actualXML, resultXML); + } } From b9c6f335ee832e1db56a3db4a84657323b82fc2f Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 19 Jul 2015 09:04:10 -0500 Subject: [PATCH 144/451] fixed comment location --- XMLTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/XMLTest.java b/XMLTest.java index 8a56407..6dc3842 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -329,11 +329,11 @@ public class XMLTest { inputJSON.put("nullValue", JSONObject.NULL); // This is a possible preferred result String expectedXML = ""; - String actualXML = "null"; /** * This is the current behavior. JSONObject.NULL is emitted as * the string, "null". */ + String actualXML = "null"; String resultXML = XML.toString(inputJSON); assertEquals(actualXML, resultXML); } From b39c3df766875d58abcfeb27c49489e4c051e081 Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 20 Jul 2015 23:14:15 -0500 Subject: [PATCH 145/451] document behavior of content keyword --- XMLTest.java | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/XMLTest.java b/XMLTest.java index 6dc3842..1ba88b1 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -328,7 +328,7 @@ public class XMLTest { JSONObject inputJSON = new JSONObject(); inputJSON.put("nullValue", JSONObject.NULL); // This is a possible preferred result - String expectedXML = ""; + // String expectedXML = ""; /** * This is the current behavior. JSONObject.NULL is emitted as * the string, "null". @@ -337,4 +337,89 @@ public class XMLTest { String resultXML = XML.toString(inputJSON); assertEquals(actualXML, resultXML); } -} + + @Test + public void contentOperations() { + /** + * Make sure we understand exactly how the "content" keyword works + */ + + /** + * When a standalone 0) then return]]>"; + JSONObject jsonObject = XML.toJSONObject(xmlStr); + assertTrue("1. 3 items", 3 == jsonObject.length()); + assertTrue("1. empty tag1", "".equals(jsonObject.get("tag1"))); + assertTrue("1. empty tag2", "".equals(jsonObject.get("tag2"))); + assertTrue("1. content found", "if (a < b && a > 0) then return".equals(jsonObject.get("content"))); + + // multiple consecutive standalone cdatas are accumulated into an array + xmlStr = " 0) then return]]>"; + jsonObject = XML.toJSONObject(xmlStr); + assertTrue("2. 3 items", 3 == jsonObject.length()); + assertTrue("2. empty tag1", "".equals(jsonObject.get("tag1"))); + assertTrue("2. empty tag2", "".equals(jsonObject.get("tag2"))); + assertTrue("2. content array found", jsonObject.get("content") instanceof JSONArray); + JSONArray jsonArray = jsonObject.getJSONArray("content"); + assertTrue("2. array size", jsonArray.length() == 2); + assertTrue("2. content array entry 1", "if (a < b && a > 0) then return".equals(jsonArray.get(0))); + assertTrue("2. content array entry 2", "here is another cdata".equals(jsonArray.get(1))); + + /** + * text content is accumulated in a "content" inside a local JSONObject. + * If there is only one instance, it is saved in the context (a different JSONObject + * from the calling code. and the content element is discarded. + */ + xmlStr = "value 1"; + jsonObject = XML.toJSONObject(xmlStr); + assertTrue("3. 2 items", 1 == jsonObject.length()); + assertTrue("3. value tag1", "value 1".equals(jsonObject.get("tag1"))); + + /** + * array-style text content (multiple tags with the same name) is + * accumulated in a local JSONObject with key="content" and value=JSONArray, + * saved in the context, and then the local JSONObject is discarded. + */ + xmlStr = "value 12true"; + jsonObject = XML.toJSONObject(xmlStr); + assertTrue("4. 1 item", 1 == jsonObject.length()); + assertTrue("4. content array found", jsonObject.get("tag1") instanceof JSONArray); + jsonArray = jsonObject.getJSONArray("tag1"); + assertTrue("4. array size", jsonArray.length() == 3); + assertTrue("4. content array entry 1", "value 1".equals(jsonArray.get(0))); + assertTrue("4. content array entry 2", jsonArray.getInt(1) == 2); + assertTrue("4. content array entry 2", jsonArray.getBoolean(2) == true); + + /** + * Complex content is accumulated in a "content" field. For example, an element + * may contain a mix of child elements and text. Each text segment is + * accumulated to content. + */ + xmlStr = "val1val2"; + jsonObject = XML.toJSONObject(xmlStr); + assertTrue("5. 1 item", 1 == jsonObject.length()); + assertTrue("5. jsonObject found", jsonObject.get("tag1") instanceof JSONObject); + jsonObject = jsonObject.getJSONObject("tag1"); + assertTrue("5. 2 contained items", 2 == jsonObject.length()); + assertTrue("5. contained tag", "".equals(jsonObject.get("tag2"))); + assertTrue("5. contained content jsonArray found", jsonObject.get("content") instanceof JSONArray); + jsonArray = jsonObject.getJSONArray("content"); + assertTrue("5. array size", jsonArray.length() == 2); + assertTrue("5. content array entry 1", "val1".equals(jsonArray.get(0))); + assertTrue("5. content array entry 2", "val2".equals(jsonArray.get(1))); + + /** + * If there is only 1 complex text content, then it is accumulated in a + * "content" field as a string. + */ + xmlStr = "val1"; + jsonObject = XML.toJSONObject(xmlStr); + assertTrue("6. 1 item", 1 == jsonObject.length()); + assertTrue("6. jsonObject found", jsonObject.get("tag1") instanceof JSONObject); + jsonObject = jsonObject.getJSONObject("tag1"); + assertTrue("6. contained content found", "val1".equals(jsonObject.get("content"))); + assertTrue("6. contained tag2", "".equals(jsonObject.get("tag2"))); + } +} \ No newline at end of file From 0361cc58d696ce6cb7d94c0824c56945c1283e3e Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 20 Jul 2015 23:31:52 -0500 Subject: [PATCH 146/451] one more test - and a bug? --- XMLTest.java | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/XMLTest.java b/XMLTest.java index 1ba88b1..ab959ab 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -364,8 +364,8 @@ public class XMLTest { assertTrue("2. content array found", jsonObject.get("content") instanceof JSONArray); JSONArray jsonArray = jsonObject.getJSONArray("content"); assertTrue("2. array size", jsonArray.length() == 2); - assertTrue("2. content array entry 1", "if (a < b && a > 0) then return".equals(jsonArray.get(0))); - assertTrue("2. content array entry 2", "here is another cdata".equals(jsonArray.get(1))); + assertTrue("2. content array entry 0", "if (a < b && a > 0) then return".equals(jsonArray.get(0))); + assertTrue("2. content array entry 1", "here is another cdata".equals(jsonArray.get(1))); /** * text content is accumulated in a "content" inside a local JSONObject. @@ -388,8 +388,8 @@ public class XMLTest { assertTrue("4. content array found", jsonObject.get("tag1") instanceof JSONArray); jsonArray = jsonObject.getJSONArray("tag1"); assertTrue("4. array size", jsonArray.length() == 3); - assertTrue("4. content array entry 1", "value 1".equals(jsonArray.get(0))); - assertTrue("4. content array entry 2", jsonArray.getInt(1) == 2); + assertTrue("4. content array entry 0", "value 1".equals(jsonArray.get(0))); + assertTrue("4. content array entry 1", jsonArray.getInt(1) == 2); assertTrue("4. content array entry 2", jsonArray.getBoolean(2) == true); /** @@ -407,8 +407,8 @@ public class XMLTest { assertTrue("5. contained content jsonArray found", jsonObject.get("content") instanceof JSONArray); jsonArray = jsonObject.getJSONArray("content"); assertTrue("5. array size", jsonArray.length() == 2); - assertTrue("5. content array entry 1", "val1".equals(jsonArray.get(0))); - assertTrue("5. content array entry 2", "val2".equals(jsonArray.get(1))); + assertTrue("5. content array entry 0", "val1".equals(jsonArray.get(0))); + assertTrue("5. content array entry 1", "val2".equals(jsonArray.get(1))); /** * If there is only 1 complex text content, then it is accumulated in a @@ -421,5 +421,22 @@ public class XMLTest { jsonObject = jsonObject.getJSONObject("tag1"); assertTrue("6. contained content found", "val1".equals(jsonObject.get("content"))); assertTrue("6. contained tag2", "".equals(jsonObject.get("tag2"))); - } + + /** + * In this corner case, the content sibling happens to have key=content + * We end up with an array within an array, and no content element. + * This is probably a bug. + */ + xmlStr = "val1"; + jsonObject = XML.toJSONObject(xmlStr); + assertTrue("7. 1 item", 1 == jsonObject.length()); + assertTrue("7. jsonArray found", jsonObject.get("tag1") instanceof JSONArray); + jsonArray = jsonObject.getJSONArray("tag1"); + assertTrue("array size 1", jsonArray.length() == 1); + assertTrue("7. contained array found", jsonArray.get(0) instanceof JSONArray); + jsonArray = jsonArray.getJSONArray(0); + assertTrue("7. inner array size 2", jsonArray.length() == 2); + assertTrue("7. inner array item 0", "val1".equals(jsonArray.get(0))); + assertTrue("7. inner array item 1", "".equals(jsonArray.get(1))); +} } \ No newline at end of file From 752f66746b6fa921af49e85b692a115fb6d6344b Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 21 Jul 2015 09:12:16 -0500 Subject: [PATCH 147/451] Update README.md --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index bd83341..75d7861 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,5 @@ # JSON-Java-unit-test -**Tests are broken until bigint/bigdec changes are committed in JsonJava** [ETA for go-nogo decision is 9 Jul 2015]
- Unit tests to validate the JSON-Java GitHub project code
https://github.com/douglascrockford/JSON-java
From 4e38ed01e57c3061890c6d1ed1a5c9b38bf79d8d Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 22 Jul 2015 19:47:12 -0500 Subject: [PATCH 148/451] tests for enum-support --- EnumTest.java | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/EnumTest.java b/EnumTest.java index 14605b1..e7bb0cd 100644 --- a/EnumTest.java +++ b/EnumTest.java @@ -195,6 +195,7 @@ public class EnumTest { Util.compareActualVsExpectedJsonArrays(actualJsonArray, expectedJsonArray); } + @Test public void wrap() { /** * Wrap should handle enums exactly the same way as the JSONObject(Object) @@ -218,4 +219,54 @@ public class EnumTest { expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + + @Test + public void enumAPI() { + /** + * Exercise the proposed enum API methods + */ + MyEnumClass myEnumClass = new MyEnumClass(); + myEnumClass.setMyEnum(MyEnum.VAL1); + MyEnumField myEnumField = MyEnumField.VAL2; + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("strKey", "value"); + jsonObject.put("enumKey", myEnumField); + jsonObject.put("enumClassKey", myEnumClass); + + // get a plain old enum + MyEnumField actualEnum = jsonObject.getEnum(MyEnumField.class, "enumKey"); + assertTrue("get myEnumField", actualEnum == MyEnumField.VAL2); + + // try to get the wrong value + try { + actualEnum = jsonObject.getEnum(MyEnumField.class, "strKey"); + assertTrue("should throw an exception for wrong key", false); + } catch (Exception ignored) {} + + // get a class that contains an enum + MyEnumClass actualEnumClass = (MyEnumClass)jsonObject.get("enumClassKey"); + assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1); + + // opt a plain old enum + actualEnum = jsonObject.optEnum(MyEnumField.class, "enumKey"); + assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2); + + // opt the wrong value + actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey"); + assertTrue("opt null", actualEnum == null); + + // opt a class that contains an enum + actualEnumClass = (MyEnumClass)jsonObject.opt("enumClassKey"); + assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1); + + // opt with default a plain old enum + actualEnum = jsonObject.optEnum(MyEnumField.class, "enumKey", null); + assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2); + + // opt with default the wrong value + actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey", null); + assertTrue("opt null", actualEnum == null); + + } } From 8ac8c34e9f75f5737d55b5d98668f16c0ff0fcdc Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 22 Jul 2015 20:12:10 -0500 Subject: [PATCH 149/451] tests for enum-support --- EnumTest.java | 47 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/EnumTest.java b/EnumTest.java index e7bb0cd..469ba9d 100644 --- a/EnumTest.java +++ b/EnumTest.java @@ -222,13 +222,13 @@ public class EnumTest { @Test public void enumAPI() { - /** - * Exercise the proposed enum API methods - */ MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); MyEnumField myEnumField = MyEnumField.VAL2; + /** + * Exercise the proposed enum API methods on JSONObject + */ JSONObject jsonObject = new JSONObject(); jsonObject.put("strKey", "value"); jsonObject.put("enumKey", myEnumField); @@ -268,5 +268,46 @@ public class EnumTest { actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey", null); assertTrue("opt null", actualEnum == null); + /** + * Exercise the proposed enum API methods on JSONArray + */ + JSONArray jsonArray = new JSONArray(); + jsonArray.put("value"); + jsonArray.put(myEnumField); + jsonArray.put(myEnumClass); + + // get a plain old enum + actualEnum = jsonArray.getEnum(MyEnumField.class, 1); + assertTrue("get myEnumField", actualEnum == MyEnumField.VAL2); + + // try to get the wrong value + try { + actualEnum = jsonArray.getEnum(MyEnumField.class, 0); + assertTrue("should throw an exception for wrong index", false); + } catch (Exception ignored) {} + + // get a class that contains an enum + actualEnumClass = (MyEnumClass)jsonArray.get(2); + assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1); + + // opt a plain old enum + actualEnum = jsonArray.optEnum(MyEnumField.class, 1); + assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2); + + // opt the wrong value + actualEnum = jsonArray.optEnum(MyEnumField.class, 0); + assertTrue("opt null", actualEnum == null); + + // opt a class that contains an enum + actualEnumClass = (MyEnumClass)jsonArray.opt(2); + assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1); + + // opt with default a plain old enum + actualEnum = jsonArray.optEnum(MyEnumField.class, 1, null); + assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2); + + // opt with default the wrong value + actualEnum = jsonArray.optEnum(MyEnumField.class, 0, null); + assertTrue("opt null", actualEnum == null); } } From 1f4e8368631660b368c0c353ed038fffd027cb66 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 22 Jul 2015 20:24:45 -0500 Subject: [PATCH 150/451] few more enum support tests --- EnumTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/EnumTest.java b/EnumTest.java index 469ba9d..6b7cc6b 100644 --- a/EnumTest.java +++ b/EnumTest.java @@ -268,6 +268,10 @@ public class EnumTest { actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey", null); assertTrue("opt null", actualEnum == null); + // opt with default an index that does not exist + actualEnum = jsonObject.optEnum(MyEnumField.class, "noKey", null); + assertTrue("opt null", actualEnum == null); + /** * Exercise the proposed enum API methods on JSONArray */ @@ -309,5 +313,10 @@ public class EnumTest { // opt with default the wrong value actualEnum = jsonArray.optEnum(MyEnumField.class, 0, null); assertTrue("opt null", actualEnum == null); + + // opt with default an index that does not exist + actualEnum = jsonArray.optEnum(MyEnumField.class, 3, null); + assertTrue("opt null", actualEnum == null); + } } From f69466f4c215b58bafddac537f7064cf90310679 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 22 Jul 2015 21:21:23 -0500 Subject: [PATCH 151/451] recreate original documented issue --- XMLTest.java | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/XMLTest.java b/XMLTest.java index ab959ab..58ddee5 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -438,5 +438,47 @@ public class XMLTest { assertTrue("7. inner array size 2", jsonArray.length() == 2); assertTrue("7. inner array item 0", "val1".equals(jsonArray.get(0))); assertTrue("7. inner array item 1", "".equals(jsonArray.get(1))); -} + + /** + * Confirm behavior of original issue + */ + String jsonStr = + "{"+ + "\"Profile\": {"+ + "\"list\": {"+ + "\"history\": {"+ + "\"entries\": ["+ + "{"+ + "\"deviceId\": \"id\","+ + "\"content\": {"+ + "\"material\": ["+ + "{"+ + "\"stuff\": false"+ + "}"+ + "]"+ + "}"+ + "}"+ + "]"+ + "}"+ + "}"+ + "}"+ + "}"; + jsonObject = new JSONObject(jsonStr); + xmlStr = XML.toString(jsonObject); + /** + * This is the created XML. Looks like content was mistaken for + * complex (child node + text) XML. + * + * + * + * + * id + * {"material":[{"stuff":false}]} + * + * + * + * + */ + assertTrue("nothing to test here, see comment on created XML, above", true); + } } \ No newline at end of file From ee0a53d4948503fcbbd206013db9fd4919fc9c6b Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 8 Aug 2015 08:13:22 -0500 Subject: [PATCH 152/451] Verify exception messages. Move method comments so JavaDoc will pick them up. --- CDLTest.java | 132 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 78 insertions(+), 54 deletions(-) diff --git a/CDLTest.java b/CDLTest.java index d218b10..340977b 100644 --- a/CDLTest.java +++ b/CDLTest.java @@ -42,113 +42,137 @@ public class CDLTest { "{Col 1:\"0.23\", Col 2:\"57.42\", Col 3:\"5e27\", Col 4:\"-234.879\", Col 5:\"2.34e5\", Col 6:\"0.0\", Col 7:\"9e-3\"}, "+ "{Col 1:\"va\tl1\", Col 2:\"v\bal2\", Col 3:val3, Col 4:\"val\f4\", Col 5:val5, Col 6:va\'l6, Col 7:val7}]"); + /** + * Attempts to create a JSONArray from a null string. + * Expect a NullPointerException. + */ @Test(expected=NullPointerException.class) public void exceptionOnNullString() { - /** - * Attempts to create a JSONArray from a null string - */ String nullStr = null; CDL.toJSONArray(nullStr); } - @Test(expected=JSONException.class) + /** + * Attempts to create a JSONArray from a string with unbalanced quotes + * in column title line. Expects a JSONException. + */ + @Test public void unbalancedQuoteInName() { - /** - * Attempts to create a JSONArray from a string with unbalanced quotes - * in column title line - */ String badLine = "Col1, \"Col2\nVal1, Val2"; - CDL.toJSONArray(badLine); + try { + CDL.toJSONArray(badLine); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Missing close quote '\"'. at 12 [character 0 line 2]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Attempts to create a JSONArray from a string with unbalanced quotes + * in value line. Expects a JSONException. + */ + @Test public void unbalancedQuoteInValue() { - /** - * Attempts to create a JSONArray from a string with unbalanced quotes - * in value line - */ String badLine = "Col1, Col2\n\"Val1, Val2"; - CDL.toJSONArray(badLine); + try { + CDL.toJSONArray(badLine); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Missing close quote '\"'. at 23 [character 12 line 3]". + equals(e.getMessage())); + + } } - @Test(expected=JSONException.class) + /** + * Attempts to create a JSONArray from a string with null char + * in column title line. Expects a JSONException. + */ + @Test public void nullInName() { - /** - * Attempts to create a JSONArray from a string with null char - * in column title line - */ String badLine = "C\0ol1, Col2\nVal1, Val2"; - CDL.toJSONArray(badLine); + try { + CDL.toJSONArray(badLine); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Bad character 'o' (111). at 3 [character 4 line 1]". + equals(e.getMessage())); + + } } + /** + * call toString with a null array + */ @Test(expected=NullPointerException.class) public void nullJSONArrayToString() { - /** - * call toString with a null array - */ CDL.toString((JSONArray)null); } + /** + * Create a JSONArray from an empty string + */ @Test public void emptyString() { - /** - * Create a JSONArray from an empty string - */ String emptyStr = ""; JSONArray jsonArray = CDL.toJSONArray(emptyStr); assertTrue("CDL should return null when the input string is empty", jsonArray == null); } + /** + * Create a JSONArray with only 1 row + */ @Test public void onlyColumnNames() { - /** - * Create a JSONArray with only 1 row - */ String columnNameStr = "col1, col2, col3"; JSONArray jsonArray = CDL.toJSONArray(columnNameStr); assertTrue("CDL should return null when only 1 row is given", jsonArray == null); } + /** + * Create a JSONArray from string containing only whitespace and commas + */ @Test public void emptyLinesToJSONArray() { - /** - * Create a JSONArray from string containing only whitespace and commas - */ String str = " , , , \n , , , "; JSONArray jsonArray = CDL.toJSONArray(str); assertTrue("JSONArray should be null for no content", jsonArray == null); } + /** + * call toString with a null array + */ @Test public void emptyJSONArrayToString() { - /** - * call toString with a null array - */ JSONArray jsonArray = new JSONArray(); String str = CDL.toString(jsonArray); assertTrue("CDL should return null for toString(null)", str == null); } + /** + * call toString with a null arrays for names and values + */ @Test public void nullJSONArraysToString() { - /** - * call toString with a null arrays for names and values - */ String str = CDL.toString(null, null); assertTrue("CDL should return null for toString(null)", str == null); } + /** + * Given a JSONArray that was not built by CDL, some chars may be + * found that would otherwise be filtered out by CDL. + */ @Test public void checkSpecialChars() { - /** - * Given a JSONArray that was not built by CDL, some chars may be - * found that would otherwise be filtered out by CDL. - */ JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); jsonArray.put(jsonObject); @@ -165,22 +189,22 @@ public class CDLTest { assertTrue(cdlStr.contains("\"V2\"")); } + /** + * Create a JSONArray from a string of lines + */ @Test public void textToJSONArray() { - /** - * Create a JSONArray from a string of lines - */ JSONArray jsonArray = CDL.toJSONArray(lines); JSONArray expectedJsonArray = new JSONArray(expectedLines); Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } + /** + * Create a JSONArray from a JSONArray of titles and a + * string of value lines + */ @Test public void jsonArrayToJSONArray() { - /** - * Create a JSONArray from a JSONArray of titles and a - * string of value lines - */ String nameArrayStr = "[Col1, Col2]"; String values = "V1, V2"; JSONArray nameJSONArray = new JSONArray(nameArrayStr); @@ -189,12 +213,12 @@ public class CDLTest { Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } + /** + * Create a JSONArray from a string of lines, + * then convert to string and then back to JSONArray + */ @Test public void textToJSONArrayAndBackToString() { - /** - * Create a JSONArray from a string of lines, - * then convert to string and then back to JSONArray - */ JSONArray jsonArray = CDL.toJSONArray(lines); String jsonStr = CDL.toString(jsonArray); JSONArray finalJsonArray = CDL.toJSONArray(jsonStr); From a0108f3e8e9e2d3bf1bac7dabdd6226b34c718d1 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 8 Aug 2015 09:32:15 -0500 Subject: [PATCH 153/451] Verify exception messages. Move method comments so JavaDoc will pick them up. --- CookieListTest.java | 80 +++++++++++++++++++++++++++++---------------- 1 file changed, 52 insertions(+), 28 deletions(-) diff --git a/CookieListTest.java b/CookieListTest.java index 0eaef71..1d7ad8a 100644 --- a/CookieListTest.java +++ b/CookieListTest.java @@ -6,60 +6,70 @@ import org.json.*; import org.junit.Test; /** - * HTTP cookie specification: RFC6265 - * + * HTTP cookie specification RFC6265: http://tools.ietf.org/html/rfc6265 + *

* A cookie list is a JSONObject whose members are presumed to be cookie * name/value pairs. Entries are unescaped while being added, and escaped in * the toString() output. * Unescaping means to convert %hh hex strings to the ascii equivalent * and converting '+' to ' '. * Escaping converts '+', '%', '=', ';' and ascii control chars to %hh hex strings. - * - * CookieList should not be considered as just a list of Cookie objects: + *

+ * CookieList should not be considered as just a list of Cookie objects:
* - CookieList stores a cookie name/value pair as a single entry; Cookie stores - * it as 2 entries (key="name" and key="value"). + * it as 2 entries (key="name" and key="value").
* - CookieList requires multiple name/value pairs as input; Cookie allows the - * 'secure' name with no associated value - * - CookieList has no special handling for attribute name/value pairs. + * 'secure' name with no associated value
+ * - CookieList has no special handling for attribute name/value pairs.
*/ public class CookieListTest { + /** + * Attempts to create a CookieList from a null string. + * Expects a NullPointerException. + */ @Test(expected=NullPointerException.class) public void nullCookieListException() { - /** - * Attempts to create a CookieList from a null string - */ String cookieStr = null; CookieList.toJSONObject(cookieStr); } - @Test(expected=JSONException.class) + /** + * Attempts to create a CookieList from a malformed string. + * Expects a JSONException. + */ + @Test public void malFormedCookieListException() { - /** - * Attempts to create a CookieList from a malformed string - */ String cookieStr = "thisCookieHasNoEqualsChar"; - CookieList.toJSONObject(cookieStr); + try { + CookieList.toJSONObject(cookieStr); + assertTrue("should throw an exception", false); + } catch (JSONException e) { + /** + * Not sure of the missing char, but full string compare fails + */ + assertTrue("Expecting an exception message", + e.getMessage().startsWith("Expected '=' and instead saw '") && + e.getMessage().endsWith("' at 27 [character 28 line 1]")); + } } - @Test(expected=JSONException.class) + /** + * Creates a CookieList from an empty string. + */ + @Test public void emptyStringCookieList() { - /** - * Creates a CookieList from an empty string. - * Cookie throws an exception, but CookieList does not - */ String cookieStr = ""; String expectedCookieStr = ""; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + assertTrue(jsonObject.length() == 0); } + /** + * CookieList with the simplest cookie - a name/value pair with no delimiter. + */ @Test public void simpleCookieList() { - /** - * The simplest cookie is a name/value pair with no delimiter - */ String cookieStr = "SID=31d4d96e407aad42"; String expectedCookieStr = "{\"SID\":\"31d4d96e407aad42\"}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); @@ -67,11 +77,11 @@ public class CookieListTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * CookieList with a single a cookie which has a name/value pair and delimiter. + */ @Test public void simpleCookieListWithDelimiter() { - /** - * The simplest cookie is a name/value pair with a delimiter - */ String cookieStr = "SID=31d4d96e407aad42;"; String expectedCookieStr = "{\"SID\":\"31d4d96e407aad42\"}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); @@ -79,6 +89,10 @@ public class CookieListTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * CookieList with multiple cookies consisting of name/value pairs + * with delimiters. + */ @Test public void multiPartCookieList() { String cookieStr = @@ -102,6 +116,9 @@ public class CookieListTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * CookieList from a JSONObject with valid key and null value + */ @Test public void convertCookieListWithNullValueToString() { JSONObject jsonObject = new JSONObject(); @@ -110,6 +127,9 @@ public class CookieListTest { assertTrue("toString() should be empty", "".equals(cookieToStr)); } + /** + * CookieList with multiple entries converted to a JSON document. + */ @Test public void convertCookieListToString() { String cookieStr = @@ -136,6 +156,10 @@ public class CookieListTest { Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } + /** + * CookieList with multiple entries and some '+' chars and URL-encoded + * values converted to a JSON document. + */ @Test public void convertEncodedCookieListToString() { String cookieStr = From f66cc8d5c4fea0deb96fe06c4eca6bc61673af35 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 8 Aug 2015 10:22:17 -0500 Subject: [PATCH 154/451] Verify exception messages. Move method comments so JavaDoc will pick them up. --- CookieTest.java | 133 +++++++++++++++++++++++++++++------------------- 1 file changed, 80 insertions(+), 53 deletions(-) diff --git a/CookieTest.java b/CookieTest.java index c96bd72..9104b60 100644 --- a/CookieTest.java +++ b/CookieTest.java @@ -10,61 +10,88 @@ import org.junit.Test; /** * HTTP cookie specification: RFC6265 - * + *

* At its most basic, a cookie is a name=value pair. The value may be subdivided * into other cookies, but that is not tested here. The cookie may also include * certain named attributes, delimited by semicolons. - * + *

* The Cookie.toString() method emits certain attributes if present: expires, * domain, path, secure. All but secure are name-value pairs. Other attributes * are not included in the toString() output. - * + *

* A JSON-Java encoded cookie escapes '+', '%', '=', ';' with %hh values. */ public class CookieTest { + /** + * Attempts to create a JSONObject from a null string. + * Expects a NullPointerException. + */ @Test(expected=NullPointerException.class) public void nullCookieException() { - /** - * Attempts to create a JSONObject from a null string - */ String cookieStr = null; Cookie.toJSONObject(cookieStr); } - @Test(expected=JSONException.class) + /** + * Attempts to create a JSONObject from a cookie string with + * no '=' char. + * Expects a JSONException. + */ + @Test public void malFormedNameValueException() { - /** - * Attempts to create a JSONObject from a malformed cookie string - */ String cookieStr = "thisCookieHasNoEqualsChar"; - Cookie.toJSONObject(cookieStr); + try { + Cookie.toJSONObject(cookieStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + e.getMessage().startsWith("Expected '=' and instead saw '") + && e.getMessage().endsWith("' at 27 [character 28 line 1]")); + } } - @Test(expected=JSONException.class) + /** + * Attempts to create a JSONObject from a cookie string + * with embedded ';' char. + * Expects a JSONException. + */ + @Test public void malFormedAttributeException() { - /** - * Attempts to create a JSONObject from a malformed cookie string - */ String cookieStr = "this=Cookie;myAttribute"; - Cookie.toJSONObject(cookieStr); + try { + Cookie.toJSONObject(cookieStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Missing '=' in cookie parameter. at 25 [character 26 line 1]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Attempts to create a JSONObject from an empty cookie string.
+ * Note: Cookie throws an exception, but CookieList does not.
+ * Expects a JSONException + */ + @Test public void emptyStringCookieException() { - /** - * Attempts to create a JSONObject from an empty cookie string - * Note: Cookie throws an exception, but CookieList does not - */ String cookieStr = ""; - Cookie.toJSONObject(cookieStr); + try { + Cookie.toJSONObject(cookieStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + e.getMessage().startsWith("Expected '=' and instead saw '") && + e.getMessage().endsWith("' at 2 [character 3 line 1]")); + } } + /** + * Cookie from a simple name/value pair with no delimiter + */ @Test public void simpleCookie() { - /** - * The simplest cookie is a name/value pair with no delimiter - */ String cookieStr = "SID=31d4d96e407aad42"; String expectedCookieStr = "{\"name\":\"SID\",\"value\":\"31d4d96e407aad42\"}"; JSONObject jsonObject = Cookie.toJSONObject(cookieStr); @@ -72,13 +99,13 @@ public class CookieTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * Store a cookie with all of the supported attributes in a + * JSONObject. The secure attribute, which has no value, is treated + * as a boolean. + */ @Test public void multiPartCookie() { - /** - * Store a cookie with all of the supported attributes in a - * JSONObject. The secure attribute, which has no value, is treated - * as a boolean. - */ String cookieStr = "PH=deleted; "+ " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ @@ -99,13 +126,13 @@ public class CookieTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * Cookie.toString() will omit the non-standard "thiswont=beIncluded" + * attribute, but the attribute is still stored in the JSONObject. + * This test confirms both behaviors. + */ @Test public void convertCookieToString() { - /** - * ToString() will omit the non-standard "thiswont=beIncluded" - * attribute, but the attribute is still stored in the JSONObject. - * This test confirms both behaviors. - */ String cookieStr = "PH=deleted; "+ " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ @@ -138,14 +165,14 @@ public class CookieTest { Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } + /** + * A string may be URL-encoded when converting to JSONObject. + * If found, '+' is converted to ' ', and %hh hex strings are converted + * to their ascii char equivalents. This test confirms the decoding + * behavior. + */ @Test public void convertEncodedCookieToString() { - /** - * A string may be URL-encoded when converting to JSONObject. - * If found, '+' is converted to ' ', and %hh hex strings are converted - * to their ascii char equivalents. This test confirms the decoding - * behavior. - */ String cookieStr = "PH=deleted; "+ " expires=Wed,+19-Mar-2014+17:53:53+GMT;"+ @@ -167,14 +194,14 @@ public class CookieTest { Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } + /** + * A public API method performs a URL encoding for selected chars + * in a string. Control chars, '+', '%', '=', ';' are all encoded + * as %hh hex strings. The string is also trimmed. + * This test confirms that behavior. + */ @Test public void escapeString() { - /** - * A public API method performs a URL encoding for selected chars - * in a string. Control chars, '+', '%', '=', ';' are all encoded - * as %hh hex strings. The string is also trimmed. - * This test confirms that behavior. - */ String str = " +%\r\n\t\b%=;;; "; String expectedStr = "%2b%25%0d%0a%09%08%25%3d%3b%3b%3b"; String actualStr = Cookie.escape(str); @@ -182,14 +209,14 @@ public class CookieTest { " expected: " +expectedStr, expectedStr.equals(actualStr)); } + /** + * A public API method performs URL decoding for strings. + * '+' is converted to space and %hh hex strings are converted to + * their ascii equivalent values. The string is not trimmed. + * This test confirms that behavior. + */ @Test public void unescapeString() { - /** - * A public API method performs URL decoding for strings. - * '+' is converted to space and %hh hex strings are converted to - * their ascii equivalent values. The string is not trimmed. - * This test confirms that behavior. - */ String str = " +%2b%25%0d%0a%09%08%25%3d%3b%3b%3b+ "; String expectedStr = " +%\r\n\t\b%=;;; "; String actualStr = Cookie.unescape(str); From 9ce62b954047eafda5d8eccdc1576c2102ae0593 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 8 Aug 2015 10:30:20 -0500 Subject: [PATCH 155/451] Move method comments so JavaDoc will pick them up. --- EnumTest.java | 68 +++++++++++++++++++++++++++++---------------------- 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/EnumTest.java b/EnumTest.java index 6b7cc6b..d24824b 100644 --- a/EnumTest.java +++ b/EnumTest.java @@ -11,14 +11,14 @@ import org.junit.*; * These tests explore how enum serialization works with JSON-Java. */ public class EnumTest { + + /** + * To serialize an enum by its getters, use the JSONObject Object constructor. + * The JSONObject ctor handles enum like any other bean. A JSONobject + * is created whose entries are the getter name/value pairs. + */ @Test public void jsonObjectFromEnum() { - /** - * To serialize an enum by its getters, use the JSONObject Object constructor. - * The JSONObject ctor handles enum like any other bean. A JSONobject - * is created whose entries are the getter name/value pairs. - */ - // If there are no getters then the object is empty. MyEnum myEnum = MyEnum.VAL2; JSONObject jsonObject = new JSONObject(myEnum); @@ -44,12 +44,12 @@ public class EnumTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * To serialize an enum by its set of allowed values, use getNames() + * and the the JSONObject Object with names constructor. + */ @Test public void jsonObjectFromEnumWithNames() { - /** - * To serialize an enum by its set of allowed values, use getNames() - * and the the JSONObject Object with names constructor. - */ String [] names; String expectedStr; JSONObject jsonObject; @@ -74,12 +74,13 @@ public class EnumTest { expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedJsonObject); } + + /** + * To serialize by assigned value, use the put() methods. The value + * will be stored as a enum type. + */ @Test public void enumPut() { - /** - * To serialize by assigned value, use the put() methods. The value - * will be stored as a enum type. - */ String expectedFinalStr = "{\"myEnum\":\"VAL2\", \"myEnumField\":\"VAL1\"}"; JSONObject jsonObject = new JSONObject(); MyEnum myEnum = MyEnum.VAL2; @@ -106,12 +107,12 @@ public class EnumTest { assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.remove(1))); } + /** + * The default action of valueToString() is to call object.toString(). + * For enums, this means the assigned value will be returned as a string. + */ @Test public void enumValueToString() { - /** - * The default action of valueToString() is to call object.toString(). - * For enums, this means the assigned value will be returned as a string. - */ String expectedStr1 = "\"VAL1\""; String expectedStr2 = "\"VAL1\""; MyEnum myEnum = MyEnum.VAL1; @@ -137,12 +138,12 @@ public class EnumTest { str3.startsWith(expectedStr3)); } + /** + * In whatever form the enum was added to the JSONObject or JSONArray, + * json[Object|Array].toString should serialize it in a reasonable way. + */ @Test public void enumToString() { - /** - * In whatever form the enum was added to the JSONObject or JSONArray, - * json[Object|Array].toString should serialize it in a reasonable way. - */ MyEnum myEnum = MyEnum.VAL2; JSONObject jsonObject = new JSONObject(myEnum); String expectedStr = "{}"; @@ -195,12 +196,12 @@ public class EnumTest { Util.compareActualVsExpectedJsonArrays(actualJsonArray, expectedJsonArray); } + /** + * Wrap should handle enums exactly the same way as the JSONObject(Object) + * constructor. + */ @Test public void wrap() { - /** - * Wrap should handle enums exactly the same way as the JSONObject(Object) - * constructor. - */ MyEnum myEnum = MyEnum.VAL2; JSONObject jsonObject = (JSONObject)JSONObject.wrap(myEnum); assertTrue("simple enum has no getters", jsonObject.length() == 0); @@ -220,15 +221,24 @@ public class EnumTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * It was determined that some API methods should be added to + * support enums:
+ * JSONObject.getEnum(class, key)
+ * JSONObject.optEnum(class, key)
+ * JSONObject.optEnum(class, key, default)
+ * JSONArray.getEnum(class, index)
+ * JSONArray.optEnum(class, index)
+ * JSONArray.optEnum(class, index, default)
+ *

+ * Exercise these enum API methods on JSONObject and JSONArray + */ @Test public void enumAPI() { MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); MyEnumField myEnumField = MyEnumField.VAL2; - /** - * Exercise the proposed enum API methods on JSONObject - */ JSONObject jsonObject = new JSONObject(); jsonObject.put("strKey", "value"); jsonObject.put("enumKey", myEnumField); From 6f5bcb32e58064a8ef6fc81c15eb346c337024b9 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 8 Aug 2015 12:10:18 -0500 Subject: [PATCH 156/451] Unit tests for JSON-Java HTTP.java. See RFC7230 --- HTTPTest.java | 71 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 61 insertions(+), 10 deletions(-) diff --git a/HTTPTest.java b/HTTPTest.java index 52e166b..1bc0463 100644 --- a/HTTPTest.java +++ b/HTTPTest.java @@ -1,30 +1,50 @@ package org.json.junit; +import static org.junit.Assert.*; + import org.json.*; import org.junit.Test; /** - * Tests for JSON-Java HTTP.java - * See RFC7230 + * Unit tests for JSON-Java HTTP.java. See RFC7230 */ public class HTTPTest { + /** + * Attempt to call HTTP.toJSONObject() with a null string + * Expects a NUllPointerException. + */ @Test(expected=NullPointerException.class) public void nullHTTPException() { String httpStr = null; HTTP.toJSONObject(httpStr); } - @Test(expected=JSONException.class) + /** + * Attempt to call HTTP.toJSONObject() with a string containing + * an empty object. Expects a JSONException. + */ + @Test public void notEnoughHTTPException() { String httpStr = "{}"; JSONObject jsonObject = new JSONObject(httpStr); - HTTP.toString(jsonObject); + try { + HTTP.toString(jsonObject); + assertTrue("Expected to throw exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Not enough material for an HTTP header.".equals(e.getMessage())); + } } + /** + * Calling HTTP.toJSONObject() with an empty string will result in a + * populated JSONObject with keys but no values for Request-URI, Method, + * and HTTP-Version. + */ @Test - public void emptyStringHTTPException() { + public void emptyStringHTTPRequest() { String httpStr = ""; String expectedHTTPStr = "{\"Request-URI\":\"\",\"Method\":\"\",\"HTTP-Version\":\"\"}"; JSONObject jsonObject = HTTP.toJSONObject(httpStr); @@ -32,6 +52,10 @@ public class HTTPTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * Call HTTP.toJSONObject() with a Request-URI, Method, + * and HTTP-Version. + */ @Test public void simpleHTTPRequest() { String httpStr = "GET /hello.txt HTTP/1.1"; @@ -42,6 +66,10 @@ public class HTTPTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * Call HTTP.toJSONObject() with a response string containing a + * HTTP-Version, Status-Code, and Reason. + */ @Test public void simpleHTTPResponse() { String httpStr = "HTTP/1.1 200 OK"; @@ -52,6 +80,10 @@ public class HTTPTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * Call HTTP.toJSONObject() with a full request string including + * request headers. + */ @Test public void extendedHTTPRequest() { String httpStr = @@ -70,11 +102,18 @@ public class HTTPTest { "\"Content-Type\":\"text/xml; charset=utf-8\"}"; JSONObject jsonObject = HTTP.toJSONObject(httpStr); JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); - // not too easy for JSONObject to parse a string with embedded quotes + /** + * Not too easy for JSONObject to parse a string with embedded quotes. + * For the sake of the test, add it here. + */ expectedJsonObject.put("SOAPAction","\"http://clearforest.com/Enlighten\""); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * Call HTTP.toJSONObject() with a full response string including + * response headers. + */ @Test public void extendedHTTPResponse() { String httpStr = @@ -92,6 +131,10 @@ public class HTTPTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * Call HTTP.toJSONObject() with a full POST request string including + * response headers, then convert it back into an HTTP string. + */ @Test public void convertHTTPRequestToString() { String httpStr = @@ -110,8 +153,10 @@ public class HTTPTest { JSONObject jsonObject = HTTP.toJSONObject(httpStr); JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); String httpToStr = HTTP.toString(jsonObject); - // JSONObject objects to crlfs and any trailing chars - // httpToStr = httpToStr.replaceAll("(\r\n\r\n)", ""); + /** + * JSONObject objects to crlfs and any trailing chars. + * For the sake of the test, simplify the resulting string + */ httpToStr = httpToStr.replaceAll("("+HTTP.CRLF+HTTP.CRLF+")", ""); httpToStr = httpToStr.replaceAll(HTTP.CRLF, "\n"); JSONObject finalJsonObject = HTTP.toJSONObject(httpToStr); @@ -119,6 +164,10 @@ public class HTTPTest { Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } + /** + * Call HTTP.toJSONObject() with a full response string including + * response headers, then convert it back into an HTTP string. + */ @Test public void convertHTTPResponseToString() { String httpStr = @@ -134,8 +183,10 @@ public class HTTPTest { JSONObject jsonObject = HTTP.toJSONObject(httpStr); JSONObject expectedJsonObject = new JSONObject(expectedHTTPStr); String httpToStr = HTTP.toString(jsonObject); - // JSONObject objects to crlfs and any trailing chars - // httpToStr = httpToStr.replaceAll("(\r\n\r\n)", ""); + /** + * JSONObject objects to crlfs and any trailing chars. + * For the sake of the test, simplify the resulting string + */ httpToStr = httpToStr.replaceAll("("+HTTP.CRLF+HTTP.CRLF+")", ""); httpToStr = httpToStr.replaceAll(HTTP.CRLF, "\n"); JSONObject finalJsonObject = HTTP.toJSONObject(httpToStr); From 41bfdad91fe4136f54080716b408493daf1262b0 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 8 Aug 2015 12:10:52 -0500 Subject: [PATCH 157/451] Move method comments so JavaDoc will pick them up. --- HTTPTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HTTPTest.java b/HTTPTest.java index 1bc0463..2716c3c 100644 --- a/HTTPTest.java +++ b/HTTPTest.java @@ -7,7 +7,7 @@ import org.junit.Test; /** - * Unit tests for JSON-Java HTTP.java. See RFC7230 + * Unit tests for JSON-Java HTTP.java. See RFC7230. */ public class HTTPTest { From 4a3bbedc3237c98beda74f33fd66c4a3797ad5f4 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 8 Aug 2015 14:09:52 -0500 Subject: [PATCH 158/451] Verify exception messages. Move method comments so JavaDoc will pick them up. --- JSONArrayTest.java | 151 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 119 insertions(+), 32 deletions(-) diff --git a/JSONArrayTest.java b/JSONArrayTest.java index b033a60..4c21456 100644 --- a/JSONArrayTest.java +++ b/JSONArrayTest.java @@ -36,27 +36,59 @@ public class JSONArrayTest { "\"-1\""+ "]"; + /** + * Attempt to create a JSONArray with a null string. + * Expects a NullPointerException. + */ @Test(expected=NullPointerException.class) public void nullException() { String str = null; new JSONArray(str); } - @Test(expected=JSONException.class) + /** + * Attempt to create a JSONArray with an empty string. + * Expects a JSONException. + */ + @Test public void emptStr() { String str = ""; - new JSONArray(str); + try { + new JSONArray(str); + assertTrue("Should throw an exception", false); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "A JSONArray text must start with '[' at 1 [character 2 line 1]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Attempt to create a JSONArray with a string as object that is + * not a JSON array doc. + * Expects a JSONException. + */ + @Test public void badObject() { String str = "abc"; - new JSONArray((Object)str); + try { + new JSONArray((Object)str); + assertTrue("Should throw an exception", false); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "JSONArray initial value should be a string or collection or array.". + equals(e.getMessage())); + } } + /** + * Create a JSONArray doc with a variety of different elements. + * Confirm that the values can be accessed via the get[type]() API methods + */ @Test public void getArrayValues() { JSONArray jsonArray = new JSONArray(arrayStr); + // booleans assertTrue("Array true", true == jsonArray.getBoolean(0)); assertTrue("Array false", @@ -65,83 +97,105 @@ public class JSONArrayTest { true == jsonArray.getBoolean(2)); assertTrue("Array string false", false == jsonArray.getBoolean(3)); - + // strings + assertTrue("Array value string", + "hello".equals(jsonArray.getString(4))); + // doubles assertTrue("Array double", new Double(23.45e-4).equals(jsonArray.getDouble(5))); assertTrue("Array string double", new Double(23.45).equals(jsonArray.getDouble(6))); - + // ints assertTrue("Array value int", new Integer(42).equals(jsonArray.getInt(7))); assertTrue("Array value string int", new Integer(43).equals(jsonArray.getInt(8))); - + // nested objects JSONArray nestedJsonArray = jsonArray.getJSONArray(9); assertTrue("Array value JSONArray", nestedJsonArray != null); - JSONObject nestedJsonObject = jsonArray.getJSONObject(10); assertTrue("Array value JSONObject", nestedJsonObject != null); - + // longs assertTrue("Array value long", new Long(0).equals(jsonArray.getLong(11))); assertTrue("Array value string long", new Long(-1).equals(jsonArray.getLong(12))); - assertTrue("Array value string", - "hello".equals(jsonArray.getString(4))); - assertTrue("Array value null", jsonArray.isNull(-1)); } + /** + * Create a JSONArray doc with a variety of different elements. + * Confirm that attempting to get the wrong types via the get[type]() + * API methods result in JSONExceptions + */ @Test public void failedGetArrayValues() { - int tryCount = 0; - int exceptionCount = 0; JSONArray jsonArray = new JSONArray(arrayStr); try { - tryCount++; jsonArray.getBoolean(4); assertTrue("expected getBoolean to fail", false); - } catch (JSONException ignored) { exceptionCount++; } + } catch (JSONException e) { + assertTrue("Expected an exception message", + "JSONArray[4] is not a boolean.".equals(e.getMessage())); + } try { - tryCount++; jsonArray.get(-1); assertTrue("expected get to fail", false); - } catch (JSONException ignored) { exceptionCount++; } + } catch (JSONException e) { + assertTrue("Expected an exception message", + "JSONArray[-1] not found.".equals(e.getMessage())); + } try { - tryCount++; jsonArray.getDouble(4); assertTrue("expected getDouble to fail", false); - } catch (JSONException ignored) { exceptionCount++; } + } catch (JSONException e) { + assertTrue("Expected an exception message", + "JSONArray[4] is not a number.".equals(e.getMessage())); + } try { - tryCount++; jsonArray.getInt(4); assertTrue("expected getInt to fail", false); - } catch (JSONException ignored) { exceptionCount++; } + } catch (JSONException e) { + assertTrue("Expected an exception message", + "JSONArray[4] is not a number.".equals(e.getMessage())); + } try { - tryCount++; jsonArray.getJSONArray(4); assertTrue("expected getJSONArray to fail", false); - } catch (JSONException ignored) { exceptionCount++; } + } catch (JSONException e) { + assertTrue("Expected an exception message", + "JSONArray[4] is not a JSONArray.".equals(e.getMessage())); + } try { - tryCount++; jsonArray.getJSONObject(4); assertTrue("expected getJSONObject to fail", false); - } catch (JSONException ignored) { exceptionCount++; } + } catch (JSONException e) { + assertTrue("Expected an exception message", + "JSONArray[4] is not a JSONObject.".equals(e.getMessage())); + } try { - tryCount++; jsonArray.getLong(4); assertTrue("expected getLong to fail", false); - } catch (JSONException ignored) { exceptionCount++; } + } catch (JSONException e) { + assertTrue("Expected an exception message", + "JSONArray[4] is not a number.".equals(e.getMessage())); + } try { - tryCount++; jsonArray.getString(5); assertTrue("expected getString to fail", false); - } catch (JSONException ignored) { exceptionCount++; } - assertTrue("tryCount should match exceptionCount", - tryCount == exceptionCount); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "JSONArray[5] not a string.".equals(e.getMessage())); + } } + /** + * Exercise JSONArray.join() by converting a JSONArray into a + * comma-separated string. Since this is very nearly a JSON document, + * array braces are added to the beginning and end, and it is reconverted + * back to a JSONArray for comparison. + */ @Test public void join() { String expectedStr = @@ -176,6 +230,9 @@ public class JSONArrayTest { Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } + /** + * Confirm the JSONArray.length() method + */ @Test public void length() { assertTrue("expected empty JSONArray length 0", @@ -186,6 +243,11 @@ public class JSONArrayTest { assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1); } + /** + * Create a JSONArray doc with a variety of different elements. + * Confirm that the values can be accessed via the opt[type](index) + * and opt[type](index, default) API methods. + */ @Test public void opt() { JSONArray jsonArray = new JSONArray(arrayStr); @@ -238,6 +300,10 @@ public class JSONArrayTest { "".equals(jsonArray.optString(-1))); } + /** + * Exercise the JSONArray.put(value) method with various parameters + * and confirm the resulting JSONArray. + */ @Test public void put() { String expectedStr = @@ -314,6 +380,10 @@ public class JSONArrayTest { Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } + /** + * Exercise the JSONArray.put(index, value) method with various parameters + * and confirm the resulting JSONArray. + */ @Test public void putIndex() { String expectedStr = @@ -393,6 +463,10 @@ public class JSONArrayTest { Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } + /** + * Exercise the JSONArray.remove(index) method + * and confirm the resulting JSONArray. + */ @Test public void remove() { String arrayStr = @@ -406,6 +480,10 @@ public class JSONArrayTest { Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } + /** + * Exercise the JSONArray.similar() method with various parameters + * and confirm the results when not similar. + */ @Test public void notSimilar() { String arrayStr = @@ -441,6 +519,9 @@ public class JSONArrayTest { !jsonArray.similar(otherJsonArray)); } + /** + * Convert an empty JSONArray to JSONObject + */ @Test public void toJSONObject() { JSONArray names = new JSONArray(); @@ -449,6 +530,9 @@ public class JSONArrayTest { null == jsonArray.toJSONObject(names)); } + /** + * Confirm the creation of a JSONArray from an array of ints + */ @Test public void objectArrayVsIsArray() { String expectedStr = @@ -462,6 +546,9 @@ public class JSONArrayTest { Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } + /** + * Exercise the JSONArray iterator. + */ @Test public void iterator() { JSONArray jsonArray = new JSONArray(arrayStr); From 8e48caeb3d056749f373aa2cfd6aaf3bea70691c Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 8 Aug 2015 15:12:20 -0500 Subject: [PATCH 159/451] Verify exception messages. Move method comments so JavaDoc will pick them up. --- JSONMLTest.java | 264 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 212 insertions(+), 52 deletions(-) diff --git a/JSONMLTest.java b/JSONMLTest.java index fa982e1..a16f0ea 100644 --- a/JSONMLTest.java +++ b/JSONMLTest.java @@ -23,34 +23,93 @@ import org.junit.Test; */ public class JSONMLTest { + /** + * Attempts to transform a null XML string to JSON. + * Expects a NullPointerException + */ @Test(expected=NullPointerException.class) public void nullXMLException() { - /** - * Attempts to transform a null XML string to JSON - */ String xmlStr = null; JSONML.toJSONArray(xmlStr); } - @Test(expected=JSONException.class) + /** + * Attempts to transform an empty string to JSON. + * Expects a JSONException + */ + @Test public void emptyXMLException() { - /** - * Attempts to transform an empty XML string to JSON - */ String xmlStr = ""; - JSONML.toJSONArray(xmlStr); + try { + JSONML.toJSONArray(xmlStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Bad XML at 1 [character 2 line 1]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Attempts to call JSONML.toString() with a null JSONArray. + * Expects a NullPointerException. + */ + @Test(expected=NullPointerException.class) + public void nullJSONXMLException() { + /** + * Tries to convert a null JSONArray to XML. + */ + JSONArray jsonArray= null; + JSONML.toString(jsonArray); + } + + /** + * Attempts to call JSONML.toString() with a null JSONArray. + * Expects a JSONException. + */ + @Test + public void emptyJSONXMLException() { + /** + * Tries to convert an empty JSONArray to XML. + */ + JSONArray jsonArray = new JSONArray(); + try { + JSONML.toString(jsonArray); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONArray[0] not found.". + equals(e.getMessage())); + } + } + + /** + * Attempts to transform an non-XML string to JSON. + * Expects a JSONException + */ + @Test public void nonXMLException() { /** * Attempts to transform a nonXML string to JSON */ String xmlStr = "{ \"this is\": \"not xml\"}"; - JSONML.toJSONArray(xmlStr); + try { + JSONML.toJSONArray(xmlStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Bad XML at 25 [character 26 line 1]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Attempts to transform a JSON document with XML content that + * does not follow JSONML conventions (element name is not first value + * in a nested JSONArray) to a JSONArray then back to string. + * Expects a JSONException + */ + @Test public void emptyTagException() { /** * jsonArrayStr is used to build a JSONArray which is then @@ -70,10 +129,22 @@ public class JSONMLTest { "]"+ "]"; JSONArray jsonArray = new JSONArray(jsonArrayStr); - JSONML.toString(jsonArray); + try { + JSONML.toString(jsonArray); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONArray[0] not a string.". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Attempts to transform a JSON document with XML content that + * does not follow JSONML conventions (element tag has an embedded space) + * to a JSONArray then back to string. Expects a JSONException + */ + @Test public void spaceInTagException() { /** * jsonArrayStr is used to build a JSONArray which is then @@ -94,10 +165,22 @@ public class JSONMLTest { "]"+ "]"; JSONArray jsonArray = new JSONArray(jsonArrayStr); - JSONML.toString(jsonArray); + try { + JSONML.toString(jsonArray); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "'addr esses' contains a space character.". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Attempts to transform a malformed XML document + * (element tag has a frontslash) to a JSONArray.\ + * Expects a JSONException + */ + @Test public void invalidSlashInTagException() { /** * xmlStr contains XML text which is transformed into a JSONArray. @@ -113,16 +196,22 @@ public class JSONMLTest { " abc street\n"+ " \n"+ ""; - JSONML.toJSONArray(xmlStr); + try { + JSONML.toJSONArray(xmlStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Misshaped tag at 176 [character 14 line 7]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Malformed XML text (invalid tagname) is transformed into a JSONArray. + * Expects a JSONException. + */ + @Test public void invalidBangInTagException() { - /** - * xmlStr contains XML text which is transformed into a JSONArray. - * In this case, the XML is invalid because an element - * has the invalid name '!'. - */ String xmlStr = "\n"+ "\n"+ " \n"+ ""; - JSONML.toJSONArray(xmlStr); + try { + JSONML.toJSONArray(xmlStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Misshaped meta tag at 216 [character 13 line 11]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Malformed XML text (invalid tagname, no close bracket) is transformed\ + * into a JSONArray. Expects a JSONException. + */ + @Test public void invalidBangNoCloseInTagException() { /** * xmlStr contains XML text which is transformed into a JSONArray. @@ -151,10 +251,21 @@ public class JSONMLTest { " \n"+ ""; - JSONML.toJSONArray(xmlStr); + try { + JSONML.toJSONArray(xmlStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Misshaped meta tag at 215 [character 13 line 11]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Malformed XML text (tagname with no close bracket) is transformed\ + * into a JSONArray. Expects a JSONException. + */ + @Test public void noCloseStartTagException() { /** * xmlStr contains XML text which is transformed into a JSONArray. @@ -170,10 +281,21 @@ public class JSONMLTest { " \n"+ ""; - JSONML.toJSONArray(xmlStr); + try { + JSONML.toJSONArray(xmlStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Misplaced '<' at 194 [character 5 line 10]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Malformed XML text (endtag with no name) is transformed\ + * into a JSONArray. Expects a JSONException. + */ + @Test public void noCloseEndTagException() { /** * xmlStr contains XML text which is transformed into a JSONArray. @@ -189,10 +311,21 @@ public class JSONMLTest { " \n"+ " \n"+ ""; - JSONML.toJSONArray(xmlStr); + try { + JSONML.toJSONArray(xmlStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Expected a closing name instead of '>'.". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Malformed XML text (endtag with no close bracket) is transformed\ + * into a JSONArray. Expects a JSONException. + */ + @Test public void noCloseEndBraceException() { /** * xmlStr contains XML text which is transformed into a JSONArray. @@ -208,10 +341,21 @@ public class JSONMLTest { " \n"+ " "; - JSONML.toJSONArray(xmlStr); + try { + JSONML.toJSONArray(xmlStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Misplaced '<' at 206 [character 1 line 12]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Malformed XML text (incomplete CDATA string) is transformed\ + * into a JSONArray. Expects a JSONException. + */ + @Test public void invalidCDATABangInTagException() { /** * xmlStr contains XML text which is transformed into a JSONArray. @@ -227,27 +371,22 @@ public class JSONMLTest { " \n"+ " \n"+ ""; - JSONML.toJSONArray(xmlStr); - } - - @Test(expected=NullPointerException.class) - public void nullJSONXMLException() { - /** - * Tries to convert a null JSONArray to XML. - */ - JSONArray jsonArray= null; - JSONML.toString(jsonArray); - } - - @Test(expected=JSONException.class) - public void emptyJSONXMLException() { - /** - * Tries to convert an empty JSONArray to XML. - */ - JSONArray jsonArray = new JSONArray(); - JSONML.toString(jsonArray); + try { + JSONML.toJSONArray(xmlStr); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Expected 'CDATA[' at 204 [character 11 line 9]". + equals(e.getMessage())); + } } + /** + * Convert an XML document into a JSONArray, then use JSONML.toString() + * to convert it into a string. This string is then converted back into + * a JSONArray. Both JSONArrays are compared against a control to + * confirm the contents. + */ @Test public void toJSONArray() { /** @@ -290,6 +429,20 @@ public class JSONMLTest { Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } + /** + * Convert an XML document into a JSONObject. Use JSONML.toString() to + * convert it back into a string, and then re-convert it into a JSONObject. + * Both JSONObjects are compared against a control JSONObject to confirm + * the contents. + *

+ * Next convert the XML document into a JSONArray. Use JSONML.toString() to + * convert it back into a string, and then re-convert it into a JSONArray. + * Both JSONArrays are compared against a control JSONArray to confirm + * the contents. + *

+ * This test gives a comprehensive example of how the JSONML + * transformations work. + */ @Test public void toJSONObjectToJSONArray() { /** @@ -505,7 +658,14 @@ public class JSONMLTest { Util.compareXML(jsonObjectXmlToStr, jsonArrayXmlToStr); } - + /** + * Convert an XML document which contains embedded comments into + * a JSONArray. Use JSONML.toString() to turn it into a string, then + * reconvert it into a JSONArray. Compare both JSONArrays to a control + * JSONArray to confirm the contents. + *

+ * This test shows how XML comments are handled. + */ @Test public void commentsInXML() { From 58d72fe20f2759679f931c2ae03340a15d171606 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 9 Aug 2015 18:19:32 -0500 Subject: [PATCH 160/451] Verify exception messages. Move method comments so JavaDoc will pick them up. --- JSONObjectTest.java | 510 +++++++++++++++++++++++++++++------------- JSONStringerTest.java | 196 +++++++++++----- 2 files changed, 498 insertions(+), 208 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index b818a9e..240bbeb 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -12,7 +12,7 @@ import org.json.*; import org.junit.*; /** - * These classes will be used for testing + * Used in testing when a JSONString is needed */ class MyJsonString implements JSONString { @@ -22,6 +22,9 @@ class MyJsonString implements JSONString { } } +/** + * Used in testing when Bean behavior is needed + */ interface MyBean { public Integer getIntKey(); public Double getDoubleKey(); @@ -32,6 +35,9 @@ interface MyBean { public StringReader getStringReaderKey(); }; +/** + * Used in testing when a Bean containing big numbers is needed + */ interface MyBigNumberBean { public BigInteger getBigInteger(); public BigDecimal getBigDecimal(); @@ -39,34 +45,45 @@ interface MyBigNumberBean { /** * JSONObject, along with JSONArray, are the central classes of the reference app. - * All of the other classes interact with it and JSON functionality would be - * impossible without it. + * All of the other classes interact with them, and JSON functionality would + * otherwise be impossible. */ public class JSONObjectTest { /** * Need a class with some public data members for testing, so - * JSONObjectTest is chosen. + * JSONObjectTest itself will be used for this purpose. + * TODO: Why not use MyBigNumberBean or MyBean? */ public Integer publicInt = 42; public String publicString = "abc"; + /** + * JSONObject built from a bean, but only using a null value. + * Nothing good is expected to happen. + * Expects NullPointerException + */ + @Test(expected=NullPointerException.class) + public void jsonObjectByNullBean() { + MyBean myBean = null; + new JSONObject(myBean); + } + /** + * A JSONObject can be created with no content + */ @Test public void emptyJsonObject() { - /** - * A JSONObject can be created with no content - */ JSONObject jsonObject = new JSONObject(); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } + /** + * A JSONObject can be created from another JSONObject plus a list of names. + * In this test, some of the starting JSONObject keys are not in the + * names list. + */ @Test public void jsonObjectByNames() { - /** - * A JSONObject can be created from another JSONObject plus a list of names. - * In this test, some of the starting JSONObject keys are not in the - * names list. - */ String str = "{"+ "\"trueKey\":true,"+ @@ -92,28 +109,25 @@ public class JSONObjectTest { } /** + * JSONObjects can be built from a Map. + * In this test the map is null. * the JSONObject(JsonTokener) ctor is not tested directly since it already * has full coverage from other tests. */ - @Test public void jsonObjectByNullMap() { - /** - * JSONObjects can be built from a Map. - * In this test the map is null. - */ Map map = null; JSONObject jsonObject = new JSONObject(map); JSONObject expectedJsonObject = new JSONObject(); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * JSONObjects can be built from a Map. + * In this test all of the map entries are valid JSON types. + */ @Test public void jsonObjectByMap() { - /** - * JSONObjects can be built from a Map. - * In this test all of the map entries are valid JSON types. - */ String expectedStr = "{"+ "\"trueKey\":true,"+ @@ -136,13 +150,13 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * JSONObjects can be built from a Map. + * In this test the map entries are not valid JSON types. + * The actual conversion is kind of interesting. + */ @Test public void jsonObjectByMapWithUnsupportedValues() { - /** - * JSONObjects can be built from a Map. - * In this test the map entries are not valid JSON types. - * The actual conversion is kind of interesting. - */ String expectedStr = "{"+ "\"key1\":{},"+ @@ -158,12 +172,12 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * JSONObjects can be built from a Map. + * In this test one of the map values is null + */ @Test public void jsonObjectByMapWithNullValue() { - /** - * JSONObjects can be built from a Map. - * In this test one of the map values is null - */ String expectedStr = "{"+ "\"trueKey\":true,"+ @@ -187,22 +201,12 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } - @Test(expected=NullPointerException.class) - public void jsonObjectByNullBean() { - /** - * JSONObject built from a bean, but only using a null value. - * Nothing good is expected to happen. - */ - MyBean myBean = null; - new JSONObject(myBean); - } - + /** + * JSONObject built from a bean. In this case all but one of the + * bean getters return valid JSON types + */ @Test public void jsonObjectByBean() { - /** - * JSONObject built from a bean. In this case all but one of the - * bean getters return valid JSON types - */ String expectedStr = "{"+ "\"trueKey\":true,"+ @@ -244,14 +248,14 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * A bean is also an object. But in order to test the JSONObject + * ctor that takes an object and a list of names, + * this particular bean needs some public + * data members, which have been added to the class. + */ @Test public void jsonObjectByObjectAndNames() { - /** - * A bean is also an object. But in order to test the JSONObject - * ctor that takes an object and a list of names, - * this particular bean needs some public - * data members, which have been added to the class. - */ String expectedStr = "{"+ "\"publicString\":\"abc\","+ @@ -265,6 +269,9 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * Exercise the JSONObject from resource bundle functionality + */ @Test public void jsonObjectByResourceBundle() { // TODO: how to improve resource bundle testing? @@ -286,6 +293,9 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * Exercise the JSONObject.accumulate() method + */ @Test public void jsonObjectAccumulate() { // TODO: should include an unsupported object @@ -311,6 +321,9 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * Exercise the JSONObject append() functionality + */ @Test public void jsonObjectAppend() { // TODO: should include an unsupported object @@ -336,6 +349,9 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * Exercise the JSONObject doubleToString() method + */ @Test public void jsonObjectDoubleToString() { String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; @@ -349,6 +365,9 @@ public class JSONObjectTest { } } + /** + * Exercise some JSONObject get[type] and opt[type] methods + */ @Test public void jsonObjectValues() { String str = @@ -423,9 +442,12 @@ public class JSONObjectTest { jsonObjectInner.get("myKey").equals("myVal")); } + /** + * Check whether JSONObject handles large or high precision numbers correctly + */ @Test public void stringToValueNumbersTest() { - // Check if library handles large or high precision numbers correctly + assertTrue( "0.2 should be a Double!", JSONObject.stringToValue( "0.2" ) instanceof Double ); assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", @@ -528,6 +550,9 @@ public class JSONObjectTest { jsonObject.get("doubleIdentifier").equals(new Double(0.1))); } + /** + * Tests how JSONObject get[type] handles incorrect types + */ @Test public void jsonObjectNonAndWrongValues() { String str = @@ -547,75 +572,126 @@ public class JSONObjectTest { "\"objectKey\":{\"myKey\":\"myVal\"}"+ "}"; JSONObject jsonObject = new JSONObject(str); - int tryCount = 0; - int exceptionCount = 0; try { - ++tryCount; jsonObject.getBoolean("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getBoolean("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a Boolean.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getString("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getString("trueKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"trueKey\"] not a string.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getDouble("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getDouble("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a number.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getInt("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getInt("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not an int.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getLong("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getLong("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a long.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getJSONArray("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getJSONArray("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a JSONArray.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getJSONObject("nonKey"); - } catch (JSONException ignore) { ++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } try { - ++tryCount; jsonObject.getJSONObject("stringKey"); - } catch (JSONException ignore) { ++exceptionCount; } - assertTrue("all get calls should have failed", - exceptionCount == tryCount); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a JSONObject.". + equals(e.getMessage())); + } } + /** + * This test documents an unexpected numeric behavior. + * A double that ends with .0 is parsed, serialized, then + * parsed again. On the second parse, it has become an int. + */ @Test public void unexpectedDoubleToIntConversion() { - /** - * This test documents an unexpected numeric behavior. - * A double that ends with .0 is parsed, serialized, then - * parsed again. On the second parse, it has become an int. - */ String key30 = "key30"; String key31 = "key31"; JSONObject jsonObject = new JSONObject(); @@ -636,11 +712,11 @@ public class JSONObjectTest { assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); } - @Test /** - * Important behaviors of big numbers. Includes both JSONObject + * Document behaviors of big numbers. Includes both JSONObject * and JSONArray tests */ + @Test public void bigNumberOperations() { /** * JSONObject tries to parse BigInteger as a bean, but it only has @@ -874,6 +950,10 @@ public class JSONObjectTest { Util.compareActualVsExpectedStringArrays(names, jsonObjectTestExpectedNames); } + /** + * Populate a JSONArray from an empty JSONObject names() method. + * It should be empty. + */ @Test public void emptyJsonObjectNamesToJsonAray() { JSONObject jsonObject = new JSONObject(); @@ -881,6 +961,10 @@ public class JSONObjectTest { assertTrue("jsonArray should be null", jsonArray == null); } + /** + * Populate a JSONArray from a JSONObject names() method. + * Confirm that it contains the expected names. + */ @Test public void jsonObjectNamesToJsonAray() { String str = @@ -907,6 +991,9 @@ public class JSONObjectTest { Util.compareActualVsExpectedStringArrays(names, expectedNames); } + /** + * Exercise the JSONObject increment() method. + */ @Test public void jsonObjectIncrement() { String str = @@ -919,19 +1006,31 @@ public class JSONObjectTest { "\"keyInt\":3,"+ "\"keyLong\":9999999993,"+ "\"keyDouble\":3.1,"+ - // Should work the same way on any platform! @see https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 - // This is the effect of a float to double conversion and is inherent to the shortcomings of the IEEE 754 format, when - // converting 32-bit into double-precision 64-bit. - // Java type-casts float to double. A 32 bit float is type-casted to 64 bit double by simply appending zero-bits to the - // mantissa (and extended the signed exponent by 3 bits.) and there is no way to obtain more information than it is - // stored in the 32-bits float. - - // Like 1/3 cannot be represented as base10 number because it is periodically, 1/5 (for example) cannot be represented - // as base2 number since it is periodically in base2 (take a look at http://www.h-schmidt.net/FloatConverter/) - // The same happens to 3.1, that decimal number (base10 representation) is periodic in base2 representation, therefore - // appending zero-bits is inaccurate. Only repeating the periodically occuring bits (0110) would be a proper conversion. - // However one cannot detect from a 32 bit IEE754 representation which bits would "repeat infinitely", since the missing - // bits would not fit into the 32 bit float, i.e. the information needed simply is not there! + /** + * Should work the same way on any platform! @see + * https://docs.oracle + * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is + * the effect of a float to double conversion and is inherent to + * the shortcomings of the IEEE 754 format, when converting + * 32-bit into double-precision 64-bit. Java type-casts float to + * double. A 32 bit float is type-casted to 64 bit double by + * simply appending zero-bits to the mantissa (and extended the + * signed exponent by 3 bits.) and there is no way to obtain + * more information than it is stored in the 32-bits float. + * + * Like 1/3 cannot be represented as base10 number because it is + * periodically, 1/5 (for example) cannot be represented as + * base2 number since it is periodically in base2 (take a look + * at http://www.h-schmidt.net/FloatConverter/) The same happens + * to 3.1, that decimal number (base10 representation) is + * periodic in base2 representation, therefore appending + * zero-bits is inaccurate. Only repeating the periodically + * occuring bits (0110) would be a proper conversion. However + * one cannot detect from a 32 bit IEE754 representation which + * bits would "repeat infinitely", since the missing bits would + * not fit into the 32 bit float, i.e. the information needed + * simply is not there! + */ "\"keyFloat\":3.0999999046325684,"+ "}"; JSONObject jsonObject = new JSONObject(str); @@ -948,24 +1047,28 @@ public class JSONObjectTest { JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - /* - float f = 3.1f; - double df = (double) f; - double d = 3.1d; - System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f))); - System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(df))); - System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d))); + /** + * float f = 3.1f; + * double df = (double) f; + * double d = 3.1d; + * System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f))); + * System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(df))); + * System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d))); + * + * - Float: + * seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm + * 1000000010001100110011001100110 + * - Double + * seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + * 10000000 10001100110011001100110 + * 100000000001000110011001100110011000000000000000000000000000000 + * 100000000001000110011001100110011001100110011001100110011001101 + */ - - Float: - seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm - 1000000010001100110011001100110 - - Double - seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - 10000000 10001100110011001100110 - 100000000001000110011001100110011000000000000000000000000000000 - 100000000001000110011001100110011001100110011001100110011001101 - */ - // Examples of well documented but probably unexpected behavior in java / with 32-bit float to 64-bit float conversion. + /** + * Examples of well documented but probably unexpected behavior in + * java / with 32-bit float to 64-bit float conversion. + */ assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d ); assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d ); Double d1 = new Double( 1.1f ); @@ -997,7 +1100,9 @@ public class JSONObjectTest { } - + /** + * Exercise JSONObject numberToString() method + */ @Test public void jsonObjectNumberToString() { String str; @@ -1017,6 +1122,9 @@ public class JSONObjectTest { assertTrue("expected 5000000 actual "+str, str.equals("5000000")); } + /** + * Exercise JSONObject put() and similar() methods + */ @Test public void jsonObjectPut() { String expectedStr = @@ -1090,6 +1198,9 @@ public class JSONObjectTest { !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); } + /** + * Exercise JSONObject toString() method + */ @Test public void jsonObjectToString() { String str = @@ -1110,6 +1221,13 @@ public class JSONObjectTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * Explores how JSONObject handles maps. Insert a string/string map + * as a value in a JSONObject. It will remain a map. Convert the + * JSONObject to string, then create a new JSONObject from the string. + * In the new JSONObject, the value will be stored as a nested JSONObject. + * Confirm that map and nested JSONObject have the same contents. + */ @Test @SuppressWarnings("unchecked") public void jsonObjectToStringSuppressWarningOnCastToMap() { @@ -1124,7 +1242,8 @@ public class JSONObjectTest { expectedJsonObject.keySet().iterator().next())); /** * Can't do a Util compare because although they look the same - * in the debugger, one is a map and the other is a JSONObject. + * in the debugger, one is a map and the other is a JSONObject. + * TODO: write a util method for such comparisons */ map = (Map)jsonObject.get("key"); JSONObject mapJsonObject = expectedJsonObject.getJSONObject("key"); @@ -1137,6 +1256,13 @@ public class JSONObjectTest { map.get(map.keySet().iterator().next()))); } + /** + * Explores how JSONObject handles collections. Insert a string collection + * as a value in a JSONObject. It will remain a collection. Convert the + * JSONObject to string, then create a new JSONObject from the string. + * In the new JSONObject, the value will be stored as a nested JSONArray. + * Confirm that collection and nested JSONArray have the same contents. + */ @Test @SuppressWarnings("unchecked") public void jsonObjectToStringSuppressWarningOnCastToCollection() { @@ -1166,6 +1292,9 @@ public class JSONObjectTest { } } + /** + * Exercises the JSONObject.valueToString() method for various types + */ @Test public void valueToString() { @@ -1211,6 +1340,12 @@ public class JSONObjectTest { jsonArray.toString().equals(JSONObject.valueToString(array))); } + /** + * Exercise the JSONObject wrap() method. Sometimes wrap() will change + * the object being wrapped, other times not. The purpose of wrap() is + * to ensure the value is packaged in a way that is compatible with how + * a JSONObject value or JSONArray value is supposed to be stored. + */ @Test public void wrapObject() { // wrap(null) returns NULL @@ -1224,8 +1359,9 @@ public class JSONObjectTest { /** * This test is to document the preferred behavior if BigDecimal is - * supported. At the present time, bd returns as a string, since it - * is recognized as being a Java package class. + * supported. Previously bd returned as a string, since it + * is recognized as being a Java package class. Now with explicit + * support for big numbers, it remains a BigDecimal */ Object bdWrap = JSONObject.wrap(BigDecimal.ONE); assertTrue("BigDecimal.ONE evaluates to ONE", @@ -1273,88 +1409,128 @@ public class JSONObjectTest { // TODO test wrap(package) } + /** + * Explore how JSONObject handles parsing errors. + */ @Test public void jsonObjectParsingErrors() { - int tryCount = 0; - int exceptionCount = 0; try { // does not start with '{' - ++tryCount; String str = "abc"; new JSONObject(str); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "A JSONObject text must begin with '{' at 1 [character 2 line 1]". + equals(e.getMessage())); + } try { // does not end with '}' - ++tryCount; String str = "{"; new JSONObject(str); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "A JSONObject text must end with '}' at 2 [character 3 line 1]". + equals(e.getMessage())); + } try { // key with no ':' - ++tryCount; String str = "{\"myKey\" = true}"; new JSONObject(str); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Expected a ':' after a key at 10 [character 11 line 1]". + equals(e.getMessage())); + } try { // entries with no ',' separator - ++tryCount; String str = "{\"myKey\":true \"myOtherKey\":false}"; new JSONObject(str); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Expected a ',' or '}' at 15 [character 16 line 1]". + equals(e.getMessage())); + } try { // append to wrong key - ++tryCount; String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.append("myKey", "hello"); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[myKey] is not a JSONArray.". + equals(e.getMessage())); + } try { // increment wrong key - ++tryCount; String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("myKey"); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Unable to increment [\"myKey\"].". + equals(e.getMessage())); + } try { // invalid key - ++tryCount; String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.get(null); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Null key.". + equals(e.getMessage())); + } try { // invalid numberToString() - ++tryCount; JSONObject.numberToString((Number)null); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Null pointer". + equals(e.getMessage())); + } try { // null put key - ++tryCount; JSONObject jsonObject = new JSONObject("{}"); jsonObject.put(null, 0); - } catch (NullPointerException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (NullPointerException ignored) { + } try { // multiple putOnce key - ++tryCount; JSONObject jsonObject = new JSONObject("{}"); jsonObject.putOnce("hello", "world"); jsonObject.putOnce("hello", "world!"); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("", true); + } try { // test validity of invalid double - ++tryCount; JSONObject.testValidity(Double.NaN); - } catch (JSONException ignore) {++exceptionCount; } + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("", true); + } try { // test validity of invalid float - ++tryCount; JSONObject.testValidity(Float.NEGATIVE_INFINITY); - } catch (JSONException ignore) {++exceptionCount; } - - assertTrue("all tries should have failed", - exceptionCount == tryCount); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("", true); + } } + /** + * Confirm behavior when putOnce() is called with null parameters + */ @Test public void jsonObjectPutOnceNull() { JSONObject jsonObject = new JSONObject(); @@ -1362,6 +1538,9 @@ public class JSONObjectTest { assertTrue("jsonObject should be empty", jsonObject.length() == 0); } + /** + * Exercise JSONObject opt(key, default) method + */ @Test public void jsonObjectOptDefault() { @@ -1382,6 +1561,9 @@ public class JSONObjectTest { "hi".equals(jsonObject.optString("hiKey", "hi"))); } + /** + * Confirm behavior when JSONObject put(key, null object) is called + */ @Test public void jsonObjectputNull() { @@ -1397,6 +1579,11 @@ public class JSONObjectTest { jsonObjectPutNull.length() == 0); } + /** + * Exercise JSONObject quote() method + * This purpose of quote() is to ensure that for strings with embedded + * quotes, the quotes are properly escaped. + */ @Test public void jsonObjectQuote() { String str; @@ -1435,6 +1622,10 @@ public class JSONObjectTest { "\"\u1234\\u0088\"".equals(quotedStr)); } + /** + * Confirm behavior when JSONObject stringToValue() is called for an + * empty string + */ @Test public void stringToValue() { String str = ""; @@ -1443,12 +1634,18 @@ public class JSONObjectTest { "".equals(valueStr)); } + /** + * Confirm behavior when toJSONArray is called with a null value + */ @Test public void toJSONArray() { assertTrue("toJSONArray() with null names should be null", null == new JSONObject().toJSONArray(null)); } + /** + * Exercise the JSONObject write() method + */ @Test public void write() { String str = "{\"key\":\"value\"}"; @@ -1462,6 +1659,9 @@ public class JSONObjectTest { expectedStr.equals(actualStr)); } + /** + * Exercise the JSONObject equals() method + */ @Test public void equals() { String str = "{\"key\":\"value\"}"; @@ -1470,6 +1670,10 @@ public class JSONObjectTest { aJsonObject.equals(aJsonObject)); } + /** + * JSON null is not the same as Java null. This test examines the differences + * in how they are handled by JSON-java. + */ @Test public void jsonObjectNullOperations() { /** diff --git a/JSONStringerTest.java b/JSONStringerTest.java index d76bfb1..7a35064 100644 --- a/JSONStringerTest.java +++ b/JSONStringerTest.java @@ -1,100 +1,178 @@ package org.json.junit; +import static org.junit.Assert.*; + import org.json.*; import org.junit.Test; /** - * Tests for JSON-Java JSONStringer.java + * Tests for JSON-Java JSONStringer. + * TODO: Could use a lot more testing. For example, cascade-style productions. */ public class JSONStringerTest { - @Test(expected=JSONException.class) + /** + * Object with a null key. + * Expects a JSONException. + */ + @Test public void nullKeyException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object(); - jsonStringer.key(null); + try { + jsonStringer.key(null); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "Null key.". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Add a key with no object. + * Expects a JSONException. + */ + @Test public void outOfSequenceException() { JSONStringer jsonStringer = new JSONStringer(); - jsonStringer.key("hi"); + try { + jsonStringer.key("hi"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "Misplaced key.". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Missplace an array. + * Expects a JSONException + */ + @Test public void missplacedArrayException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object().endObject(); - jsonStringer.array(); + try { + jsonStringer.array(); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "Misplaced array.". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Missplace an endErray. + * Expects a JSONException + */ + @Test public void missplacedEndArrayException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object(); - jsonStringer.endArray(); + try { + jsonStringer.endArray(); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "Misplaced endArray.". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Missplace an endObject. + * Expects a JSONException + */ + @Test public void missplacedEndObjectException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.array(); - jsonStringer.endObject(); + try { + jsonStringer.endObject(); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "Misplaced endObject.". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Missplace an object. + * Expects a JSONException. + */ + @Test public void missplacedObjectException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object().endObject(); - jsonStringer.object(); + try { + jsonStringer.object(); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "Misplaced object.". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Exceeds implementation max nesting depth. + * Expects a JSONException + */ + @Test public void exceedNestDepthException() { - new JSONStringer().object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). - key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(); + try { + new JSONStringer().object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(); + } catch (JSONException e) { + assertTrue("Expected an exception message", + "". + equals(e.getMessage())); + } } + /** + * Build a JSON doc using JSONString API calls, + * then convert to JSONObject + */ @Test public void simpleObjectString() { String expectedStr = @@ -123,6 +201,10 @@ public class JSONStringerTest { Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + /** + * Build a JSON doc using JSONString API calls, + * then convert to JSONArray + */ @Test public void simpleArrayString() { String expectedStr = @@ -149,6 +231,10 @@ public class JSONStringerTest { Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } + /** + * Build a nested JSON doc using JSONString API calls, + * then convert to JSONObject + */ @Test public void complexObjectString() { String expectedStr = From 1081ae092bf5dc37d402c8f3c9e3a56cbb5d8fe2 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 9 Aug 2015 18:19:51 -0500 Subject: [PATCH 161/451] Move method comments so JavaDoc will pick them up. --- Util.java | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/Util.java b/Util.java index 635b7a6..eb33ab5 100644 --- a/Util.java +++ b/Util.java @@ -6,12 +6,16 @@ import java.util.*; import org.json.*; +/** + * These are helpful utility methods that perform basic comparisons + * between various objects. In most cases, the comparisons are not + * order-dependent, or else the order is known. + */ public class Util { - - /** - * Compares two json arrays for equality + * Compares two JSONArrays for equality. + * The arrays need not be in the same order. * @param jsonArray created by the code to be tested * @param expectedJsonArray created specifically for comparing */ @@ -27,7 +31,8 @@ public class Util { } /** - * Compares two json objects for equality + * Compares two JSONObjects for equality. The objects need not be + * in the same order * @param jsonObject created by the code to be tested * @param expectedJsonObject created specifically for comparing */ @@ -68,6 +73,8 @@ public class Util { * Certain helper classes (e.g. XML) may create Long instead of * Integer for small int values. As long as both are Numbers, * just compare the toString() values. + * TODO: this may not work in the case where the underlying types + * do not have the same precision. */ if (!(value instanceof Number && expectedValue instanceof Number)) { assertTrue("object types should be equal for actual: "+ @@ -78,12 +85,31 @@ public class Util { value.getClass().toString().equals( expectedValue.getClass().toString())); } + /** + * When in doubt, compare by string + * TODO: should not this be an else to the previous condition? + */ assertTrue("string values should be equal for actual: "+ value.toString()+" expected: "+expectedValue.toString(), value.toString().equals(expectedValue.toString())); } } + /** + * Sometimes test completion requires comparison of JSONArray objects that + * were produced from a JSONObject, and so unordered. This method is + * imperfect since it only compares the array elements and won't catch + * JSON syntax errors but at least it does not rely on ordering + *

+ * It is expected that the arrays to be compared come from JSONArray + * instances which have been rendered by toString(), and whose syntax + * chars have been removed. + *

+ * TODO: why are we not simply comparing the JSONArrays? + *

+ * @param names an array of strings for comparison + * @param expectedNames the other array of strings for comparison + */ public static void compareActualVsExpectedStringArrays(String[] names, String [] expectedNames) { assertTrue("Array lengths should be equal", @@ -97,6 +123,13 @@ public class Util { } } + /** + * This is stopgap test utility. It is meant to compare strings + * of XML, but it does not take ordering into account and should + * not be expected to work correctly with complex XML. + * @param aXmlStr an XML doc to be compared + * @param bXmlStr the other XML doc to be compared + */ public static void compareXML(String aXmlStr, String bXmlStr) { // TODO For simple tests this may be adequate, but it won't work for // elements with multiple attributes and possibly other cases as well. From ccbec8127c844a8aa41e74a04199ff20b402e6a8 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 9 Aug 2015 18:24:47 -0500 Subject: [PATCH 162/451] Added some class documentation --- MyEnum.java | 3 +++ MyEnumField.java | 3 +++ StringsResourceBundle.java | 3 +++ TestRunner.java | 4 ++++ 4 files changed, 13 insertions(+) diff --git a/MyEnum.java b/MyEnum.java index d2fe08d..0952bc2 100644 --- a/MyEnum.java +++ b/MyEnum.java @@ -1,5 +1,8 @@ package org.json.junit; +/** + * An enum with no methods or data + */ public enum MyEnum { VAL1, VAL2, diff --git a/MyEnumField.java b/MyEnumField.java index 7efec54..cff565a 100644 --- a/MyEnumField.java +++ b/MyEnumField.java @@ -1,5 +1,8 @@ package org.json.junit; +/** + * An enum that contains getters and some internal fields + */ public enum MyEnumField { VAL1(1, "val 1"), VAL2(2, "val 2"), diff --git a/StringsResourceBundle.java b/StringsResourceBundle.java index b1b9df4..83d9322 100644 --- a/StringsResourceBundle.java +++ b/StringsResourceBundle.java @@ -2,6 +2,9 @@ package org.json.junit; import java.util.*; +/** + * A resource bundle class + */ public class StringsResourceBundle extends ListResourceBundle { public Object[][] getContents() { return contents; diff --git a/TestRunner.java b/TestRunner.java index 8f9dd89..d13c63e 100644 --- a/TestRunner.java +++ b/TestRunner.java @@ -4,6 +4,10 @@ import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; +/** + * Invoke this class main method if you want to run unit tests from the + * command line. If successful, will print "true" to stdout. + */ public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(JunitTestSuite.class); From 8f71e01ae3cb64c8d9db11e45cc13dc101c861f0 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 9 Aug 2015 18:30:16 -0500 Subject: [PATCH 163/451] Add method comments so JavaDoc will pick them up. --- PropertyTest.java | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/PropertyTest.java b/PropertyTest.java index 4354488..60d3eb5 100644 --- a/PropertyTest.java +++ b/PropertyTest.java @@ -9,26 +9,35 @@ import org.junit.Test; /** - * Tests for JSON-Java Property.java + * Tests for JSON-Java Property */ public class PropertyTest { + /** + * JSONObject from null properties object should + * result in an empty JSONObject. + */ @Test public void shouldHandleNullProperties() { - Properties properties = null; JSONObject jsonObject = Property.toJSONObject(properties); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } + /** + * JSONObject from empty properties object should + * result in an empty JSONObject. + */ @Test public void shouldHandleEmptyProperties() { - Properties properties = new Properties(); JSONObject jsonObject = Property.toJSONObject(properties); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } + /** + * JSONObject from simple properties object. + */ @Test public void shouldHandleProperties() { Properties properties = new Properties(); @@ -54,6 +63,10 @@ public class PropertyTest { "Indianapolis".equals(jsonObject.get("Indiana"))); } + /** + * Null JSONObject toProperties() should result in an empty + * Properties object. + */ @Test public void shouldHandleNullJSONProperty() { JSONObject jsonObject= null; @@ -62,6 +75,10 @@ public class PropertyTest { properties.size() == 0); } + /** + * Properties should convert to JSONObject, and back to + * Properties without changing. + */ @Test public void shouldHandleJSONProperty() { Properties properties = new Properties(); From 1f6e07c91445f4abeae07fed982cfe727918b739 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 19 Aug 2015 19:16:22 -0500 Subject: [PATCH 164/451] sample tests for XML.toJSONObject(Reader) --- XMLTest.java | 200 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 179 insertions(+), 21 deletions(-) diff --git a/XMLTest.java b/XMLTest.java index 58ddee5..b7d7477 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -2,8 +2,11 @@ package org.json.junit; import static org.junit.Assert.*; +import java.io.*; + import org.json.*; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.*; /** @@ -11,15 +14,27 @@ import org.junit.Test; * Note: noSpace() will be tested by JSONMLTest */ public class XMLTest { + /** + * JUnit supports temporary files and folders that are cleaned up after the test. + * https://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/ + */ + @Rule + public TemporaryFolder testFolder = new TemporaryFolder(); + /** + * JSONObject from a null XML string. + * Expects a NullPointerException + */ @Test(expected=NullPointerException.class) public void shouldHandleNullXML() { - String xmlStr = null; JSONObject jsonObject = XML.toJSONObject(xmlStr); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } + /** + * Empty JSONObject from an empty XML string. + */ @Test public void shouldHandleEmptyXML() { @@ -28,6 +43,9 @@ public class XMLTest { assertTrue("jsonObject should be empty", jsonObject.length() == 0); } + /** + * Empty JSONObject from a non-XML string. + */ @Test public void shouldHandleNonXML() { String xmlStr = "{ \"this is\": \"not xml\"}"; @@ -35,7 +53,11 @@ public class XMLTest { assertTrue("xml string should be empty", jsonObject.length() == 0); } - @Test(expected=JSONException.class) + /** + * Invalid XML string (tag contains a frontslash). + * Expects a JSONException + */ + @Test public void shouldHandleInvalidSlashInTag() { String xmlStr = "\n"+ @@ -46,10 +68,21 @@ public class XMLTest { " abc street\n"+ " \n"+ ""; - XML.toJSONObject(xmlStr); + try { + XML.toJSONObject(xmlStr); + assertTrue("Expecting a JSONException", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Misshaped tag at 176 [character 14 line 5]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Invalid XML string ('!' char in tag) + * Expects a JSONException + */ + @Test public void shouldHandleInvalidBangInTag() { String xmlStr = "\n"+ @@ -60,10 +93,21 @@ public class XMLTest { " \n"+ " \n"+ ""; - XML.toJSONObject(xmlStr); + try { + XML.toJSONObject(xmlStr); + assertTrue("Expecting a JSONException", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Misshaped meta tag at 215 [character 13 line 8]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Invalid XML string ('!' char and no closing tag brace) + * Expects a JSONException + */ + @Test public void shouldHandleInvalidBangNoCloseInTag() { String xmlStr = "\n"+ @@ -74,10 +118,21 @@ public class XMLTest { " \n"+ ""; - XML.toJSONObject(xmlStr); + try { + XML.toJSONObject(xmlStr); + assertTrue("Expecting a JSONException", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Misshaped meta tag at 214 [character 13 line 8]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Invalid XML string (no end brace for tag) + * Expects JSONException + */ + @Test public void shouldHandleNoCloseStartTag() { String xmlStr = "\n"+ @@ -88,10 +143,21 @@ public class XMLTest { " \n"+ ""; - XML.toJSONObject(xmlStr); + try { + XML.toJSONObject(xmlStr); + assertTrue("Expecting a JSONException", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Misplaced '<' at 193 [character 4 line 7]". + equals(e.getMessage())); + } } - @Test(expected=JSONException.class) + /** + * Invalid XML string (partial CDATA chars in tag name) + * Expects JSONException + */ + @Test public void shouldHandleInvalidCDATABangInTag() { String xmlStr = "\n"+ @@ -102,15 +168,29 @@ public class XMLTest { " \n"+ " \n"+ ""; - XML.toJSONObject(xmlStr); + try { + XML.toJSONObject(xmlStr); + assertTrue("Expecting a JSONException", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Expected 'CDATA[' at 204 [character 11 line 6]". + equals(e.getMessage())); + } } + /** + * Null JSONObject in XML.toString() + * Expects NullPointerException + */ @Test(expected=NullPointerException.class) public void shouldHandleNullJSONXML() { JSONObject jsonObject= null; XML.toString(jsonObject); } + /** + * Empty JSONObject in XML.toString() + */ @Test public void shouldHandleEmptyJSONXML() { JSONObject jsonObject= new JSONObject(); @@ -118,6 +198,9 @@ public class XMLTest { assertTrue("xml string should be empty", xmlStr.length() == 0); } + /** + * No SML start tag. The ending tag ends up being treated as content. + */ @Test public void shouldHandleNoStartTag() { String xmlStr = @@ -138,6 +221,9 @@ public class XMLTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * Valid XML to JSONObject + */ @Test public void shouldHandleSimpleXML() { String xmlStr = @@ -168,12 +254,15 @@ public class XMLTest { "},\"xsi:noNamespaceSchemaLocation\":"+ "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ "XMLSchema-instance\"}}"; - - JSONObject expectedJsonObject = new JSONObject(expectedStr); - JSONObject jsonObject = XML.toJSONObject(xmlStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + + compareStringToJSONObject(xmlStr, expectedStr); + compareReaderToJSONObject(xmlStr, expectedStr); + compareFileToJSONObject(xmlStr, expectedStr); } + /** + * Valid XML with comments to JSONObject + */ @Test public void shouldHandleCommentsInXML() { @@ -197,6 +286,9 @@ public class XMLTest { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } + /** + * Valid XML to XML.toString() + */ @Test public void shouldHandleToString() { String xmlStr = @@ -226,6 +318,10 @@ public class XMLTest { Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } + /** + * Converting a JSON doc containing '>' content to JSONObject, then + * XML.toString() should result in valid XML. + */ @Test public void shouldHandleContentNoArraytoString() { String expectedStr = @@ -242,6 +338,11 @@ public class XMLTest { finalStr+"]", expectedFinalStr.equals(finalStr)); } + /** + * Converting a JSON doc containing a 'content' array to JSONObject, then + * XML.toString() should result in valid XML. + * TODO: This is probably an error in how the 'content' keyword is used. + */ @Test public void shouldHandleContentArraytoString() { String expectedStr = @@ -259,6 +360,10 @@ public class XMLTest { finalStr+"]", expectedFinalStr.equals(finalStr)); } + /** + * Converting a JSON doc containing a named array to JSONObject, then + * XML.toString() should result in valid XML. + */ @Test public void shouldHandleArraytoString() { String expectedStr = @@ -276,6 +381,10 @@ public class XMLTest { finalStr+"]", expectedFinalStr.equals(finalStr)); } + /** + * Converting a JSON doc containing a named array of nested arrays to + * JSONObject, then XML.toString() should result in valid XML. + */ @Test public void shouldHandleNestedArraytoString() { String xmlStr = @@ -297,10 +406,10 @@ public class XMLTest { /** + * Possible bug: * Illegal node-names must be converted to legal XML-node-names. * The given example shows 2 nodes which are valid for JSON, but not for XML. * Therefore illegal arguments should be converted to e.g. an underscore (_). - * */ @Test public void shouldHandleIllegalJSONNodeNames() @@ -322,6 +431,9 @@ public class XMLTest { assertEquals(expected, result); } + /** + * JSONObject with NULL value, to XML.toString() + */ @Test public void shouldHandleNullNodeValue() { @@ -338,12 +450,11 @@ public class XMLTest { assertEquals(actualXML, resultXML); } + /** + * Investigate exactly how the "content" keyword works + */ @Test public void contentOperations() { - /** - * Make sure we understand exactly how the "content" keyword works - */ - /** * When a standalone Date: Sun, 23 Aug 2015 18:54:10 -0500 Subject: [PATCH 165/451] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 75d7861..19d0354 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # JSON-Java-unit-test Unit tests to validate the JSON-Java GitHub project code
+ https://github.com/douglascrockford/JSON-java
*These tests are a work in progress. Help from interested developers is welcome.*
From 1a5718dc396e4cb841aed023c1d059d636d3463e Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 27 Sep 2015 23:55:32 -0500 Subject: [PATCH 166/451] Commenting out some code until JSON-java supports XML.toJSONObject(Reader) --- XMLTest.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/XMLTest.java b/XMLTest.java index b7d7477..2f770ef 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -612,10 +612,14 @@ public class XMLTest { * @param expectedStr the expected JSON string */ private void compareReaderToJSONObject(String xmlStr, String expectedStr) { + /* + * Commenting out this method until the JSON-java code is updated + * to support XML.toJSONObject(reader) JSONObject expectedJsonObject = new JSONObject(expectedStr); Reader reader = new StringReader(xmlStr); JSONObject jsonObject = XML.toJSONObject(reader); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + */ } /** @@ -626,6 +630,9 @@ public class XMLTest { * @throws IOException */ private void compareFileToJSONObject(String xmlStr, String expectedStr) { + /* + * Commenting out this method until the JSON-java code is updated + * to support XML.toJSONObject(reader) try { JSONObject expectedJsonObject = new JSONObject(expectedStr); File tempFile = testFolder.newFile("fileToJSONObject.xml"); @@ -638,5 +645,6 @@ public class XMLTest { } catch (IOException e) { assertTrue("file writer error: " +e.getMessage(), false); } + */ } } \ No newline at end of file From 4b0db65877c18132d6b45b0a147ac5ba0c912fd4 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 12 Oct 2015 13:48:05 -0400 Subject: [PATCH 167/451] Fixes NPE in XML --- XMLTest.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/XMLTest.java b/XMLTest.java index 2f770ef..f680e18 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -1,12 +1,17 @@ package org.json.junit; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.io.*; +import java.io.IOException; -import org.json.*; -import org.junit.*; -import org.junit.rules.*; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.XML; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; /** @@ -180,9 +185,8 @@ public class XMLTest { /** * Null JSONObject in XML.toString() - * Expects NullPointerException */ - @Test(expected=NullPointerException.class) + @Test public void shouldHandleNullJSONXML() { JSONObject jsonObject= null; XML.toString(jsonObject); From cb63a968fa68ac39f94dfffb0962d91ed1d28862 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 12 Oct 2015 14:49:18 -0400 Subject: [PATCH 168/451] fixes test case to validate the input/output of the function being tested --- XMLTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/XMLTest.java b/XMLTest.java index f680e18..fb3b42c 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -189,7 +189,8 @@ public class XMLTest { @Test public void shouldHandleNullJSONXML() { JSONObject jsonObject= null; - XML.toString(jsonObject); + String actualXml=XML.toString(jsonObject); + assertEquals("generated XML does not equal expected XML","\"null\"",actualXml); } /** From 4a2f9b8cd395cf60582ec44fe0ebd66c3ba26769 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 14 Oct 2015 15:15:24 -0400 Subject: [PATCH 169/451] Adds test cases for corrected generic constructors and put methods --- JSONArrayTest.java | 119 +++++++++++++++++++++++++- JSONObjectTest.java | 199 ++++++++++++++++++++++++++++++++++++-------- 2 files changed, 281 insertions(+), 37 deletions(-) diff --git a/JSONArrayTest.java b/JSONArrayTest.java index 4c21456..1cb5dc3 100644 --- a/JSONArrayTest.java +++ b/JSONArrayTest.java @@ -1,10 +1,17 @@ package org.json.junit; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; -import org.json.*; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; import org.junit.Test; @@ -80,6 +87,112 @@ public class JSONArrayTest { equals(e.getMessage())); } } + + /** + * Verifies that the constructor has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyConstructor() { + + final JSONArray expected = new JSONArray("[10]"); + + @SuppressWarnings("rawtypes") + Collection myRawC = Collections.singleton(Integer.valueOf(10)); + JSONArray jaRaw = new JSONArray(myRawC); + + Collection myCInt = Collections.singleton(Integer.valueOf(10)); + JSONArray jaInt = new JSONArray(myCInt); + + Collection myCObj = Collections.singleton((Object) Integer + .valueOf(10)); + JSONArray jaObj = new JSONArray(myCObj); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObj)); + } + + /** + * Verifies that the put Collection has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyPutCollection() { + + final JSONArray expected = new JSONArray("[[10]]"); + + @SuppressWarnings("rawtypes") + Collection myRawC = Collections.singleton(Integer.valueOf(10)); + JSONArray jaRaw = new JSONArray(); + jaRaw.put(myRawC); + + Collection myCObj = Collections.singleton((Object) Integer + .valueOf(10)); + JSONArray jaObj = new JSONArray(); + jaObj.put(myCObj); + + Collection myCInt = Collections.singleton(Integer.valueOf(10)); + JSONArray jaInt = new JSONArray(); + jaInt.put(myCInt); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaInt)); + } + + + /** + * Verifies that the put Map has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyPutMap() { + + final JSONArray expected = new JSONArray("[{\"myKey\":10}]"); + + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONArray jaRaw = new JSONArray(); + jaRaw.put(myRawC); + + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONArray jaStrObj = new JSONArray(); + jaStrObj.put(myCStrObj); + + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONArray jaStrInt = new JSONArray(); + jaStrInt.put(myCStrInt); + + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONArray jaObjObj = new JSONArray(); + jaObjObj.put(myCObjObj); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); + } /** * Create a JSONArray doc with a variety of different elements. diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 240bbeb..1eec143 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -1,15 +1,32 @@ package org.json.junit; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; -import java.io.*; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; -import org.json.*; -import org.junit.*; +import org.json.CDL; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONString; +import org.json.XML; +import org.junit.Test; /** * Used in testing when a JSONString is needed @@ -149,6 +166,122 @@ public class JSONObjectTest { JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } + + /** + * Verifies that the constructor has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyConstructor() { + + final JSONObject expected = new JSONObject("{\"myKey\":10}"); + + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(myRawC); + + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONObject jaStrObj = new JSONObject(myCStrObj); + + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONObject jaStrInt = new JSONObject(myCStrInt); + + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONObject jaObjObj = new JSONObject(myCObjObj); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); + } + + /** + * Verifies that the put Collection has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyPutCollection() { + + final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); + + @SuppressWarnings("rawtypes") + Collection myRawC = Collections.singleton(Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(); + jaRaw.put("myCollection", myRawC); + + Collection myCObj = Collections.singleton((Object) Integer + .valueOf(10)); + JSONObject jaObj = new JSONObject(); + jaObj.put("myCollection", myCObj); + + Collection myCInt = Collections.singleton(Integer + .valueOf(10)); + JSONObject jaInt = new JSONObject(); + jaInt.put("myCollection", myCInt); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaInt)); + } + + + /** + * Verifies that the put Map has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyPutMap() { + + final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); + + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(); + jaRaw.put("myMap", myRawC); + + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONObject jaStrObj = new JSONObject(); + jaStrObj.put("myMap", myCStrObj); + + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONObject jaStrInt = new JSONObject(); + jaStrInt.put("myMap", myCStrInt); + + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONObject jaObjObj = new JSONObject(); + jaObjObj.put("myMap", myCObjObj); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); + } + /** * JSONObjects can be built from a Map. @@ -1229,10 +1362,9 @@ public class JSONObjectTest { * Confirm that map and nested JSONObject have the same contents. */ @Test - @SuppressWarnings("unchecked") public void jsonObjectToStringSuppressWarningOnCastToMap() { JSONObject jsonObject = new JSONObject(); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("abc", "def"); jsonObject.put("key", map); String toStr = jsonObject.toString(); @@ -1245,7 +1377,7 @@ public class JSONObjectTest { * in the debugger, one is a map and the other is a JSONObject. * TODO: write a util method for such comparisons */ - map = (Map)jsonObject.get("key"); + assertTrue("Maps should be entered as JSONObject", jsonObject.get("key") instanceof JSONObject); JSONObject mapJsonObject = expectedJsonObject.getJSONObject("key"); assertTrue("value size should be equal", map.size() == mapJsonObject.length() && map.size() == 1); @@ -1264,32 +1396,31 @@ public class JSONObjectTest { * Confirm that collection and nested JSONArray have the same contents. */ @Test - @SuppressWarnings("unchecked") public void jsonObjectToStringSuppressWarningOnCastToCollection() { - JSONObject jsonObject = new JSONObject(); - Collection collection = new ArrayList(); - collection.add("abc"); - // ArrayList will be added as an object - jsonObject.put("key", collection); - String toStr = jsonObject.toString(); - // [abc] will be added as a JSONArray - JSONObject expectedJsonObject = new JSONObject(toStr); - /** - * Can't do a Util compare because although they look the same - * in the debugger, one is a collection and the other is a JSONArray. - */ - assertTrue("keys should be equal", - jsonObject.keySet().iterator().next().equals( - expectedJsonObject.keySet().iterator().next())); - collection = (Collection)jsonObject.get("key"); - JSONArray jsonArray = expectedJsonObject.getJSONArray("key"); - assertTrue("value size should be equal", - collection.size() == jsonArray.length()); - Iterator it = collection.iterator(); - for (int i = 0; i < collection.size(); ++i) { - assertTrue("items should be equal for index: "+i, - jsonArray.get(i).toString().equals(it.next().toString())); - } + JSONObject jsonObject = new JSONObject(); + Collection collection = new ArrayList(); + collection.add("abc"); + // ArrayList will be added as an object + jsonObject.put("key", collection); + String toStr = jsonObject.toString(); + // [abc] will be added as a JSONArray + JSONObject expectedJsonObject = new JSONObject(toStr); + /** + * Can't do a Util compare because although they look the same in the + * debugger, one is a collection and the other is a JSONArray. + */ + assertTrue("keys should be equal", jsonObject.keySet().iterator() + .next().equals(expectedJsonObject.keySet().iterator().next())); + assertTrue("Collections should be converted to JSONArray", + jsonObject.get("key") instanceof JSONArray); + JSONArray jsonArray = expectedJsonObject.getJSONArray("key"); + assertTrue("value size should be equal", + collection.size() == jsonArray.length()); + Iterator it = collection.iterator(); + for (int i = 0; i < collection.size(); ++i) { + assertTrue("items should be equal for index: " + i, jsonArray + .get(i).toString().equals(it.next().toString())); + } } /** From 3850b5fd25968142e700058b6d11872e148ab63b Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 26 Oct 2015 18:35:53 -0400 Subject: [PATCH 170/451] Add tests to verify arrays are handled consistently. --- XMLTest.java | 103 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 87 insertions(+), 16 deletions(-) diff --git a/XMLTest.java b/XMLTest.java index fb3b42c..8069f70 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -385,6 +385,74 @@ public class XMLTest { assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ finalStr+"]", expectedFinalStr.equals(finalStr)); } + + /** + * Tests that the XML output for empty arrays is consistent. + */ + @Test + public void shouldHandleEmptyArray(){ + final JSONObject jo1 = new JSONObject(); + jo1.put("array",new Object[]{}); + final JSONObject jo2 = new JSONObject(); + jo2.put("array",new JSONArray()); + + final String expected = ""; + String output1 = XML.toString(jo1,"jo"); + assertTrue("Expected an empty root tag", expected.equals(output1)); + String output2 = XML.toString(jo2,"jo"); + assertTrue("Expected an empty root tag", expected.equals(output2)); + } + + /** + * Tests that the XML output for arrays is consistent when an internal array is empty. + */ + @Test + public void shouldHandleEmptyMultiArray(){ + final JSONObject jo1 = new JSONObject(); + jo1.put("arr",new Object[]{"One", new String[]{}, "Four"}); + final JSONObject jo2 = new JSONObject(); + jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{}), "Four"})); + + final String expected = "OneFour"; + String output1 = XML.toString(jo1,"jo"); + assertTrue("Expected a matching array", expected.equals(output1)); + String output2 = XML.toString(jo2,"jo"); + assertTrue("Expected a matching array", expected.equals(output2)); + } + + /** + * Tests that the XML output for arrays is consistent when arrays are not empty. + */ + @Test + public void shouldHandleNonEmptyArray(){ + final JSONObject jo1 = new JSONObject(); + jo1.put("arr",new String[]{"One", "Two", "Three"}); + final JSONObject jo2 = new JSONObject(); + jo2.put("arr",new JSONArray(new String[]{"One", "Two", "Three"})); + + final String expected = "OneTwoThree"; + String output1 = XML.toString(jo1,"jo"); + assertTrue("Expected a non empty root tag", expected.equals(output1)); + String output2 = XML.toString(jo2,"jo"); + assertTrue("Expected a non empty root tag", expected.equals(output2)); + } + + /** + * Tests that the XML output for arrays is consistent when arrays are not empty and contain internal arrays. + */ + @Test + public void shouldHandleMultiArray(){ + final JSONObject jo1 = new JSONObject(); + jo1.put("arr",new Object[]{"One", new String[]{"Two", "Three"}, "Four"}); + final JSONObject jo2 = new JSONObject(); + jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{"Two", "Three"}), "Four"})); + + final String expected = "OneTwoThreeFour"; + String output1 = XML.toString(jo1,"jo"); + assertTrue("Expected a matching array", expected.equals(output1)); + String output2 = XML.toString(jo2,"jo"); + assertTrue("Expected a matching array", expected.equals(output2)); + } /** * Converting a JSON doc containing a named array of nested arrays to @@ -425,7 +493,7 @@ public class XMLTest { String result = XML.toString(inputJSON); - /** + /* * This is invalid XML. Names should not begin with digits or contain * certain values, including '@'. One possible solution is to replace * illegal chars with '_', in which case the expected output would be: @@ -460,7 +528,7 @@ public class XMLTest { */ @Test public void contentOperations() { - /** + /* * When a standalone 0) then return".equals(jsonArray.get(0))); assertTrue("2. content array entry 1", "here is another cdata".equals(jsonArray.get(1))); - /** + /* * text content is accumulated in a "content" inside a local JSONObject. * If there is only one instance, it is saved in the context (a different JSONObject * from the calling code. and the content element is discarded. @@ -493,7 +561,7 @@ public class XMLTest { assertTrue("3. 2 items", 1 == jsonObject.length()); assertTrue("3. value tag1", "value 1".equals(jsonObject.get("tag1"))); - /** + /* * array-style text content (multiple tags with the same name) is * accumulated in a local JSONObject with key="content" and value=JSONArray, * saved in the context, and then the local JSONObject is discarded. @@ -508,7 +576,7 @@ public class XMLTest { assertTrue("4. content array entry 1", jsonArray.getInt(1) == 2); assertTrue("4. content array entry 2", jsonArray.getBoolean(2) == true); - /** + /* * Complex content is accumulated in a "content" field. For example, an element * may contain a mix of child elements and text. Each text segment is * accumulated to content. @@ -526,7 +594,7 @@ public class XMLTest { assertTrue("5. content array entry 0", "val1".equals(jsonArray.get(0))); assertTrue("5. content array entry 1", "val2".equals(jsonArray.get(1))); - /** + /* * If there is only 1 complex text content, then it is accumulated in a * "content" field as a string. */ @@ -538,7 +606,7 @@ public class XMLTest { assertTrue("6. contained content found", "val1".equals(jsonObject.get("content"))); assertTrue("6. contained tag2", "".equals(jsonObject.get("tag2"))); - /** + /* * In this corner case, the content sibling happens to have key=content * We end up with an array within an array, and no content element. * This is probably a bug. @@ -555,7 +623,7 @@ public class XMLTest { assertTrue("7. inner array item 0", "val1".equals(jsonArray.get(0))); assertTrue("7. inner array item 1", "".equals(jsonArray.get(1))); - /** + /* * Confirm behavior of original issue */ String jsonStr = @@ -581,7 +649,7 @@ public class XMLTest { "}"; jsonObject = new JSONObject(jsonStr); xmlStr = XML.toString(jsonObject); - /** + /* * This is the created XML. Looks like content was mistaken for * complex (child node + text) XML. * @@ -600,7 +668,7 @@ public class XMLTest { /** * Convenience method, given an input string and expected result, - * convert to JSONBObject and compare actual to expected result. + * convert to JSONObject and compare actual to expected result. * @param xmlStr the string to parse * @param expectedStr the expected JSON string */ @@ -612,7 +680,7 @@ public class XMLTest { /** * Convenience method, given an input string and expected result, - * convert to JSONBObject via reader and compare actual to expected result. + * convert to JSONObject via reader and compare actual to expected result. * @param xmlStr the string to parse * @param expectedStr the expected JSON string */ @@ -628,11 +696,14 @@ public class XMLTest { } /** - * Convenience method, given an input string and expected result, - * convert to JSONBObject via file and compare actual to expected result. - * @param xmlStr the string to parse - * @param expectedStr the expected JSON string - * @throws IOException + * Convenience method, given an input string and expected result, convert to + * JSONObject via file and compare actual to expected result. + * + * @param xmlStr + * the string to parse + * @param expectedStr + * the expected JSON string + * @throws IOException */ private void compareFileToJSONObject(String xmlStr, String expectedStr) { /* From 38cbc31624ed6dbce05e5c2710203dc906d99a8a Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 31 Oct 2015 03:58:04 -0500 Subject: [PATCH 171/451] Fix tabs, add valueToString() test to JSONObjectTest --- JSONArrayTest.java | 144 +++++++++++++------------- JSONObjectTest.java | 241 ++++++++++++++++++++++++-------------------- 2 files changed, 202 insertions(+), 183 deletions(-) diff --git a/JSONArrayTest.java b/JSONArrayTest.java index 1cb5dc3..8327e18 100644 --- a/JSONArrayTest.java +++ b/JSONArrayTest.java @@ -93,29 +93,29 @@ public class JSONArrayTest { */ @Test public void verifyConstructor() { - - final JSONArray expected = new JSONArray("[10]"); - - @SuppressWarnings("rawtypes") - Collection myRawC = Collections.singleton(Integer.valueOf(10)); - JSONArray jaRaw = new JSONArray(myRawC); + + final JSONArray expected = new JSONArray("[10]"); + + @SuppressWarnings("rawtypes") + Collection myRawC = Collections.singleton(Integer.valueOf(10)); + JSONArray jaRaw = new JSONArray(myRawC); - Collection myCInt = Collections.singleton(Integer.valueOf(10)); - JSONArray jaInt = new JSONArray(myCInt); + Collection myCInt = Collections.singleton(Integer.valueOf(10)); + JSONArray jaInt = new JSONArray(myCInt); - Collection myCObj = Collections.singleton((Object) Integer - .valueOf(10)); - JSONArray jaObj = new JSONArray(myCObj); + Collection myCObj = Collections.singleton((Object) Integer + .valueOf(10)); + JSONArray jaObj = new JSONArray(myCObj); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObj)); } /** @@ -123,32 +123,32 @@ public class JSONArrayTest { */ @Test public void verifyPutCollection() { - - final JSONArray expected = new JSONArray("[[10]]"); + + final JSONArray expected = new JSONArray("[[10]]"); - @SuppressWarnings("rawtypes") - Collection myRawC = Collections.singleton(Integer.valueOf(10)); - JSONArray jaRaw = new JSONArray(); - jaRaw.put(myRawC); + @SuppressWarnings("rawtypes") + Collection myRawC = Collections.singleton(Integer.valueOf(10)); + JSONArray jaRaw = new JSONArray(); + jaRaw.put(myRawC); - Collection myCObj = Collections.singleton((Object) Integer - .valueOf(10)); - JSONArray jaObj = new JSONArray(); - jaObj.put(myCObj); + Collection myCObj = Collections.singleton((Object) Integer + .valueOf(10)); + JSONArray jaObj = new JSONArray(); + jaObj.put(myCObj); - Collection myCInt = Collections.singleton(Integer.valueOf(10)); - JSONArray jaInt = new JSONArray(); - jaInt.put(myCInt); + Collection myCInt = Collections.singleton(Integer.valueOf(10)); + JSONArray jaInt = new JSONArray(); + jaInt.put(myCInt); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaInt)); } @@ -157,41 +157,41 @@ public class JSONArrayTest { */ @Test public void verifyPutMap() { - - final JSONArray expected = new JSONArray("[{\"myKey\":10}]"); + + final JSONArray expected = new JSONArray("[{\"myKey\":10}]"); - @SuppressWarnings("rawtypes") - Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); - JSONArray jaRaw = new JSONArray(); - jaRaw.put(myRawC); + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONArray jaRaw = new JSONArray(); + jaRaw.put(myRawC); - Map myCStrObj = Collections.singletonMap("myKey", - (Object) Integer.valueOf(10)); - JSONArray jaStrObj = new JSONArray(); - jaStrObj.put(myCStrObj); + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONArray jaStrObj = new JSONArray(); + jaStrObj.put(myCStrObj); - Map myCStrInt = Collections.singletonMap("myKey", - Integer.valueOf(10)); - JSONArray jaStrInt = new JSONArray(); - jaStrInt.put(myCStrInt); + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONArray jaStrInt = new JSONArray(); + jaStrInt.put(myCStrInt); - Map myCObjObj = Collections.singletonMap((Object) "myKey", - (Object) Integer.valueOf(10)); - JSONArray jaObjObj = new JSONArray(); - jaObjObj.put(myCObjObj); + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONArray jaObjObj = new JSONArray(); + jaObjObj.put(myCObjObj); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); } /** diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 1eec143..2d0fc4c 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -172,37 +172,37 @@ public class JSONObjectTest { */ @Test public void verifyConstructor() { - - final JSONObject expected = new JSONObject("{\"myKey\":10}"); - - @SuppressWarnings("rawtypes") - Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); - JSONObject jaRaw = new JSONObject(myRawC); + + final JSONObject expected = new JSONObject("{\"myKey\":10}"); + + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(myRawC); - Map myCStrObj = Collections.singletonMap("myKey", - (Object) Integer.valueOf(10)); - JSONObject jaStrObj = new JSONObject(myCStrObj); + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONObject jaStrObj = new JSONObject(myCStrObj); - Map myCStrInt = Collections.singletonMap("myKey", - Integer.valueOf(10)); - JSONObject jaStrInt = new JSONObject(myCStrInt); + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONObject jaStrInt = new JSONObject(myCStrInt); - Map myCObjObj = Collections.singletonMap((Object) "myKey", - (Object) Integer.valueOf(10)); - JSONObject jaObjObj = new JSONObject(myCObjObj); + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONObject jaObjObj = new JSONObject(myCObjObj); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); } /** @@ -210,33 +210,33 @@ public class JSONObjectTest { */ @Test public void verifyPutCollection() { - - final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); + + final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); - @SuppressWarnings("rawtypes") - Collection myRawC = Collections.singleton(Integer.valueOf(10)); - JSONObject jaRaw = new JSONObject(); - jaRaw.put("myCollection", myRawC); + @SuppressWarnings("rawtypes") + Collection myRawC = Collections.singleton(Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(); + jaRaw.put("myCollection", myRawC); - Collection myCObj = Collections.singleton((Object) Integer - .valueOf(10)); - JSONObject jaObj = new JSONObject(); - jaObj.put("myCollection", myCObj); + Collection myCObj = Collections.singleton((Object) Integer + .valueOf(10)); + JSONObject jaObj = new JSONObject(); + jaObj.put("myCollection", myCObj); - Collection myCInt = Collections.singleton(Integer - .valueOf(10)); - JSONObject jaInt = new JSONObject(); - jaInt.put("myCollection", myCInt); + Collection myCInt = Collections.singleton(Integer + .valueOf(10)); + JSONObject jaInt = new JSONObject(); + jaInt.put("myCollection", myCInt); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaInt)); } @@ -245,41 +245,41 @@ public class JSONObjectTest { */ @Test public void verifyPutMap() { - - final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); + + final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); - @SuppressWarnings("rawtypes") - Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); - JSONObject jaRaw = new JSONObject(); - jaRaw.put("myMap", myRawC); + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(); + jaRaw.put("myMap", myRawC); - Map myCStrObj = Collections.singletonMap("myKey", - (Object) Integer.valueOf(10)); - JSONObject jaStrObj = new JSONObject(); - jaStrObj.put("myMap", myCStrObj); + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONObject jaStrObj = new JSONObject(); + jaStrObj.put("myMap", myCStrObj); - Map myCStrInt = Collections.singletonMap("myKey", - Integer.valueOf(10)); - JSONObject jaStrInt = new JSONObject(); - jaStrInt.put("myMap", myCStrInt); + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONObject jaStrInt = new JSONObject(); + jaStrInt.put("myMap", myCStrInt); - Map myCObjObj = Collections.singletonMap((Object) "myKey", - (Object) Integer.valueOf(10)); - JSONObject jaObjObj = new JSONObject(); - jaObjObj.put("myMap", myCObjObj); + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONObject jaObjObj = new JSONObject(); + jaObjObj.put("myMap", myCObjObj); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); } @@ -640,7 +640,7 @@ public class JSONObjectTest { */ @Test public void jsonInvalidNumberValues() { - // Number-notations supported by Java and invalid as JSON + // Number-notations supported by Java and invalid as JSON String str = "{"+ "\"hexNumber\":-0x123,"+ @@ -1180,7 +1180,7 @@ public class JSONObjectTest { JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - /** + /** * float f = 3.1f; * double df = (double) f; * double d = 3.1d; @@ -1220,11 +1220,11 @@ public class JSONObjectTest { assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! // this.put(key, (Float) value + 1); - // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. - // 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects! - // 3. A float+float operation will be performed and results into a float primitive. - // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method - // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa + // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. + // 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects! + // 3. A float+float operation will be performed and results into a float primitive. + // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method + // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Double ); // correct implementation (with change of behavior) would be: // this.put(key, new Float((Float) value + 1)); @@ -1397,30 +1397,30 @@ public class JSONObjectTest { */ @Test public void jsonObjectToStringSuppressWarningOnCastToCollection() { - JSONObject jsonObject = new JSONObject(); - Collection collection = new ArrayList(); - collection.add("abc"); - // ArrayList will be added as an object - jsonObject.put("key", collection); - String toStr = jsonObject.toString(); - // [abc] will be added as a JSONArray - JSONObject expectedJsonObject = new JSONObject(toStr); - /** - * Can't do a Util compare because although they look the same in the - * debugger, one is a collection and the other is a JSONArray. - */ - assertTrue("keys should be equal", jsonObject.keySet().iterator() - .next().equals(expectedJsonObject.keySet().iterator().next())); - assertTrue("Collections should be converted to JSONArray", - jsonObject.get("key") instanceof JSONArray); - JSONArray jsonArray = expectedJsonObject.getJSONArray("key"); - assertTrue("value size should be equal", - collection.size() == jsonArray.length()); - Iterator it = collection.iterator(); - for (int i = 0; i < collection.size(); ++i) { - assertTrue("items should be equal for index: " + i, jsonArray - .get(i).toString().equals(it.next().toString())); - } + JSONObject jsonObject = new JSONObject(); + Collection collection = new ArrayList(); + collection.add("abc"); + // ArrayList will be added as an object + jsonObject.put("key", collection); + String toStr = jsonObject.toString(); + // [abc] will be added as a JSONArray + JSONObject expectedJsonObject = new JSONObject(toStr); + /** + * Can't do a Util compare because although they look the same in the + * debugger, one is a collection and the other is a JSONArray. + */ + assertTrue("keys should be equal", jsonObject.keySet().iterator() + .next().equals(expectedJsonObject.keySet().iterator().next())); + assertTrue("Collections should be converted to JSONArray", + jsonObject.get("key") instanceof JSONArray); + JSONArray jsonArray = expectedJsonObject.getJSONArray("key"); + assertTrue("value size should be equal", + collection.size() == jsonArray.length()); + Iterator it = collection.iterator(); + for (int i = 0; i < collection.size(); ++i) { + assertTrue("items should be equal for index: " + i, jsonArray + .get(i).toString().equals(it.next().toString())); + } } /** @@ -1471,6 +1471,25 @@ public class JSONObjectTest { jsonArray.toString().equals(JSONObject.valueToString(array))); } + /** + * Confirm that https://github.com/douglascrockford/JSON-java/issues/167 is fixed. + * The following code was throwing a ClassCastException in the + * JSONObject(Map) constructor + */ + @Test + public void valueToStringConfirmException() { + String expectedStr = "{\"1\":\"myValue\"}"; + Map myMap = new HashMap(); + myMap.put(1, "myValue"); + // this is the test, it should not throw an exception + String str = JSONObject.valueToString(myMap); + // confirm result, just in case + JSONObject jsonObject = new JSONObject(str); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject, + expectedJsonObject); + } + /** * Exercise the JSONObject wrap() method. Sometimes wrap() will change * the object being wrapped, other times not. The purpose of wrap() is From c6204a9f016c85212eb85a4979fc2fa280e90f78 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 26 Dec 2015 13:21:06 -0600 Subject: [PATCH 172/451] Replace util compare method with JsonPath --- JSONObjectTest.java | 720 +++++++++++++++++++++++++++----------------- 1 file changed, 444 insertions(+), 276 deletions(-) diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 2d0fc4c..d420e22 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -10,15 +10,7 @@ import java.io.StringWriter; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import java.util.*; import org.json.CDL; import org.json.JSONArray; @@ -28,6 +20,8 @@ import org.json.JSONString; import org.json.XML; import org.junit.Test; +import com.jayway.jsonpath.*; + /** * Used in testing when a JSONString is needed */ @@ -112,17 +106,24 @@ public class JSONObjectTest { "\"doubleKey\":-23.45e67"+ "}"; String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"}; - String expectedStr = - "{"+ - "\"falseKey\":false,"+ - "\"nullKey\":null,"+ - "\"stringKey\":\"hello world!\","+ - "\"doubleKey\":-23.45e67"+ - "}"; JSONObject jsonObject = new JSONObject(str); - JSONObject copyJsonObject = new JSONObject(jsonObject, keys); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(copyJsonObject, expectedJsonObject); + + // validate JSON + JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObjectByName.toString()); + Map> docMap = JsonPath.read(doc, "$"); + assertTrue("expected 4 items", docMap.size() == 4); + assertTrue("expected \"falseKey\":false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"nullKey\":null", + null == JsonPath.read(doc, "$.nullKey")); + assertTrue("expected \"stringKey\":\"hello world!\"", + "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue( + "expected \"doubleKey\":-23.45e67", + Double.valueOf("-23.45e67").equals( + JsonPath.read(doc, "$.doubleKey"))); } /** @@ -135,8 +136,7 @@ public class JSONObjectTest { public void jsonObjectByNullMap() { Map map = null; JSONObject jsonObject = new JSONObject(map); - JSONObject expectedJsonObject = new JSONObject(); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** @@ -145,26 +145,33 @@ public class JSONObjectTest { */ @Test public void jsonObjectByMap() { - String expectedStr = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ - "\"intKey\":42,"+ - "\"doubleKey\":-23.45e67"+ - "}"; - Map jsonMap = new HashMap(); - jsonMap.put("trueKey", new Boolean(true)); - jsonMap.put("falseKey", new Boolean(false)); - jsonMap.put("stringKey", "hello world!"); - jsonMap.put("escapeStringKey", "h\be\tllo w\u1234orld!"); - jsonMap.put("intKey", new Long(42)); - jsonMap.put("doubleKey", new Double(-23.45e67)); + Map map = new HashMap(); + map.put("trueKey", new Boolean(true)); + map.put("falseKey", new Boolean(false)); + map.put("stringKey", "hello world!"); + map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); + map.put("intKey", new Long(42)); + map.put("doubleKey", new Double(-23.45e67)); + JSONObject jsonObject = new JSONObject(map); - JSONObject jsonObject = new JSONObject(jsonMap); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 6 items", docMap.size() == 6); + assertTrue("expected \"trueKey\":true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected \"falseKey\":false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", + "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.escapeStringKey"))); + assertTrue( + "expected \"doubleKey\":-23.45e67", + Double.valueOf("-23.45e67").equals( + JsonPath.read(doc, "$.doubleKey"))); } /** @@ -290,19 +297,22 @@ public class JSONObjectTest { */ @Test public void jsonObjectByMapWithUnsupportedValues() { - String expectedStr = - "{"+ - "\"key1\":{},"+ - "\"key2\":\"java.lang.Exception\""+ - "}"; Map jsonMap = new HashMap(); // Just insert some random objects jsonMap.put("key1", new CDL()); jsonMap.put("key2", new Exception()); JSONObject jsonObject = new JSONObject(jsonMap); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 2 items", docMap.size() == 2); + assertTrue("expected \"key2\":java.lang.Exception", + "java.lang.Exception".equals(JsonPath.read(doc, "$.key2"))); + docMap = JsonPath.read(doc, "$.key1"); + assertTrue("expected 0 items", docMap.size() == 0); } /** @@ -311,27 +321,36 @@ public class JSONObjectTest { */ @Test public void jsonObjectByMapWithNullValue() { - String expectedStr = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ - "\"intKey\":42,"+ - "\"doubleKey\":-23.45e67"+ - "}"; - Map jsonMap = new HashMap(); - jsonMap.put("trueKey", new Boolean(true)); - jsonMap.put("falseKey", new Boolean(false)); - jsonMap.put("stringKey", "hello world!"); - jsonMap.put("nullKey", null); - jsonMap.put("escapeStringKey", "h\be\tllo w\u1234orld!"); - jsonMap.put("intKey", new Long(42)); - jsonMap.put("doubleKey", new Double(-23.45e67)); + Map map = new HashMap(); + map.put("trueKey", new Boolean(true)); + map.put("falseKey", new Boolean(false)); + map.put("stringKey", "hello world!"); + map.put("nullKey", null); + map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); + map.put("intKey", new Long(42)); + map.put("doubleKey", new Double(-23.45e67)); + JSONObject jsonObject = new JSONObject(map); - JSONObject jsonObject = new JSONObject(jsonMap); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 6 items", docMap.size() == 6); + assertTrue("expected \"trueKey\":true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected \"falseKey\":false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", + "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.escapeStringKey"))); + assertTrue("expected \"intKey\":42", + Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); + assertTrue( + "expected \"doubleKey\":-23.45e67", + Double.valueOf("-23.45e67").equals( + JsonPath.read(doc, "$.doubleKey"))); } /** @@ -340,18 +359,6 @@ public class JSONObjectTest { */ @Test public void jsonObjectByBean() { - String expectedStr = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ - "\"intKey\":42,"+ - "\"doubleKey\":-23.45e7,"+ - "\"stringReaderKey\":{},"+ - "\"callbacks\":[{\"handler\":{}},{}]"+ // sorry, mockito artifact - "}"; - /** * Default access classes have to be mocked since JSONObject, which is * not in the same package, cannot call MyBean methods by reflection. @@ -377,8 +384,37 @@ public class JSONObjectTest { }); JSONObject jsonObject = new JSONObject(myBean); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 8 items", docMap.size() == 8); + assertTrue("expected \"trueKey\":true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected \"falseKey\":false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", + "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.escapeStringKey"))); + assertTrue("expected \"intKey\":42", + Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); + assertTrue("expected \"doubleKey\":-23.45e7", Double + .valueOf("-23.45e7").equals(JsonPath.read(doc, "$.doubleKey"))); + assertTrue( + "expected \"stringReaderKey\":{}", + ((Map) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); + // sorry, mockito artifact + List docList = JsonPath.read(doc, "$.callbacks"); + assertTrue("expected 2 items", docList.size() == 2); + assertTrue("expected \"handler\":{}", + ((Map) (JsonPath.read(doc, + "$.callbacks[0].handler"))).size() == 0); + assertTrue("expected empty object", + ((Map) (JsonPath.read(doc, "$.callbacks[1]"))) + .size() == 0); } /** @@ -389,17 +425,20 @@ public class JSONObjectTest { */ @Test public void jsonObjectByObjectAndNames() { - String expectedStr = - "{"+ - "\"publicString\":\"abc\","+ - "\"publicInt\":42"+ - "}"; String[] keys = {"publicString", "publicInt"}; // just need a class that has public data members JSONObjectTest jsonObjectTest = new JSONObjectTest(); JSONObject jsonObject = new JSONObject(jsonObjectTest, keys); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 2 items", docMap.size() == 2); + assertTrue("expected \"publicString\":\"abc\"", + "abc".equals(JsonPath.read(doc, "$.publicString"))); + assertTrue("expected \"publicInt\":42", + Integer.valueOf(42).equals(JsonPath.read(doc, "$.publicInt"))); } /** @@ -408,22 +447,27 @@ public class JSONObjectTest { @Test public void jsonObjectByResourceBundle() { // TODO: how to improve resource bundle testing? - String expectedStr = - "{"+ - "\"greetings\": {"+ - "\"hello\":\"Hello, \","+ - "\"world\":\"World!\""+ - "},"+ - "\"farewells\": {"+ - "\"later\":\"Later, \","+ - "\"gator\":\"Alligator!\""+ - "}"+ - "}"; - JSONObject jsonObject = new + JSONObject jsonObject = new JSONObject("org.json.junit.StringsResourceBundle", Locale.getDefault()); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 2 items in top level map", docMap.size() == 2); + docMap = JsonPath.read(doc, "$.greetings"); + assertTrue("expected 2 items in greetings map", docMap.size() == 2); + assertTrue("expected \"hello\":\"Hello, \"", + "Hello, ".equals(JsonPath.read(doc, "$.greetings.hello"))); + assertTrue("expected \"world\":\"World!\"", + "World!".equals(JsonPath.read(doc, "$.greetings.world"))); + docMap = JsonPath.read(doc, "$.farewells"); + assertTrue("expected 2 items in farewells map", docMap.size() == 2); + assertTrue("expected \"later\":\"Later, \"", + "Later, ".equals(JsonPath.read(doc, "$.farewells.later"))); + assertTrue("expected \"world\":\"World!\"", + "Alligator!".equals(JsonPath.read(doc, "$.farewells.gator"))); } /** @@ -432,17 +476,7 @@ public class JSONObjectTest { @Test public void jsonObjectAccumulate() { // TODO: should include an unsupported object - String expectedStr = - "{"+ - "\"myArray\": ["+ - "true,"+ - "false,"+ - "\"hello world!\","+ - "\"h\be\tllo w\u1234orld!\","+ - "42,"+ - "-23.45e7"+ - "]"+ - "}"; + JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("myArray", true); jsonObject.accumulate("myArray", false); @@ -450,8 +484,29 @@ public class JSONObjectTest { jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); jsonObject.accumulate("myArray", 42); jsonObject.accumulate("myArray", -23.45e7); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 1 item in top level object", docMap.size() == 1); + List docList = JsonPath.read(doc, "$.myArray"); + assertTrue("expected 6 items in myArray", docList.size() == 6); + assertTrue("expected true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); + assertTrue("expected false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); + assertTrue("expected hello world!", + "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); + assertTrue("expected h\be\tllo w\u1234orld!", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.myArray[3]"))); + assertTrue("expected 42", + Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); + assertTrue( + "expected -23.45e7", + Double.valueOf(-23.45e7).equals( + JsonPath.read(doc, "$.myArray[5]"))); } /** @@ -460,17 +515,6 @@ public class JSONObjectTest { @Test public void jsonObjectAppend() { // TODO: should include an unsupported object - String expectedStr = - "{"+ - "\"myArray\": ["+ - "true,"+ - "false,"+ - "\"hello world!\","+ - "\"h\be\tllo w\u1234orld!\","+ - "42,"+ - "-23.45e7"+ - "]"+ - "}"; JSONObject jsonObject = new JSONObject(); jsonObject.append("myArray", true); jsonObject.append("myArray", false); @@ -478,8 +522,29 @@ public class JSONObjectTest { jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); jsonObject.append("myArray", 42); jsonObject.append("myArray", -23.45e7); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 1 item in top level object", docMap.size() == 1); + List docList = JsonPath.read(doc, "$.myArray"); + assertTrue("expected 6 items in myArray", docList.size() == 6); + assertTrue("expected true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); + assertTrue("expected false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); + assertTrue("expected hello world!", + "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); + assertTrue("expected h\be\tllo w\u1234orld!", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.myArray[3]"))); + assertTrue("expected 42", + Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); + assertTrue( + "expected -23.45e7", + Double.valueOf(-23.45e7).equals( + JsonPath.read(doc, "$.myArray[5]"))); } /** @@ -1058,19 +1123,47 @@ public class JSONObjectTest { "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ "}"; - String [] expectedNames = {"trueKey", "falseKey", "stringKey"}; jsonObject = new JSONObject(str); names = JSONObject.getNames(jsonObject); - Util.compareActualVsExpectedStringArrays(names, expectedNames); + JSONArray jsonArray = new JSONArray(names); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + List docList = JsonPath.read(doc, "$"); + assertTrue("expected 3 items", docList.size() == 3); + assertTrue( + "expected to find trueKey", + ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); + assertTrue( + "expected to find falseKey", + ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); + assertTrue( + "expected to find stringKey", + ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); /** * getNames() from an enum with properties has an interesting result. * It returns the enum values, not the selected enum properties */ - MyEnumField myEnumField = MyEnumField.VAL1; - String[] enumExpectedNames = {"VAL1", "VAL2", "VAL3"}; + MyEnumField myEnumField = MyEnumField.VAL1; names = JSONObject.getNames(myEnumField); - Util.compareActualVsExpectedStringArrays(names, enumExpectedNames); + + // validate JSON + jsonArray = new JSONArray(names); + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + docList = JsonPath.read(doc, "$"); + assertTrue("expected 3 items", docList.size() == 3); + assertTrue( + "expected to find VAL1", + ((List) JsonPath.read(doc, "$[?(@=='VAL1')]")).size() == 1); + assertTrue( + "expected to find VAL2", + ((List) JsonPath.read(doc, "$[?(@=='VAL2')]")).size() == 1); + assertTrue( + "expected to find VAL3", + ((List) JsonPath.read(doc, "$[?(@=='VAL3')]")).size() == 1); /** * A bean is also an object. But in order to test the static @@ -1078,9 +1171,20 @@ public class JSONObjectTest { * data members, which have been added to the class. */ JSONObjectTest jsonObjectTest = new JSONObjectTest(); - String [] jsonObjectTestExpectedNames = {"publicString", "publicInt"}; names = JSONObject.getNames(jsonObjectTest); - Util.compareActualVsExpectedStringArrays(names, jsonObjectTestExpectedNames); + + // validate JSON + jsonArray = new JSONArray(names); + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + docList = JsonPath.read(doc, "$"); + assertTrue("expected 2 items", docList.size() == 2); + assertTrue( + "expected to find publicString", + ((List) JsonPath.read(doc, "$[?(@=='publicString')]")).size() == 1); + assertTrue( + "expected to find publicInt", + ((List) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1); } /** @@ -1106,22 +1210,24 @@ public class JSONObjectTest { "\"falseKey\":false,"+ "\"stringKey\":\"hello world!\","+ "}"; - String [] expectedNames = {"trueKey", "falseKey", "stringKey" }; JSONObject jsonObject = new JSONObject(str); JSONArray jsonArray = jsonObject.names(); - /** - * Cannot really compare to an expected JSONArray because the ordering - * of the JSONObject keys is not fixed, and JSONArray comparisons - * presume fixed. Since this test is limited to key strings, a - * string comparison will have to suffice. - */ - String namesStr = jsonArray.toString(); - // remove square brackets, commas, and spaces - namesStr = namesStr.replaceAll("[\\]|\\[|\"]", ""); - String [] names = namesStr.split(","); - Util.compareActualVsExpectedStringArrays(names, expectedNames); + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + List docList = JsonPath.read(doc, "$"); + assertTrue("expected 3 items in array", docList.size() == 3); + assertTrue( + "expected to find trueKey", + ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); + assertTrue( + "expected to find falseKey", + ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); + assertTrue( + "expected to find stringKey", + ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); } /** @@ -1134,38 +1240,6 @@ public class JSONObjectTest { "\"keyLong\":9999999991,"+ "\"keyDouble\":1.1,"+ "}"; - String expectedStr = - "{"+ - "\"keyInt\":3,"+ - "\"keyLong\":9999999993,"+ - "\"keyDouble\":3.1,"+ - /** - * Should work the same way on any platform! @see - * https://docs.oracle - * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is - * the effect of a float to double conversion and is inherent to - * the shortcomings of the IEEE 754 format, when converting - * 32-bit into double-precision 64-bit. Java type-casts float to - * double. A 32 bit float is type-casted to 64 bit double by - * simply appending zero-bits to the mantissa (and extended the - * signed exponent by 3 bits.) and there is no way to obtain - * more information than it is stored in the 32-bits float. - * - * Like 1/3 cannot be represented as base10 number because it is - * periodically, 1/5 (for example) cannot be represented as - * base2 number since it is periodically in base2 (take a look - * at http://www.h-schmidt.net/FloatConverter/) The same happens - * to 3.1, that decimal number (base10 representation) is - * periodic in base2 representation, therefore appending - * zero-bits is inaccurate. Only repeating the periodically - * occuring bits (0110) would be a proper conversion. However - * one cannot detect from a 32 bit IEE754 representation which - * bits would "repeat infinitely", since the missing bits would - * not fit into the 32 bit float, i.e. the information needed - * simply is not there! - */ - "\"keyFloat\":3.0999999046325684,"+ - "}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("keyInt"); jsonObject.increment("keyInt"); @@ -1177,16 +1251,56 @@ public class JSONObjectTest { jsonObject.put("keyFloat", new Float(1.1)); jsonObject.increment("keyFloat"); jsonObject.increment("keyFloat"); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - /** - * float f = 3.1f; - * double df = (double) f; - * double d = 3.1d; - * System.out.println(Integer.toBinaryString(Float.floatToRawIntBits(f))); - * System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(df))); - * System.out.println(Long.toBinaryString(Double.doubleToRawLongBits(d))); + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 4 items in object", docMap.size() == 4); + assertTrue("expected to find keyInt:3", + Integer.valueOf(3).equals(JsonPath.read(doc, "$.keyInt"))); + assertTrue( + "expected to find keyLong:9999999993", + Long.valueOf(9999999993L).equals( + JsonPath.read(doc, "$.keyLong"))); + assertTrue("expected to find keyDouble:3.1", Double.valueOf(3.1) + .equals(JsonPath.read(doc, "$.keyDouble"))); + /** + * Should work the same way on any platform! @see https://docs.oracle + * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is the + * effect of a float to double conversion and is inherent to the + * shortcomings of the IEEE 754 format, when converting 32-bit into + * double-precision 64-bit. Java type-casts float to double. A 32 bit + * float is type-casted to 64 bit double by simply appending zero-bits + * to the mantissa (and extended the signed exponent by 3 bits.) and + * there is no way to obtain more information than it is stored in the + * 32-bits float. + * + * Like 1/3 cannot be represented as base10 number because it is + * periodically, 1/5 (for example) cannot be represented as base2 number + * since it is periodically in base2 (take a look at + * http://www.h-schmidt.net/FloatConverter/) The same happens to 3.1, + * that decimal number (base10 representation) is periodic in base2 + * representation, therefore appending zero-bits is inaccurate. Only + * repeating the periodically occuring bits (0110) would be a proper + * conversion. However one cannot detect from a 32 bit IEE754 + * representation which bits would "repeat infinitely", since the + * missing bits would not fit into the 32 bit float, i.e. the + * information needed simply is not there! + */ + assertTrue( + "expected to find keyFloat:3.0999999046325684", + Double.valueOf(3.0999999046325684).equals( + JsonPath.read(doc, "$.keyFloat"))); + + /** + * float f = 3.1f; double df = (double) f; double d = 3.1d; + * System.out.println + * (Integer.toBinaryString(Float.floatToRawIntBits(f))); + * System.out.println + * (Long.toBinaryString(Double.doubleToRawLongBits(df))); + * System.out.println + * (Long.toBinaryString(Double.doubleToRawLongBits(d))); * * - Float: * seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm @@ -1216,7 +1330,7 @@ public class JSONObjectTest { assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); JSONObject inc = new JSONObject(); - inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) + inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! // this.put(key, (Float) value + 1); @@ -1272,17 +1386,6 @@ public class JSONObjectTest { "\"myKey4\":\"myVal4\""+ "}"+ "}"; - String expectedStrAfterRemoval = - "{"+ - "\"falseKey\":false,"+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{"+ - "\"myKey1\":\"myVal1\","+ - "\"myKey2\":\"myVal2\","+ - "\"myKey3\":\"myVal3\","+ - "\"myKey4\":\"myVal4\""+ - "}"+ - "}"; JSONObject jsonObject = new JSONObject(); jsonObject.put("trueKey", true); jsonObject.put("falseKey", false); @@ -1294,19 +1397,40 @@ public class JSONObjectTest { myMap.put("myKey3", "myVal3"); myMap.put("myKey4", "myVal4"); jsonObject.put("objectKey", myMap); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - assertTrue("equal jsonObjects should be similar", - jsonObject.similar(expectedJsonObject)); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 4 items in object", docMap.size() == 4); + assertTrue("expected to find trueKey:true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected to find falseKey:false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + List docList = JsonPath.read(doc, "$.arrayKey"); + assertTrue("expected 3 items in array", docList.size() == 3); + assertTrue("expected to find 0", + Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); + assertTrue("expected to find 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); + assertTrue("expected to find 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + docMap = JsonPath.read(doc, "$.objectKey"); + assertTrue("expected 4 items in object", docMap.size() == 4); + assertTrue("expected to find myKey1:myVal1", + "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); + assertTrue("expected to find myKey2:myVal2", + "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); + assertTrue("expected to find myKey3:myVal3", + "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); + assertTrue("expected to find myKey4:myVal4", + "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); jsonObject.remove("trueKey"); - JSONObject expectedJsonObjectAfterRemoval = - new JSONObject(expectedStrAfterRemoval); - Util.compareActualVsExpectedJsonObjects(jsonObject, - expectedJsonObjectAfterRemoval); + JSONObject expectedJsonObject = new JSONObject(expectedStr); assertTrue("unequal jsonObjects should not be similar", !jsonObject.similar(expectedJsonObject)); - assertTrue("unequal Objects should not be similar", + assertTrue("jsonObject should not be similar to jsonArray", !jsonObject.similar(new JSONArray())); String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; @@ -1349,9 +1473,34 @@ public class JSONObjectTest { "}"+ "}"; JSONObject jsonObject = new JSONObject(str); - String toStr = jsonObject.toString(); - JSONObject expectedJsonObject = new JSONObject(toStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 4 items in object", docMap.size() == 4); + assertTrue("expected to find \"trueKey\":true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected to find \"falseKey\":false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + List docList = JsonPath.read(doc, "$.arrayKey"); + assertTrue("expected 3 array items", docList.size() == 3); + assertTrue("expected array value 0", + Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); + assertTrue("expected array value 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); + assertTrue("expected array value 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + docMap = JsonPath.read(doc, "$.objectKey"); + assertTrue("expected 4 items in objectKey object", docMap.size() == 4); + assertTrue("expected objectKey myKey1:myVal1", + "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); + assertTrue("expected objectKey myKey2:myVal2", + "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); + assertTrue("expected objectKey myKey3:myVal3", + "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); + assertTrue("expected objectKey myKey4:myVal4", + "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); } /** @@ -1367,25 +1516,16 @@ public class JSONObjectTest { Map map = new HashMap<>(); map.put("abc", "def"); jsonObject.put("key", map); - String toStr = jsonObject.toString(); - JSONObject expectedJsonObject = new JSONObject(toStr); - assertTrue("keys should be equal", - jsonObject.keySet().iterator().next().equals( - expectedJsonObject.keySet().iterator().next())); - /** - * Can't do a Util compare because although they look the same - * in the debugger, one is a map and the other is a JSONObject. - * TODO: write a util method for such comparisons - */ - assertTrue("Maps should be entered as JSONObject", jsonObject.get("key") instanceof JSONObject); - JSONObject mapJsonObject = expectedJsonObject.getJSONObject("key"); - assertTrue("value size should be equal", - map.size() == mapJsonObject.length() && map.size() == 1); - assertTrue("keys should be equal for key: "+map.keySet().iterator().next(), - mapJsonObject.keys().next().equals(map.keySet().iterator().next())); - assertTrue("values should be equal for key: "+map.keySet().iterator().next(), - mapJsonObject.get(mapJsonObject.keys().next()).toString().equals( - map.get(map.keySet().iterator().next()))); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 1 item in object", docMap.size() == 1); + docMap = JsonPath.read(doc, "$.key"); + assertTrue("expected 1 item in key object", docMap.size() == 1); + assertTrue("expected abc:def", + "def".equals(JsonPath.read(doc, "$.key.abc"))); } /** @@ -1402,25 +1542,15 @@ public class JSONObjectTest { collection.add("abc"); // ArrayList will be added as an object jsonObject.put("key", collection); - String toStr = jsonObject.toString(); - // [abc] will be added as a JSONArray - JSONObject expectedJsonObject = new JSONObject(toStr); - /** - * Can't do a Util compare because although they look the same in the - * debugger, one is a collection and the other is a JSONArray. - */ - assertTrue("keys should be equal", jsonObject.keySet().iterator() - .next().equals(expectedJsonObject.keySet().iterator().next())); - assertTrue("Collections should be converted to JSONArray", - jsonObject.get("key") instanceof JSONArray); - JSONArray jsonArray = expectedJsonObject.getJSONArray("key"); - assertTrue("value size should be equal", - collection.size() == jsonArray.length()); - Iterator it = collection.iterator(); - for (int i = 0; i < collection.size(); ++i) { - assertTrue("items should be equal for index: " + i, jsonArray - .get(i).toString().equals(it.next().toString())); - } + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 1 item in object", docMap.size() == 1); + List docList = JsonPath.read(doc, "$.key"); + assertTrue("expected 1 item in key object", docList.size() == 1); + assertTrue("expected abc", "abc".equals(JsonPath.read(doc, "$.key[0]"))); } /** @@ -1478,16 +1608,17 @@ public class JSONObjectTest { */ @Test public void valueToStringConfirmException() { - String expectedStr = "{\"1\":\"myValue\"}"; Map myMap = new HashMap(); myMap.put(1, "myValue"); // this is the test, it should not throw an exception String str = JSONObject.valueToString(myMap); // confirm result, just in case - JSONObject jsonObject = new JSONObject(str); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, - expectedJsonObject); + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(str); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 1 item in object", docMap.size() == 1); + assertTrue("expected myValue", + "myValue".equals(JsonPath.read(doc, "$.1"))); } /** @@ -1533,28 +1664,66 @@ public class JSONObjectTest { collection.add(new Integer(1)); collection.add(new Integer(2)); collection.add(new Integer(3)); - JSONArray jsonArray = (JSONArray)(JSONObject.wrap(collection)); - String expectedCollectionJsonArrayStr = - "[1,2,3]"; - JSONArray expectedCollectionJsonArray = - new JSONArray(expectedCollectionJsonArrayStr); - Util.compareActualVsExpectedJsonArrays(jsonArray, - expectedCollectionJsonArray); + JSONArray jsonArray = (JSONArray) (JSONObject.wrap(collection)); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + List docList = JsonPath.read(doc, "$"); + assertTrue("expected 3 items in array", docList.size() == 3); + assertTrue("expected 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", + Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); // wrap Array returns JSONArray Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); - JSONArray expectedIntegerArrayJsonArray = new JSONArray("[1,2,3]"); - Util.compareActualVsExpectedJsonArrays(integerArrayJsonArray, - expectedIntegerArrayJsonArray); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + docList = JsonPath.read(doc, "$"); + assertTrue("expected 3 items in array", docList.size() == 3); + assertTrue("expected 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", + Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(integerArrayJsonArray.toString()); + docList = JsonPath.read(doc, "$"); + assertTrue("expected 3 items in array", docList.size() == 3); + assertTrue("expected 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", + Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); // wrap map returns JSONObject Map map = new HashMap(); map.put("key1", "val1"); map.put("key2", "val2"); map.put("key3", "val3"); - JSONObject mapJsonObject = (JSONObject)(JSONObject.wrap(map)); - Util.compareActualVsExpectedJsonObjects(jsonObject, mapJsonObject); + JSONObject mapJsonObject = (JSONObject) (JSONObject.wrap(map)); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(mapJsonObject.toString()); + Map docMap = JsonPath.read(doc, "$"); + assertTrue("expected 3 items in object", docMap.size() == 3); + assertTrue("expected key1:val1", + "val1".equals(JsonPath.read(doc, "$.key1"))); + assertTrue("expected key2:val2", + "val2".equals(JsonPath.read(doc, "$.key2"))); + assertTrue("expected key3:val3", + "val3".equals(JsonPath.read(doc, "$.key3"))); // TODO test wrap(package) } @@ -1720,13 +1889,14 @@ public class JSONObjectTest { // put null should remove the item. String str = "{\"myKey\": \"myval\"}"; JSONObject jsonObjectRemove = new JSONObject(str); - JSONObject jsonObjectPutNull = new JSONObject(str); jsonObjectRemove.remove("myKey"); - jsonObjectPutNull.put("myKey", (Object)null); - Util.compareActualVsExpectedJsonObjects(jsonObjectRemove, jsonObjectPutNull); - assertTrue("jsonObject should be empty", - jsonObjectRemove.length() == 0 && - jsonObjectPutNull.length() == 0); + + JSONObject jsonObjectPutNull = new JSONObject(str); + jsonObjectPutNull.put("myKey", (Object) null); + + // validate JSON + assertTrue("jsonObject should be empty", jsonObjectRemove.length() == 0 + && jsonObjectPutNull.length() == 0); } /** @@ -1878,7 +2048,7 @@ public class JSONObjectTest { obj = null; jsonObjectNull.put("key", obj); value = jsonObjectNull.opt("key"); - assertTrue("opt() null should find null", value == null);; + assertTrue("opt() null should find null", value == null); if (value == null) { value = ""; } @@ -1904,5 +2074,3 @@ public class JSONObjectTest { assertTrue("null should emit an empty string", "".equals(sNull)); } } - - From a5390a068563e095f6a71452407f4ffd8cde5cd6 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 26 Dec 2015 19:02:02 -0600 Subject: [PATCH 173/451] Replace util compare method with JsonPath --- JSONArrayTest.java | 205 +++++++++++++++++++++++---------------------- 1 file changed, 105 insertions(+), 100 deletions(-) diff --git a/JSONArrayTest.java b/JSONArrayTest.java index 8327e18..c042acd 100644 --- a/JSONArrayTest.java +++ b/JSONArrayTest.java @@ -2,18 +2,15 @@ package org.json.junit; import static org.junit.Assert.assertTrue; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; +import java.util.*; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; +import com.jayway.jsonpath.*; + /** * Tests for JSON-Java JSONArray.java @@ -306,41 +303,41 @@ public class JSONArrayTest { /** * Exercise JSONArray.join() by converting a JSONArray into a * comma-separated string. Since this is very nearly a JSON document, - * array braces are added to the beginning and end, and it is reconverted - * back to a JSONArray for comparison. + * array braces are added to the beginning and end prior to validation. */ @Test public void join() { - String expectedStr = - "["+ - "true,"+ - "false,"+ - "\"true\","+ - "\"false\","+ - "\"hello\","+ - "0.002345,"+ - "\"23.45\","+ - "42,"+ - "\"43\","+ - "["+ - "\"world\""+ - "],"+ - "{"+ - "\"key1\":\"value1\","+ - "\"key2\":\"value2\","+ - "\"key3\":\"value3\","+ - "\"key4\":\"value4\""+ - "},"+ - "0,"+ - "\"-1\""+ - "]"; - JSONArray jsonArray = new JSONArray(arrayStr); String joinStr = jsonArray.join(","); - JSONArray finalJsonArray = new JSONArray("["+joinStr+"]"); - JSONArray expectedJsonArray = new JSONArray(expectedStr); - Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); - Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); + + // validate JSON + /** + * Don't need to remake the JSONArray to perform the parsing + */ + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse("["+joinStr+"]"); + List docList = JsonPath.read(doc, "$"); + assertTrue("expected 13 items in top level object", docList.size() == 13); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected \"true\"", "true".equals(JsonPath.read(doc, "$[2]"))); + assertTrue("expected \"false\"", "false".equals(JsonPath.read(doc, "$[3]"))); + assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[4]"))); + assertTrue("expected 0.002345", Double.valueOf(0.002345).equals(JsonPath.read(doc, "$[5]"))); + assertTrue("expected \"23.45\"", "23.45".equals(JsonPath.read(doc, "$[6]"))); + assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$[7]"))); + assertTrue("expected \"43\"", "43".equals(JsonPath.read(doc, "$[8]"))); + docList = JsonPath.read(doc, "$[9]"); + assertTrue("expected 1 array item", docList.size() == 1); + assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[9][0]"))); + Map docMap = JsonPath.read(doc, "$[10]"); + assertTrue("expected 4 object items", docMap.size() == 4); + assertTrue("expected value1", "value1".equals(JsonPath.read(doc, "$[10].key1"))); + assertTrue("expected value2", "value2".equals(JsonPath.read(doc, "$[10].key2"))); + assertTrue("expected value3", "value3".equals(JsonPath.read(doc, "$[10].key3"))); + assertTrue("expected value4", "value4".equals(JsonPath.read(doc, "$[10].key4"))); + assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$[11]"))); + assertTrue("expected \"-1\"", "-1".equals(JsonPath.read(doc, "$[12]"))); } /** @@ -419,33 +416,7 @@ public class JSONArrayTest { */ @Test public void put() { - String expectedStr = - "["+ - "true,"+ - "false,"+ - "["+ - "hello,"+ - "world"+ - "],"+ - "2.5,"+ - "1,"+ - "45,"+ - "\"objectPut\","+ - "{"+ - "\"key10\":\"val10\","+ - "\"key20\":\"val20\","+ - "\"key30\":\"val30\""+ - "},"+ - "{"+ - "\"k1\":\"v1\""+ - "},"+ - "["+ - "1,"+ - "2"+ - "]"+ - "]"; JSONArray jsonArray = new JSONArray(); - JSONArray expectedJsonArray = new JSONArray(expectedStr); // index 0 jsonArray.put(true); @@ -488,9 +459,36 @@ public class JSONArrayTest { Collection collection = new ArrayList(); collection.add(1); collection.add(2); - // 9 + // 9 jsonArray.put(collection); - Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + List docList = JsonPath.read(doc, "$"); + assertTrue("expected 10 items in top level object", docList.size() == 10); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); + docList = JsonPath.read(doc, "$[2]"); + assertTrue("expected 2 items in array", docList.size() == 2); + assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[2][0]"))); + assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[2][1]"))); + assertTrue("expected 2.5", Double.valueOf(2.5).equals(JsonPath.read(doc, "$[3]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[4]"))); + assertTrue("expected 45", Integer.valueOf(45).equals(JsonPath.read(doc, "$[5]"))); + assertTrue("expected objectPut", "objectPut".equals(JsonPath.read(doc, "$[6]"))); + Map docMap = JsonPath.read(doc, "$[7]"); + assertTrue("expected 3 items in object", docMap.size() == 3); + assertTrue("expected val10", "val10".equals(JsonPath.read(doc, "$[7].key10"))); + assertTrue("expected val20", "val20".equals(JsonPath.read(doc, "$[7].key20"))); + assertTrue("expected val30", "val30".equals(JsonPath.read(doc, "$[7].key30"))); + docMap = JsonPath.read(doc, "$[8]"); + assertTrue("expected 1 item in object", docMap.size() == 1); + assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$[8].k1"))); + docList = JsonPath.read(doc, "$[9]"); + assertTrue("expected 2 items in array", docList.size() == 2); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[9][0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[9][1]"))); } /** @@ -499,34 +497,7 @@ public class JSONArrayTest { */ @Test public void putIndex() { - String expectedStr = - "["+ - "true,"+ - "false,"+ - "["+ - "hello,"+ - "world"+ - "],"+ - "2.5,"+ - "1,"+ - "45,"+ - "\"objectPut\","+ - "null,"+ - "{"+ - "\"key10\":\"val10\","+ - "\"key20\":\"val20\","+ - "\"key30\":\"val30\""+ - "},"+ - "["+ - "1,"+ - "2"+ - "],"+ - "{"+ - "\"k1\":\"v1\""+ - "},"+ - "]"; JSONArray jsonArray = new JSONArray(); - JSONArray expectedJsonArray = new JSONArray(expectedStr); // 1 jsonArray.put(1, false); @@ -573,7 +544,35 @@ public class JSONArrayTest { jsonArray.put(-1, "abc"); assertTrue("put index < 0 should have thrown exception", false); } catch(Exception ignored) {} - Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + List docList = JsonPath.read(doc, "$"); + assertTrue("expected 11 items in top level object", docList.size() == 11); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); + docList = JsonPath.read(doc, "$[2]"); + assertTrue("expected 2 items in array", docList.size() == 2); + assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[2][0]"))); + assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[2][1]"))); + assertTrue("expected 2.5", Double.valueOf(2.5).equals(JsonPath.read(doc, "$[3]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[4]"))); + assertTrue("expected 45", Integer.valueOf(45).equals(JsonPath.read(doc, "$[5]"))); + assertTrue("expected objectPut", "objectPut".equals(JsonPath.read(doc, "$[6]"))); + assertTrue("expected null", null == JsonPath.read(doc, "$[7]")); + Map docMap = JsonPath.read(doc, "$[8]"); + assertTrue("expected 3 items in object", docMap.size() == 3); + assertTrue("expected val10", "val10".equals(JsonPath.read(doc, "$[8].key10"))); + assertTrue("expected val20", "val20".equals(JsonPath.read(doc, "$[8].key20"))); + assertTrue("expected val30", "val30".equals(JsonPath.read(doc, "$[8].key30"))); + docList = JsonPath.read(doc, "$[9]"); + assertTrue("expected 2 items in array", docList.size() == 2); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[9][0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[9][1]"))); + docMap = JsonPath.read(doc, "$[10]"); + assertTrue("expected 1 item in object", docMap.size() == 1); + assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$[10].k1"))); } /** @@ -587,10 +586,9 @@ public class JSONArrayTest { "1"+ "]"; JSONArray jsonArray = new JSONArray(arrayStr); - JSONArray expectedJsonArray = new JSONArray(); jsonArray.remove(0); assertTrue("array should be empty", null == jsonArray.remove(5)); - Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + assertTrue("jsonArray should be empty", jsonArray.length() == 0); } /** @@ -648,15 +646,22 @@ public class JSONArrayTest { */ @Test public void objectArrayVsIsArray() { - String expectedStr = - "["+ - "1,2,3,4,5,6,7"+ - "]"; int[] myInts = { 1, 2, 3, 4, 5, 6, 7 }; Object myObject = myInts; JSONArray jsonArray = new JSONArray(myObject); - JSONArray expectedJsonArray = new JSONArray(expectedStr); - Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + List docList = JsonPath.read(doc, "$"); + assertTrue("expected 7 items in top level object", docList.size() == 7); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + assertTrue("expected 4", Integer.valueOf(4).equals(JsonPath.read(doc, "$[3]"))); + assertTrue("expected 5", Integer.valueOf(5).equals(JsonPath.read(doc, "$[4]"))); + assertTrue("expected 6", Integer.valueOf(6).equals(JsonPath.read(doc, "$[5]"))); + assertTrue("expected 7", Integer.valueOf(7).equals(JsonPath.read(doc, "$[6]"))); } /** From d329b6514c706cdb4502df609128922b9962c7b0 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 27 Dec 2015 15:17:01 -0600 Subject: [PATCH 174/451] Replace util compare method with JsonPath --- EnumTest.java | 170 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 110 insertions(+), 60 deletions(-) diff --git a/EnumTest.java b/EnumTest.java index d24824b..2d2ebb9 100644 --- a/EnumTest.java +++ b/EnumTest.java @@ -2,9 +2,13 @@ package org.json.junit; import static org.junit.Assert.*; +import java.util.*; + import org.json.*; import org.junit.*; +import com.jayway.jsonpath.*; + /** * Enums are not explicitly supported in JSON-Java. But because enums act like * classes, all required behavior is already be present in some form. @@ -25,23 +29,37 @@ public class EnumTest { assertTrue("simple enum has no getters", jsonObject.length() == 0); // enum with a getters should create a non-empty object - String expectedStr = "{\"value\":\"val 2\", \"intVal\":2}"; MyEnumField myEnumField = MyEnumField.VAL2; jsonObject = new JSONObject(myEnumField); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON content + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expecting 2 items in top level object", + ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expecting val 2", "val 2".equals(JsonPath.read(doc, "$.value"))); + assertTrue("expecting 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal"))); /** * class which contains enum instances. Each enum should be stored * in its own JSONObject */ - expectedStr = "{\"myEnumField\":{\"intVal\":3,\"value\":\"val 3\"},\"myEnum\":{}}"; MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); myEnumClass.setMyEnumField(MyEnumField.VAL3); jsonObject = new JSONObject(myEnumClass); - expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON content + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expecting 2 items in top level object", + ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expecting 2 items in myEnumField object", + ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); + assertTrue("expecting 0 items in myEnum object", + ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); + assertTrue("expecting 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal"))); + assertTrue("expecting val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value"))); } /** @@ -51,28 +69,30 @@ public class EnumTest { @Test public void jsonObjectFromEnumWithNames() { String [] names; - String expectedStr; JSONObject jsonObject; - JSONObject finalJsonObject; - JSONObject expectedJsonObject; - expectedStr = "{\"VAL1\":\"VAL1\",\"VAL2\":\"VAL2\",\"VAL3\":\"VAL3\"}"; MyEnum myEnum = MyEnum.VAL1; names = JSONObject.getNames(myEnum); - // The values will be MyEnmField fields, so need to convert back to string for comparison + // The values will be MyEnum fields jsonObject = new JSONObject(myEnum, names); - finalJsonObject = new JSONObject(jsonObject.toString()); - expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedJsonObject); - expectedStr = "{\"VAL1\":\"VAL1\",\"VAL2\":\"VAL2\",\"VAL3\":\"VAL3\"}"; + // validate JSON object + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1"))); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2"))); + assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3"))); + MyEnumField myEnumField = MyEnumField.VAL3; names = JSONObject.getNames(myEnumField); - // The values will be MyEnmField fields, so need to convert back to string for comparison + // The values will be MyEnmField fields jsonObject = new JSONObject(myEnumField, names); - finalJsonObject = new JSONObject(jsonObject.toString()); - expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedJsonObject); + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1"))); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2"))); + assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3"))); + } /** @@ -81,29 +101,33 @@ public class EnumTest { */ @Test public void enumPut() { - String expectedFinalStr = "{\"myEnum\":\"VAL2\", \"myEnumField\":\"VAL1\"}"; JSONObject jsonObject = new JSONObject(); MyEnum myEnum = MyEnum.VAL2; jsonObject.put("myEnum", myEnum); - assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonObject.get("myEnum"))); - assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonObject.opt("myEnum"))); MyEnumField myEnumField = MyEnumField.VAL1; jsonObject.putOnce("myEnumField", myEnumField); - assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonObject.get("myEnumField"))); - assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonObject.opt("myEnumField"))); - JSONObject finalJsonObject = new JSONObject(jsonObject.toString()); - JSONObject expectedFinalJsonObject = new JSONObject(expectedFinalStr); - Util.compareActualVsExpectedJsonObjects(finalJsonObject, expectedFinalJsonObject); + // validate JSON content + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level objects", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnum"))); + assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.myEnumField"))); + JSONArray jsonArray = new JSONArray(); jsonArray.put(myEnum); jsonArray.put(1, myEnumField); + + // validate JSON content + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 2 top level objects", ((List)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$[1]"))); + + /** + * Leaving these tests because they exercise get, opt, and remove + */ assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonArray.get(0))); assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.opt(1))); - JSONArray expectedJsonArray = new JSONArray(); - expectedJsonArray.put(MyEnum.VAL2); - expectedJsonArray.put(MyEnumField.VAL1); - Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.remove(1))); } @@ -151,49 +175,66 @@ public class EnumTest { MyEnumField myEnumField = MyEnumField.VAL2; jsonObject = new JSONObject(myEnumField); - expectedStr = "{\"value\":\"val 2\", \"intVal\":2}"; - JSONObject actualJsonObject = new JSONObject(jsonObject.toString()); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); - expectedStr = "{\"myEnumField\":{\"intVal\":3,\"value\":\"val 3\"},\"myEnum\":{}}"; + // validate JSON content + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected val 2", "val 2".equals(JsonPath.read(doc, "$.value"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal"))); + MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); myEnumClass.setMyEnumField(MyEnumField.VAL3); jsonObject = new JSONObject(myEnumClass); - actualJsonObject = new JSONObject(jsonObject.toString()); - expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); - expectedStr = "{\"VAL1\":\"VAL1\",\"VAL2\":\"VAL2\",\"VAL3\":\"VAL3\"}"; + // validate JSON content + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected 2 myEnumField items", ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); + assertTrue("expected 0 myEnum items", ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal"))); + assertTrue("expected val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value"))); + String [] names = JSONObject.getNames(myEnum); jsonObject = new JSONObject(myEnum, names); - actualJsonObject = new JSONObject(jsonObject.toString()); - expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); - expectedStr = "{\"VAL1\":\"VAL1\",\"VAL2\":\"VAL2\",\"VAL3\":\"VAL3\"}"; + // validate JSON content + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1"))); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2"))); + assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3"))); + names = JSONObject.getNames(myEnumField); jsonObject = new JSONObject(myEnumField, names); - actualJsonObject = new JSONObject(jsonObject.toString()); - expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); + + // validate JSON content + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1"))); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2"))); + assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3"))); expectedStr = "{\"myEnum\":\"VAL2\", \"myEnumField\":\"VAL2\"}"; jsonObject = new JSONObject(); jsonObject.putOpt("myEnum", myEnum); jsonObject.putOnce("myEnumField", myEnumField); - actualJsonObject = new JSONObject(jsonObject.toString()); - expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(actualJsonObject, expectedJsonObject); - expectedStr = "[\"VAL2\", \"VAL2\"]"; + // validate JSON content + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnum"))); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnumField"))); + JSONArray jsonArray = new JSONArray(); jsonArray.put(myEnum); jsonArray.put(1, myEnumField); - JSONArray actualJsonArray = new JSONArray(jsonArray.toString()); - JSONArray expectedJsonArray = new JSONArray(expectedStr); - Util.compareActualVsExpectedJsonArrays(actualJsonArray, expectedJsonArray); + + // validate JSON content + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 2 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[1]"))); } /** @@ -206,19 +247,28 @@ public class EnumTest { JSONObject jsonObject = (JSONObject)JSONObject.wrap(myEnum); assertTrue("simple enum has no getters", jsonObject.length() == 0); - String expectedStr = "{\"value\":\"val 2\", \"intVal\":2}"; MyEnumField myEnumField = MyEnumField.VAL2; jsonObject = (JSONObject)JSONObject.wrap(myEnumField); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); - expectedStr = "{\"myEnumField\":{\"intVal\":3,\"value\":\"val 3\"},\"myEnum\":{}}"; + // validate JSON content + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected val 2", "val 2".equals(JsonPath.read(doc, "$.value"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal"))); + MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); myEnumClass.setMyEnumField(MyEnumField.VAL3); jsonObject = (JSONObject)JSONObject.wrap(myEnumClass); - expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + // validate JSON content + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected 2 myEnumField items", ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); + assertTrue("expected 0 myEnum items", ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal"))); + assertTrue("expected val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value"))); + } /** From 7187006bae9135275b2cef6b3dd1213d0c4df395 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 27 Dec 2015 17:01:42 -0600 Subject: [PATCH 175/451] Replace util compare method with JsonPath --- CookieListTest.java | 112 +++++++++++++++++++++++++------------------- 1 file changed, 64 insertions(+), 48 deletions(-) diff --git a/CookieListTest.java b/CookieListTest.java index 1d7ad8a..98ede86 100644 --- a/CookieListTest.java +++ b/CookieListTest.java @@ -2,9 +2,13 @@ package org.json.junit; import static org.junit.Assert.*; +import java.util.*; + import org.json.*; import org.junit.Test; +import com.jayway.jsonpath.*; + /** * HTTP cookie specification RFC6265: http://tools.ietf.org/html/rfc6265 *

@@ -60,7 +64,6 @@ public class CookieListTest { @Test public void emptyStringCookieList() { String cookieStr = ""; - String expectedCookieStr = ""; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); assertTrue(jsonObject.length() == 0); } @@ -71,10 +74,13 @@ public class CookieListTest { @Test public void simpleCookieList() { String cookieStr = "SID=31d4d96e407aad42"; - String expectedCookieStr = "{\"SID\":\"31d4d96e407aad42\"}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Object doc = Configuration.defaultConfiguration().jsonProvider(). + parse(jsonObject.toString()); + assertTrue("Expected 1 top level item", + ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 31d4d96e407aad42", + "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID"))); } /** @@ -83,10 +89,13 @@ public class CookieListTest { @Test public void simpleCookieListWithDelimiter() { String cookieStr = "SID=31d4d96e407aad42;"; - String expectedCookieStr = "{\"SID\":\"31d4d96e407aad42\"}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Object doc = Configuration.defaultConfiguration().jsonProvider(). + parse(jsonObject.toString()); + assertTrue("Expected 1 top level item", + ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 31d4d96e407aad42", + "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID"))); } /** @@ -102,18 +111,23 @@ public class CookieListTest { " name4=myCookieValue4; "+ "name5=myCookieValue5;"+ " name6=myCookieValue6;"; - String expectedCookieStr = - "{"+ - "\"name1\":\"myCookieValue1\","+ - "\"name2\":\"myCookieValue2\","+ - "\"name3\":\"myCookieValue3\","+ - "\"name4\":\"myCookieValue4\","+ - "\"name5\":\"myCookieValue5\","+ - "\"name6\":\"myCookieValue6\""+ - "}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Object doc = Configuration.defaultConfiguration().jsonProvider(). + parse(jsonObject.toString()); + assertTrue("Expected 6 top level items", + ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected myCookieValue1", + "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); + assertTrue("expected myCookieValue2", + "myCookieValue2".equals(JsonPath.read(doc, "$.name2"))); + assertTrue("expected myCookieValue3", + "myCookieValue3".equals(JsonPath.read(doc, "$.name3"))); + assertTrue("expected myCookieValue4", + "myCookieValue4".equals(JsonPath.read(doc, "$.name4"))); + assertTrue("expected myCookieValue5", + "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); + assertTrue("expected myCookieValue6", + "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); } /** @@ -139,21 +153,23 @@ public class CookieListTest { " name4=myCookieValue4; "+ "name5=myCookieValue5;"+ " name6=myCookieValue6;"; - String expectedCookieStr = - "{"+ - "\"name1\":\"myCookieValue1\","+ - "\"name2\":\"myCookieValue2\","+ - "\"name3\":\"myCookieValue3\","+ - "\"name4\":\"myCookieValue4\","+ - "\"name5\":\"myCookieValue5\","+ - "\"name6\":\"myCookieValue6\""+ - "}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); - String cookieToStr = CookieList.toString(jsonObject); - JSONObject finalJsonObject = CookieList.toJSONObject(cookieToStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); - Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + Object doc = Configuration.defaultConfiguration().jsonProvider(). + parse(jsonObject.toString()); + assertTrue("Expected 6 top level items", + ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected myCookieValue1", + "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); + assertTrue("expected myCookieValue2", + "myCookieValue2".equals(JsonPath.read(doc, "$.name2"))); + assertTrue("expected myCookieValue3", + "myCookieValue3".equals(JsonPath.read(doc, "$.name3"))); + assertTrue("expected myCookieValue4", + "myCookieValue4".equals(JsonPath.read(doc, "$.name4"))); + assertTrue("expected myCookieValue5", + "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); + assertTrue("expected myCookieValue6", + "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); } /** @@ -169,22 +185,22 @@ public class CookieListTest { " name4=my%25CookieValue4; "+ "name5=myCookieValue5;"+ " name6=myCookieValue6;"; - String expectedCookieStr = - "{"+ - "\"name1\":\"myCookieValue1\","+ - "\"name2\":\"my Cookie Value 2\","+ - "\"name3\":\"my+Cookie&Value;3=\","+ - "\"name4\":\"my%CookieValue4\","+ - "\"name5\":\"myCookieValue5\","+ - "\"name6\":\"myCookieValue6\""+ - "}"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); - String cookieToStr = CookieList.toString(jsonObject); - JSONObject finalJsonObject = CookieList.toJSONObject(cookieToStr); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); - Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + Object doc = Configuration.defaultConfiguration().jsonProvider(). + parse(jsonObject.toString()); + assertTrue("Expected 6 top level items", + ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected myCookieValue1", + "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); + assertTrue("expected my Cookie Value 2", + "my Cookie Value 2".equals(JsonPath.read(doc, "$.name2"))); + assertTrue("expected my+Cookie&Value;3=", + "my+Cookie&Value;3=".equals(JsonPath.read(doc, "$.name3"))); + assertTrue("expected my%CookieValue4", + "my%CookieValue4".equals(JsonPath.read(doc, "$.name4"))); + assertTrue("expected my%CookieValue5", + "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); + assertTrue("expected myCookieValue6", + "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); } - - } From 48c872f66f4889754da36b209f1e8ade894744ab Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 28 Dec 2015 11:12:41 -0600 Subject: [PATCH 176/451] Replace util compare method with JsonPath --- JSONStringerTest.java | 108 ++++++++++++++++++++---------------------- 1 file changed, 51 insertions(+), 57 deletions(-) diff --git a/JSONStringerTest.java b/JSONStringerTest.java index 7a35064..4e9a9db 100644 --- a/JSONStringerTest.java +++ b/JSONStringerTest.java @@ -2,9 +2,13 @@ package org.json.junit; import static org.junit.Assert.*; +import java.util.*; + import org.json.*; import org.junit.Test; +import com.jayway.jsonpath.*; + /** * Tests for JSON-Java JSONStringer. @@ -175,16 +179,6 @@ public class JSONStringerTest { */ @Test public void simpleObjectString() { - String expectedStr = - "{"+ - "\"trueValue\":true,"+ - "\"falseValue\":false,"+ - "\"nullValue\":null,"+ - "\"stringValue\":\"hello world!\","+ - "\"complexStringValue\":\"h\be\tllo w\u1234orld!\","+ - "\"intValue\":42,"+ - "\"doubleValue\":-23.45e67"+ - "}"; JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object(); jsonStringer.key("trueValue").value(true); @@ -197,8 +191,16 @@ public class JSONStringerTest { jsonStringer.endObject(); String str = jsonStringer.toString(); JSONObject jsonObject = new JSONObject(str); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 7 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 7); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueValue"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseValue"))); + assertTrue("expected null", null == JsonPath.read(doc, "$.nullValue")); + assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.stringValue"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, "$.complexStringValue"))); + assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.intValue"))); + assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(JsonPath.read(doc, "$.doubleValue"))); } /** @@ -207,15 +209,6 @@ public class JSONStringerTest { */ @Test public void simpleArrayString() { - String expectedStr = - "["+ - "true,"+ - "false,"+ - "null,"+ - "\"hello world!\","+ - "42,"+ - "-23.45e67"+ - "]"; JSONStringer jsonStringer = new JSONStringer(); jsonStringer.array(); jsonStringer.value(true); @@ -227,8 +220,15 @@ public class JSONStringerTest { jsonStringer.endArray(); String str = jsonStringer.toString(); JSONArray jsonArray = new JSONArray(str); - JSONArray expectedJsonArray = new JSONArray(expectedStr); - Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 6 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected null", null == JsonPath.read(doc, "$[2]")); + assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$[3]"))); + assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$[4]"))); + assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(JsonPath.read(doc, "$[5]"))); } /** @@ -237,38 +237,6 @@ public class JSONStringerTest { */ @Test public void complexObjectString() { - String expectedStr = - "{"+ - "\"trueValue\":true,"+ - "\"falseValue\":false,"+ - "\"nullValue\":null,"+ - "\"stringValue\":\"hello world!\","+ - "\"object2\":{"+ - "\"k1\":\"v1\","+ - "\"k2\":\"v2\","+ - "\"k3\":\"v3\","+ - "\"array1\":["+ - "1,"+ - "2,"+ - "{"+ - "\"k4\":\"v4\","+ - "\"k5\":\"v5\","+ - "\"k6\":\"v6\","+ - "\"array2\":["+ - "5,"+ - "6,"+ - "7,"+ - "8"+ - "]"+ - "},"+ - "3,"+ - "4"+ - "]"+ - "},"+ - "\"complexStringValue\":\"h\be\tllo w\u1234orld!\","+ - "\"intValue\":42,"+ - "\"doubleValue\":-23.45e67"+ - "}"; JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object(); jsonStringer.key("trueValue").value(true); @@ -303,8 +271,34 @@ public class JSONStringerTest { jsonStringer.endObject(); String str = jsonStringer.toString(); JSONObject jsonObject = new JSONObject(str); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); + + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); + assertTrue("expected 4 object2 items", ((Map)(JsonPath.read(doc, "$.object2"))).size() == 4); + assertTrue("expected 5 array1 items", ((List)(JsonPath.read(doc, "$.object2.array1"))).size() == 5); + assertTrue("expected 4 array[2] items", ((Map)(JsonPath.read(doc, "$.object2.array1[2]"))).size() == 4); + assertTrue("expected 4 array1[2].array2 items", ((List)(JsonPath.read(doc, "$.object2.array1[2].array2"))).size() == 4); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueValue"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseValue"))); + assertTrue("expected null", null == JsonPath.read(doc, "$.nullValue")); + assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.stringValue"))); + assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.intValue"))); + assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(JsonPath.read(doc, "$.doubleValue"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, "$.complexStringValue"))); + assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$.object2.k1"))); + assertTrue("expected v2", "v2".equals(JsonPath.read(doc, "$.object2.k2"))); + assertTrue("expected v3", "v3".equals(JsonPath.read(doc, "$.object2.k3"))); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.object2.array1[0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.object2.array1[1]"))); + assertTrue("expected v4", "v4".equals(JsonPath.read(doc, "$.object2.array1[2].k4"))); + assertTrue("expected v5", "v5".equals(JsonPath.read(doc, "$.object2.array1[2].k5"))); + assertTrue("expected v6", "v6".equals(JsonPath.read(doc, "$.object2.array1[2].k6"))); + assertTrue("expected 5", Integer.valueOf(5).equals(JsonPath.read(doc, "$.object2.array1[2].array2[0]"))); + assertTrue("expected 6", Integer.valueOf(6).equals(JsonPath.read(doc, "$.object2.array1[2].array2[1]"))); + assertTrue("expected 7", Integer.valueOf(7).equals(JsonPath.read(doc, "$.object2.array1[2].array2[2]"))); + assertTrue("expected 8", Integer.valueOf(8).equals(JsonPath.read(doc, "$.object2.array1[2].array2[3]"))); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.object2.array1[3]"))); + assertTrue("expected 4", Integer.valueOf(4).equals(JsonPath.read(doc, "$.object2.array1[4]"))); } } From abe421e6bbf3fa48833e885f408bdb550b0605d0 Mon Sep 17 00:00:00 2001 From: stleary Date: Mon, 28 Dec 2015 12:07:44 -0600 Subject: [PATCH 177/451] clean up code --- CookieListTest.java | 95 ++++------ EnumTest.java | 15 +- JSONArrayTest.java | 54 ++---- JSONObjectTest.java | 428 +++++++++++++----------------------------- JSONStringerTest.java | 3 + 5 files changed, 196 insertions(+), 399 deletions(-) diff --git a/CookieListTest.java b/CookieListTest.java index 98ede86..5b298e7 100644 --- a/CookieListTest.java +++ b/CookieListTest.java @@ -75,12 +75,10 @@ public class CookieListTest { public void simpleCookieList() { String cookieStr = "SID=31d4d96e407aad42"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - Object doc = Configuration.defaultConfiguration().jsonProvider(). - parse(jsonObject.toString()); - assertTrue("Expected 1 top level item", - ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 31d4d96e407aad42", - "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID"))); + // validate JSON content + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("Expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID"))); } /** @@ -90,12 +88,10 @@ public class CookieListTest { public void simpleCookieListWithDelimiter() { String cookieStr = "SID=31d4d96e407aad42;"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - Object doc = Configuration.defaultConfiguration().jsonProvider(). - parse(jsonObject.toString()); - assertTrue("Expected 1 top level item", - ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 31d4d96e407aad42", - "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID"))); + // validate JSON content + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("Expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID"))); } /** @@ -112,22 +108,15 @@ public class CookieListTest { "name5=myCookieValue5;"+ " name6=myCookieValue6;"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - Object doc = Configuration.defaultConfiguration().jsonProvider(). - parse(jsonObject.toString()); - assertTrue("Expected 6 top level items", - ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected myCookieValue1", - "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); - assertTrue("expected myCookieValue2", - "myCookieValue2".equals(JsonPath.read(doc, "$.name2"))); - assertTrue("expected myCookieValue3", - "myCookieValue3".equals(JsonPath.read(doc, "$.name3"))); - assertTrue("expected myCookieValue4", - "myCookieValue4".equals(JsonPath.read(doc, "$.name4"))); - assertTrue("expected myCookieValue5", - "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); - assertTrue("expected myCookieValue6", - "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); + // validate JSON content + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected myCookieValue1", "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); + assertTrue("expected myCookieValue2", "myCookieValue2".equals(JsonPath.read(doc, "$.name2"))); + assertTrue("expected myCookieValue3", "myCookieValue3".equals(JsonPath.read(doc, "$.name3"))); + assertTrue("expected myCookieValue4", "myCookieValue4".equals(JsonPath.read(doc, "$.name4"))); + assertTrue("expected myCookieValue5", "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); + assertTrue("expected myCookieValue6", "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); } /** @@ -154,22 +143,15 @@ public class CookieListTest { "name5=myCookieValue5;"+ " name6=myCookieValue6;"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - Object doc = Configuration.defaultConfiguration().jsonProvider(). - parse(jsonObject.toString()); - assertTrue("Expected 6 top level items", - ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected myCookieValue1", - "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); - assertTrue("expected myCookieValue2", - "myCookieValue2".equals(JsonPath.read(doc, "$.name2"))); - assertTrue("expected myCookieValue3", - "myCookieValue3".equals(JsonPath.read(doc, "$.name3"))); - assertTrue("expected myCookieValue4", - "myCookieValue4".equals(JsonPath.read(doc, "$.name4"))); - assertTrue("expected myCookieValue5", - "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); - assertTrue("expected myCookieValue6", - "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); + // validate JSON content + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected myCookieValue1", "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); + assertTrue("expected myCookieValue2", "myCookieValue2".equals(JsonPath.read(doc, "$.name2"))); + assertTrue("expected myCookieValue3", "myCookieValue3".equals(JsonPath.read(doc, "$.name3"))); + assertTrue("expected myCookieValue4", "myCookieValue4".equals(JsonPath.read(doc, "$.name4"))); + assertTrue("expected myCookieValue5", "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); + assertTrue("expected myCookieValue6", "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); } /** @@ -186,21 +168,14 @@ public class CookieListTest { "name5=myCookieValue5;"+ " name6=myCookieValue6;"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - Object doc = Configuration.defaultConfiguration().jsonProvider(). - parse(jsonObject.toString()); - assertTrue("Expected 6 top level items", - ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected myCookieValue1", - "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); - assertTrue("expected my Cookie Value 2", - "my Cookie Value 2".equals(JsonPath.read(doc, "$.name2"))); - assertTrue("expected my+Cookie&Value;3=", - "my+Cookie&Value;3=".equals(JsonPath.read(doc, "$.name3"))); - assertTrue("expected my%CookieValue4", - "my%CookieValue4".equals(JsonPath.read(doc, "$.name4"))); - assertTrue("expected my%CookieValue5", - "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); - assertTrue("expected myCookieValue6", - "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); + // validate JSON content + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected myCookieValue1", "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); + assertTrue("expected my Cookie Value 2", "my Cookie Value 2".equals(JsonPath.read(doc, "$.name2"))); + assertTrue("expected my+Cookie&Value;3=", "my+Cookie&Value;3=".equals(JsonPath.read(doc, "$.name3"))); + assertTrue("expected my%CookieValue4", "my%CookieValue4".equals(JsonPath.read(doc, "$.name4"))); + assertTrue("expected my%CookieValue5", "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); + assertTrue("expected myCookieValue6", "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); } } diff --git a/EnumTest.java b/EnumTest.java index 2d2ebb9..a591dba 100644 --- a/EnumTest.java +++ b/EnumTest.java @@ -35,8 +35,7 @@ public class EnumTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonObject.toString()); - assertTrue("expecting 2 items in top level object", - ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expecting 2 items in top level object", ((Map)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expecting val 2", "val 2".equals(JsonPath.read(doc, "$.value"))); assertTrue("expecting 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal"))); @@ -50,14 +49,10 @@ public class EnumTest { jsonObject = new JSONObject(myEnumClass); // validate JSON content - doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expecting 2 items in top level object", - ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expecting 2 items in myEnumField object", - ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); - assertTrue("expecting 0 items in myEnum object", - ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expecting 2 items in top level object", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expecting 2 items in myEnumField object", ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); + assertTrue("expecting 0 items in myEnum object", ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); assertTrue("expecting 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal"))); assertTrue("expecting val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value"))); } diff --git a/JSONArrayTest.java b/JSONArrayTest.java index c042acd..455d680 100644 --- a/JSONArrayTest.java +++ b/JSONArrayTest.java @@ -314,10 +314,8 @@ public class JSONArrayTest { /** * Don't need to remake the JSONArray to perform the parsing */ - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse("["+joinStr+"]"); - List docList = JsonPath.read(doc, "$"); - assertTrue("expected 13 items in top level object", docList.size() == 13); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse("["+joinStr+"]"); + assertTrue("expected 13 items in top level object", ((List)(JsonPath.read(doc, "$"))).size() == 13); assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); assertTrue("expected \"true\"", "true".equals(JsonPath.read(doc, "$[2]"))); @@ -327,11 +325,9 @@ public class JSONArrayTest { assertTrue("expected \"23.45\"", "23.45".equals(JsonPath.read(doc, "$[6]"))); assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$[7]"))); assertTrue("expected \"43\"", "43".equals(JsonPath.read(doc, "$[8]"))); - docList = JsonPath.read(doc, "$[9]"); - assertTrue("expected 1 array item", docList.size() == 1); + assertTrue("expected 1 item in [9]", ((List)(JsonPath.read(doc, "$[9]"))).size() == 1); assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[9][0]"))); - Map docMap = JsonPath.read(doc, "$[10]"); - assertTrue("expected 4 object items", docMap.size() == 4); + assertTrue("expected 4 items in [10]", ((Map)(JsonPath.read(doc, "$[10]"))).size() == 4); assertTrue("expected value1", "value1".equals(JsonPath.read(doc, "$[10].key1"))); assertTrue("expected value2", "value2".equals(JsonPath.read(doc, "$[10].key2"))); assertTrue("expected value3", "value3".equals(JsonPath.read(doc, "$[10].key3"))); @@ -463,30 +459,24 @@ public class JSONArrayTest { jsonArray.put(collection); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - List docList = JsonPath.read(doc, "$"); - assertTrue("expected 10 items in top level object", docList.size() == 10); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 10 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 10); assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); - docList = JsonPath.read(doc, "$[2]"); - assertTrue("expected 2 items in array", docList.size() == 2); + assertTrue("expected 2 items in [2]", ((List)(JsonPath.read(doc, "$[2]"))).size() == 2); assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[2][0]"))); assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[2][1]"))); assertTrue("expected 2.5", Double.valueOf(2.5).equals(JsonPath.read(doc, "$[3]"))); assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[4]"))); assertTrue("expected 45", Integer.valueOf(45).equals(JsonPath.read(doc, "$[5]"))); assertTrue("expected objectPut", "objectPut".equals(JsonPath.read(doc, "$[6]"))); - Map docMap = JsonPath.read(doc, "$[7]"); - assertTrue("expected 3 items in object", docMap.size() == 3); + assertTrue("expected 3 items in [7]", ((Map)(JsonPath.read(doc, "$[7]"))).size() == 3); assertTrue("expected val10", "val10".equals(JsonPath.read(doc, "$[7].key10"))); assertTrue("expected val20", "val20".equals(JsonPath.read(doc, "$[7].key20"))); assertTrue("expected val30", "val30".equals(JsonPath.read(doc, "$[7].key30"))); - docMap = JsonPath.read(doc, "$[8]"); - assertTrue("expected 1 item in object", docMap.size() == 1); + assertTrue("expected 1 item in [8]", ((Map)(JsonPath.read(doc, "$[8]"))).size() == 1); assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$[8].k1"))); - docList = JsonPath.read(doc, "$[9]"); - assertTrue("expected 2 items in array", docList.size() == 2); + assertTrue("expected 2 items in [9]", ((List)(JsonPath.read(doc, "$[9]"))).size() == 2); assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[9][0]"))); assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[9][1]"))); } @@ -546,14 +536,11 @@ public class JSONArrayTest { } catch(Exception ignored) {} // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - List docList = JsonPath.read(doc, "$"); - assertTrue("expected 11 items in top level object", docList.size() == 11); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 11 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 11); assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); - docList = JsonPath.read(doc, "$[2]"); - assertTrue("expected 2 items in array", docList.size() == 2); + assertTrue("expected 2 items in [2]", ((List)(JsonPath.read(doc, "$[2]"))).size() == 2); assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[2][0]"))); assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[2][1]"))); assertTrue("expected 2.5", Double.valueOf(2.5).equals(JsonPath.read(doc, "$[3]"))); @@ -561,17 +548,14 @@ public class JSONArrayTest { assertTrue("expected 45", Integer.valueOf(45).equals(JsonPath.read(doc, "$[5]"))); assertTrue("expected objectPut", "objectPut".equals(JsonPath.read(doc, "$[6]"))); assertTrue("expected null", null == JsonPath.read(doc, "$[7]")); - Map docMap = JsonPath.read(doc, "$[8]"); - assertTrue("expected 3 items in object", docMap.size() == 3); + assertTrue("expected 3 items in [8]", ((Map)(JsonPath.read(doc, "$[8]"))).size() == 3); assertTrue("expected val10", "val10".equals(JsonPath.read(doc, "$[8].key10"))); assertTrue("expected val20", "val20".equals(JsonPath.read(doc, "$[8].key20"))); assertTrue("expected val30", "val30".equals(JsonPath.read(doc, "$[8].key30"))); - docList = JsonPath.read(doc, "$[9]"); - assertTrue("expected 2 items in array", docList.size() == 2); + assertTrue("expected 2 items in [9]", ((List)(JsonPath.read(doc, "$[9]"))).size() == 2); assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[9][0]"))); assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[9][1]"))); - docMap = JsonPath.read(doc, "$[10]"); - assertTrue("expected 1 item in object", docMap.size() == 1); + assertTrue("expected 1 item in [10]", ((Map)(JsonPath.read(doc, "$[10]"))).size() == 1); assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$[10].k1"))); } @@ -651,10 +635,8 @@ public class JSONArrayTest { JSONArray jsonArray = new JSONArray(myObject); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - List docList = JsonPath.read(doc, "$"); - assertTrue("expected 7 items in top level object", docList.size() == 7); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 7 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 7); assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); diff --git a/JSONObjectTest.java b/JSONObjectTest.java index d420e22..4648dce 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -110,20 +110,12 @@ public class JSONObjectTest { // validate JSON JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObjectByName.toString()); - Map> docMap = JsonPath.read(doc, "$"); - assertTrue("expected 4 items", docMap.size() == 4); - assertTrue("expected \"falseKey\":false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"nullKey\":null", - null == JsonPath.read(doc, "$.nullKey")); - assertTrue("expected \"stringKey\":\"hello world!\"", - "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue( - "expected \"doubleKey\":-23.45e67", - Double.valueOf("-23.45e67").equals( - JsonPath.read(doc, "$.doubleKey"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"nullKey\":null", null == JsonPath.read(doc, "$.nullKey")); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); } /** @@ -155,23 +147,13 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(map); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 6 items", docMap.size() == 6); - assertTrue("expected \"trueKey\":true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected \"falseKey\":false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", - "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.escapeStringKey"))); - assertTrue( - "expected \"doubleKey\":-23.45e67", - Double.valueOf("-23.45e67").equals( - JsonPath.read(doc, "$.doubleKey"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); } /** @@ -305,14 +287,10 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(jsonMap); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 2 items", docMap.size() == 2); - assertTrue("expected \"key2\":java.lang.Exception", - "java.lang.Exception".equals(JsonPath.read(doc, "$.key2"))); - docMap = JsonPath.read(doc, "$.key1"); - assertTrue("expected 0 items", docMap.size() == 0); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(JsonPath.read(doc, "$.key2"))); + assertTrue("expected 0 key1 items", ((Map)(JsonPath.read(doc, "$.key1"))).size() == 0); } /** @@ -332,25 +310,14 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(map); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 6 items", docMap.size() == 6); - assertTrue("expected \"trueKey\":true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected \"falseKey\":false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", - "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.escapeStringKey"))); - assertTrue("expected \"intKey\":42", - Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); - assertTrue( - "expected \"doubleKey\":-23.45e67", - Double.valueOf("-23.45e67").equals( - JsonPath.read(doc, "$.doubleKey"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); + assertTrue("expected \"intKey\":42", Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); } /** @@ -386,35 +353,19 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(myBean); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 8 items", docMap.size() == 8); - assertTrue("expected \"trueKey\":true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected \"falseKey\":false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", - "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.escapeStringKey"))); - assertTrue("expected \"intKey\":42", - Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); - assertTrue("expected \"doubleKey\":-23.45e7", Double - .valueOf("-23.45e7").equals(JsonPath.read(doc, "$.doubleKey"))); - assertTrue( - "expected \"stringReaderKey\":{}", - ((Map) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected hello world!","hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); + assertTrue("expected 42", Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); + assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(JsonPath.read(doc, "$.doubleKey"))); + assertTrue("expected 0 items in stringReaderKey", ((Map) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); // sorry, mockito artifact - List docList = JsonPath.read(doc, "$.callbacks"); - assertTrue("expected 2 items", docList.size() == 2); - assertTrue("expected \"handler\":{}", - ((Map) (JsonPath.read(doc, - "$.callbacks[0].handler"))).size() == 0); - assertTrue("expected empty object", - ((Map) (JsonPath.read(doc, "$.callbacks[1]"))) - .size() == 0); + assertTrue("expected 2 callbacks items", ((List)(JsonPath.read(doc, "$.callbacks"))).size() == 2); + assertTrue("expected 0 handler items", ((Map)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0); + assertTrue("expected 0 callbacks[1] items", ((Map)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0); } /** @@ -431,14 +382,10 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(jsonObjectTest, keys); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 2 items", docMap.size() == 2); - assertTrue("expected \"publicString\":\"abc\"", - "abc".equals(JsonPath.read(doc, "$.publicString"))); - assertTrue("expected \"publicInt\":42", - Integer.valueOf(42).equals(JsonPath.read(doc, "$.publicInt"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected \"publicString\":\"abc\"", "abc".equals(JsonPath.read(doc, "$.publicString"))); + assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.publicInt"))); } /** @@ -452,22 +399,14 @@ public class JSONObjectTest { Locale.getDefault()); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 2 items in top level map", docMap.size() == 2); - docMap = JsonPath.read(doc, "$.greetings"); - assertTrue("expected 2 items in greetings map", docMap.size() == 2); - assertTrue("expected \"hello\":\"Hello, \"", - "Hello, ".equals(JsonPath.read(doc, "$.greetings.hello"))); - assertTrue("expected \"world\":\"World!\"", - "World!".equals(JsonPath.read(doc, "$.greetings.world"))); - docMap = JsonPath.read(doc, "$.farewells"); - assertTrue("expected 2 items in farewells map", docMap.size() == 2); - assertTrue("expected \"later\":\"Later, \"", - "Later, ".equals(JsonPath.read(doc, "$.farewells.later"))); - assertTrue("expected \"world\":\"World!\"", - "Alligator!".equals(JsonPath.read(doc, "$.farewells.gator"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected 2 greetings items", ((Map)(JsonPath.read(doc, "$.greetings"))).size() == 2); + assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(JsonPath.read(doc, "$.greetings.hello"))); + assertTrue("expected \"world\":\"World!\"", "World!".equals(JsonPath.read(doc, "$.greetings.world"))); + assertTrue("expected 2 farewells items", ((Map)(JsonPath.read(doc, "$.farewells"))).size() == 2); + assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(JsonPath.read(doc, "$.farewells.later"))); + assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(JsonPath.read(doc, "$.farewells.gator"))); } /** @@ -486,27 +425,15 @@ public class JSONObjectTest { jsonObject.accumulate("myArray", -23.45e7); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 1 item in top level object", docMap.size() == 1); - List docList = JsonPath.read(doc, "$.myArray"); - assertTrue("expected 6 items in myArray", docList.size() == 6); - assertTrue("expected true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); - assertTrue("expected false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); - assertTrue("expected hello world!", - "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); - assertTrue("expected h\be\tllo w\u1234orld!", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.myArray[3]"))); - assertTrue("expected 42", - Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); - assertTrue( - "expected -23.45e7", - Double.valueOf(-23.45e7).equals( - JsonPath.read(doc, "$.myArray[5]"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); + assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.myArray[3]"))); + assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); + assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(JsonPath.read(doc, "$.myArray[5]"))); } /** @@ -524,27 +451,15 @@ public class JSONObjectTest { jsonObject.append("myArray", -23.45e7); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 1 item in top level object", docMap.size() == 1); - List docList = JsonPath.read(doc, "$.myArray"); - assertTrue("expected 6 items in myArray", docList.size() == 6); - assertTrue("expected true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); - assertTrue("expected false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); - assertTrue("expected hello world!", - "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); - assertTrue("expected h\be\tllo w\u1234orld!", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.myArray[3]"))); - assertTrue("expected 42", - Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); - assertTrue( - "expected -23.45e7", - Double.valueOf(-23.45e7).equals( - JsonPath.read(doc, "$.myArray[5]"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); + assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.myArray[3]"))); + assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); + assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(JsonPath.read(doc, "$.myArray[5]"))); } /** @@ -1215,19 +1130,11 @@ public class JSONObjectTest { JSONArray jsonArray = jsonObject.names(); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - List docList = JsonPath.read(doc, "$"); - assertTrue("expected 3 items in array", docList.size() == 3); - assertTrue( - "expected to find trueKey", - ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); - assertTrue( - "expected to find falseKey", - ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); - assertTrue( - "expected to find stringKey", - ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected to find trueKey", ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); + assertTrue("expected to find falseKey", ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); + assertTrue("expected to find stringKey", ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); } /** @@ -1253,18 +1160,12 @@ public class JSONObjectTest { jsonObject.increment("keyFloat"); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 4 items in object", docMap.size() == 4); - assertTrue("expected to find keyInt:3", - Integer.valueOf(3).equals(JsonPath.read(doc, "$.keyInt"))); - assertTrue( - "expected to find keyLong:9999999993", - Long.valueOf(9999999993L).equals( - JsonPath.read(doc, "$.keyLong"))); - assertTrue("expected to find keyDouble:3.1", Double.valueOf(3.1) - .equals(JsonPath.read(doc, "$.keyDouble"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.keyInt"))); + assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(JsonPath.read(doc, "$.keyLong"))); + assertTrue("expected 3.1", Double.valueOf(3.1).equals(JsonPath.read(doc, "$.keyDouble"))); + /** * Should work the same way on any platform! @see https://docs.oracle * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is the @@ -1288,10 +1189,7 @@ public class JSONObjectTest { * missing bits would not fit into the 32 bit float, i.e. the * information needed simply is not there! */ - assertTrue( - "expected to find keyFloat:3.0999999046325684", - Double.valueOf(3.0999999046325684).equals( - JsonPath.read(doc, "$.keyFloat"))); + assertTrue("expected 3.0999999046325684", Double.valueOf(3.0999999046325684).equals(JsonPath.read(doc, "$.keyFloat"))); /** * float f = 3.1f; double df = (double) f; double d = 3.1d; @@ -1399,32 +1297,19 @@ public class JSONObjectTest { jsonObject.put("objectKey", myMap); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 4 items in object", docMap.size() == 4); - assertTrue("expected to find trueKey:true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected to find falseKey:false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - List docList = JsonPath.read(doc, "$.arrayKey"); - assertTrue("expected 3 items in array", docList.size() == 3); - assertTrue("expected to find 0", - Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); - assertTrue("expected to find 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); - assertTrue("expected to find 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); - docMap = JsonPath.read(doc, "$.objectKey"); - assertTrue("expected 4 items in object", docMap.size() == 4); - assertTrue("expected to find myKey1:myVal1", - "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); - assertTrue("expected to find myKey2:myVal2", - "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); - assertTrue("expected to find myKey3:myVal3", - "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); - assertTrue("expected to find myKey4:myVal4", - "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); + assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); + assertTrue("expected myVal1", "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); + assertTrue("expected myVal2", "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); + assertTrue("expected myVal3", "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); + assertTrue("expected myVal4", "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); jsonObject.remove("trueKey"); JSONObject expectedJsonObject = new JSONObject(expectedStr); @@ -1475,32 +1360,19 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(str); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 4 items in object", docMap.size() == 4); - assertTrue("expected to find \"trueKey\":true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected to find \"falseKey\":false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - List docList = JsonPath.read(doc, "$.arrayKey"); - assertTrue("expected 3 array items", docList.size() == 3); - assertTrue("expected array value 0", - Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); - assertTrue("expected array value 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); - assertTrue("expected array value 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); - docMap = JsonPath.read(doc, "$.objectKey"); - assertTrue("expected 4 items in objectKey object", docMap.size() == 4); - assertTrue("expected objectKey myKey1:myVal1", - "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); - assertTrue("expected objectKey myKey2:myVal2", - "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); - assertTrue("expected objectKey myKey3:myVal3", - "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); - assertTrue("expected objectKey myKey4:myVal4", - "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); + assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); + assertTrue("expected myVal1", "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); + assertTrue("expected myVal2", "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); + assertTrue("expected myVal3", "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); + assertTrue("expected myVal4", "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); } /** @@ -1518,14 +1390,10 @@ public class JSONObjectTest { jsonObject.put("key", map); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 1 item in object", docMap.size() == 1); - docMap = JsonPath.read(doc, "$.key"); - assertTrue("expected 1 item in key object", docMap.size() == 1); - assertTrue("expected abc:def", - "def".equals(JsonPath.read(doc, "$.key.abc"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 1 key item", ((Map)(JsonPath.read(doc, "$.key"))).size() == 1); + assertTrue("expected def", "def".equals(JsonPath.read(doc, "$.key.abc"))); } /** @@ -1544,12 +1412,9 @@ public class JSONObjectTest { jsonObject.put("key", collection); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 1 item in object", docMap.size() == 1); - List docList = JsonPath.read(doc, "$.key"); - assertTrue("expected 1 item in key object", docList.size() == 1); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 1 key item", ((List)(JsonPath.read(doc, "$.key"))).size() == 1); assertTrue("expected abc", "abc".equals(JsonPath.read(doc, "$.key[0]"))); } @@ -1613,12 +1478,9 @@ public class JSONObjectTest { // this is the test, it should not throw an exception String str = JSONObject.valueToString(myMap); // confirm result, just in case - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(str); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 1 item in object", docMap.size() == 1); - assertTrue("expected myValue", - "myValue".equals(JsonPath.read(doc, "$.1"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1"))); } /** @@ -1667,44 +1529,29 @@ public class JSONObjectTest { JSONArray jsonArray = (JSONArray) (JSONObject.wrap(collection)); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - List docList = JsonPath.read(doc, "$"); - assertTrue("expected 3 items in array", docList.size() == 3); - assertTrue("expected 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", - Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); // wrap Array returns JSONArray Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - docList = JsonPath.read(doc, "$"); - assertTrue("expected 3 items in array", docList.size() == 3); - assertTrue("expected 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", - Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider() - .parse(integerArrayJsonArray.toString()); - docList = JsonPath.read(doc, "$"); - assertTrue("expected 3 items in array", docList.size() == 3); - assertTrue("expected 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", - Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); // wrap map returns JSONObject Map map = new HashMap(); @@ -1714,16 +1561,11 @@ public class JSONObjectTest { JSONObject mapJsonObject = (JSONObject) (JSONObject.wrap(map)); // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider() - .parse(mapJsonObject.toString()); - Map docMap = JsonPath.read(doc, "$"); - assertTrue("expected 3 items in object", docMap.size() == 3); - assertTrue("expected key1:val1", - "val1".equals(JsonPath.read(doc, "$.key1"))); - assertTrue("expected key2:val2", - "val2".equals(JsonPath.read(doc, "$.key2"))); - assertTrue("expected key3:val3", - "val3".equals(JsonPath.read(doc, "$.key3"))); + doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString()); + assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected val1", "val1".equals(JsonPath.read(doc, "$.key1"))); + assertTrue("expected val2", "val2".equals(JsonPath.read(doc, "$.key2"))); + assertTrue("expected val3", "val3".equals(JsonPath.read(doc, "$.key3"))); // TODO test wrap(package) } diff --git a/JSONStringerTest.java b/JSONStringerTest.java index 4e9a9db..c9419df 100644 --- a/JSONStringerTest.java +++ b/JSONStringerTest.java @@ -192,6 +192,7 @@ public class JSONStringerTest { String str = jsonStringer.toString(); JSONObject jsonObject = new JSONObject(str); + // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 7 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 7); assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueValue"))); @@ -221,6 +222,7 @@ public class JSONStringerTest { String str = jsonStringer.toString(); JSONArray jsonArray = new JSONArray(str); + // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 6 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 6); assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); @@ -272,6 +274,7 @@ public class JSONStringerTest { String str = jsonStringer.toString(); JSONObject jsonObject = new JSONObject(str); + // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); assertTrue("expected 4 object2 items", ((Map)(JsonPath.read(doc, "$.object2"))).size() == 4); From 472439546a5274a420eb30637bf785516156ef0a Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 28 Dec 2015 12:20:43 -0600 Subject: [PATCH 178/451] Update README.md --- README.md | 46 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 19d0354..296d27b 100644 --- a/README.md +++ b/README.md @@ -12,15 +12,51 @@ Run individual tests or JunitTestSuite using EclEmma Coverage, or **You will need the following libraries for testing:**
Test harness: http://junit.org
-* hamcrest-core-1.3.jar (for Junit)
+* asm-1.0.2.jar
+* commons-io-2.1.jar
+* commons-lang-2.6.jar
+* hamcrest-core-1.3.jar
+* json-path-2.1.0.jar
+* json-smart-2.1.1.jar
* junit-4.12.jar
- -Mockery: https://github.com/mockito/mockito
* mockito-all-1.9.5.jar
+* slf4j-api-1.7.12.jar
+* slf-simple-1.7.12.jar
+* JSON-java.jar
+ +**To build from the command line using gradle:** +build.gradle
+'''' +# In this example, both the JSON-java jar and the test code is built
+# from the same build file, in the test code directory. +apply plugin: 'java' +jar.baseName = 'JSON-java' -Coverage: http://www.eclemma.org/ (just install the latest in Eclipse)
+sourceSets { + main { + java { + srcDir '../JSON-java/src/org/json' + } + } + test { + java { + srcDir 'src/org/json/junit' + } + } +} -JSON-Java.jar (make this jar of the files to be tested yourself)
+repositories { + mavenCentral() +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.+' + testCompile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.1.0' + testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' +} +'''' + +To measure coverage: http://www.eclemma.org/ (just install the latest in Eclipse)
Conventions
Test filenames should consist of the name of the module being tested, with the suffix "Test". From 633ab108e7708f10c47d86f8b2cfdd5b193ab061 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 28 Dec 2015 12:22:29 -0600 Subject: [PATCH 179/451] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 296d27b..d7672ca 100644 --- a/README.md +++ b/README.md @@ -26,9 +26,9 @@ Test harness: http://junit.org
**To build from the command line using gradle:** build.gradle
-'''' -# In this example, both the JSON-java jar and the test code is built
-# from the same build file, in the test code directory. +```` +\# In this example, both the JSON-java jar and the test code is built
+\# from the same build file, in the test code directory. apply plugin: 'java' jar.baseName = 'JSON-java' @@ -54,7 +54,7 @@ dependencies { testCompile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.1.0' testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' } -'''' +```` To measure coverage: http://www.eclemma.org/ (just install the latest in Eclipse)
From 54cd97ded114f8523f198f85a3ce8b6e60f990ba Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 28 Dec 2015 12:24:46 -0600 Subject: [PATCH 180/451] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d7672ca..aff849f 100644 --- a/README.md +++ b/README.md @@ -25,10 +25,11 @@ Test harness: http://junit.org
* JSON-java.jar
**To build from the command line using gradle:** -build.gradle
```` -\# In this example, both the JSON-java jar and the test code is built
-\# from the same build file, in the test code directory. +build.gradle +# In this example, both the JSON-java jar and the test code is created
+# from the same build file, in the test code directory. 3rd party jars are +# obtained from the maven repository. apply plugin: 'java' jar.baseName = 'JSON-java' From 91fcd6092f92873fc45a2031a444a30b59b7e5af Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 28 Dec 2015 12:25:11 -0600 Subject: [PATCH 181/451] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index aff849f..ac87e41 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ Eclipse is the recommended development environment.
Run individual tests or JunitTestSuite using EclEmma Coverage, or execute the **TestRunner** application directly.
**You will need the following libraries for testing:**
-Test harness: http://junit.org
* asm-1.0.2.jar
* commons-io-2.1.jar
* commons-lang-2.6.jar
From 95cf86688de41c611f0a8f5a245899ff8139559c Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 28 Dec 2015 12:25:40 -0600 Subject: [PATCH 182/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ac87e41..eee0a71 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Run individual tests or JunitTestSuite using EclEmma Coverage, or **To build from the command line using gradle:** ```` build.gradle -# In this example, both the JSON-java jar and the test code is created
+# In this example, both the JSON-java jar and the test code is created # from the same build file, in the test code directory. 3rd party jars are # obtained from the maven repository. apply plugin: 'java' From 7f83a5171837818856e21b610dc192549eb5d306 Mon Sep 17 00:00:00 2001 From: stleary Date: Tue, 29 Dec 2015 17:56:43 -0600 Subject: [PATCH 183/451] refactor test classes to their own modules --- JSONObjectTest.java | 50 +++++--------------------------------------- MyBean.java | 16 ++++++++++++++ MyBigNumberBean.java | 11 ++++++++++ MyJsonString.java | 14 +++++++++++++ MyPublicClass.java | 9 ++++++++ 5 files changed, 55 insertions(+), 45 deletions(-) create mode 100644 MyBean.java create mode 100644 MyBigNumberBean.java create mode 100644 MyJsonString.java create mode 100644 MyPublicClass.java diff --git a/JSONObjectTest.java b/JSONObjectTest.java index d420e22..80bef48 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -16,57 +16,17 @@ import org.json.CDL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.json.JSONString; import org.json.XML; import org.junit.Test; import com.jayway.jsonpath.*; -/** - * Used in testing when a JSONString is needed - */ -class MyJsonString implements JSONString { - - @Override - public String toJSONString() { - return "my string"; - } -} - -/** - * Used in testing when Bean behavior is needed - */ -interface MyBean { - public Integer getIntKey(); - public Double getDoubleKey(); - public String getStringKey(); - public String getEscapeStringKey(); - public Boolean isTrueKey(); - public Boolean isFalseKey(); - public StringReader getStringReaderKey(); -}; - -/** - * Used in testing when a Bean containing big numbers is needed - */ -interface MyBigNumberBean { - public BigInteger getBigInteger(); - public BigDecimal getBigDecimal(); -} - /** * JSONObject, along with JSONArray, are the central classes of the reference app. * All of the other classes interact with them, and JSON functionality would * otherwise be impossible. */ public class JSONObjectTest { - /** - * Need a class with some public data members for testing, so - * JSONObjectTest itself will be used for this purpose. - * TODO: Why not use MyBigNumberBean or MyBean? - */ - public Integer publicInt = 42; - public String publicString = "abc"; /** * JSONObject built from a bean, but only using a null value. @@ -427,8 +387,8 @@ public class JSONObjectTest { public void jsonObjectByObjectAndNames() { String[] keys = {"publicString", "publicInt"}; // just need a class that has public data members - JSONObjectTest jsonObjectTest = new JSONObjectTest(); - JSONObject jsonObject = new JSONObject(jsonObjectTest, keys); + MyPublicClass myPublicClass = new MyPublicClass(); + JSONObject jsonObject = new JSONObject(myPublicClass, keys); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider() @@ -1168,10 +1128,10 @@ public class JSONObjectTest { /** * A bean is also an object. But in order to test the static * method getNames(), this particular bean needs some public - * data members, which have been added to the class. + * data members. */ - JSONObjectTest jsonObjectTest = new JSONObjectTest(); - names = JSONObject.getNames(jsonObjectTest); + MyPublicClass myPublicClass = new MyPublicClass(); + names = JSONObject.getNames(myPublicClass); // validate JSON jsonArray = new JSONArray(names); diff --git a/MyBean.java b/MyBean.java new file mode 100644 index 0000000..53d150a --- /dev/null +++ b/MyBean.java @@ -0,0 +1,16 @@ +package org.json.junit; + +import java.io.*; + +/** + * Used in testing when Bean behavior is needed + */ +interface MyBean { + public Integer getIntKey(); + public Double getDoubleKey(); + public String getStringKey(); + public String getEscapeStringKey(); + public Boolean isTrueKey(); + public Boolean isFalseKey(); + public StringReader getStringReaderKey(); +} \ No newline at end of file diff --git a/MyBigNumberBean.java b/MyBigNumberBean.java new file mode 100644 index 0000000..0ca1870 --- /dev/null +++ b/MyBigNumberBean.java @@ -0,0 +1,11 @@ +package org.json.junit; + +import java.math.*; + +/** + * Used in testing when a Bean containing big numbers is needed + */ +interface MyBigNumberBean { + public BigInteger getBigInteger(); + public BigDecimal getBigDecimal(); +} \ No newline at end of file diff --git a/MyJsonString.java b/MyJsonString.java new file mode 100644 index 0000000..4e63693 --- /dev/null +++ b/MyJsonString.java @@ -0,0 +1,14 @@ +package org.json.junit; + +import org.json.*; + +/** + * Used in testing when a JSONString is needed + */ +class MyJsonString implements JSONString { + + @Override + public String toJSONString() { + return "my string"; + } +} \ No newline at end of file diff --git a/MyPublicClass.java b/MyPublicClass.java new file mode 100644 index 0000000..1f55e3e --- /dev/null +++ b/MyPublicClass.java @@ -0,0 +1,9 @@ +package org.json.junit; + +/** + * Need a class with some public data members for testing + */ +public class MyPublicClass { + public Integer publicInt = 42; + public String publicString = "abc"; +} From 0990f340dbf42247f8148a662c5a2164190aaecd Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Wed, 30 Dec 2015 00:00:14 -0600 Subject: [PATCH 184/451] Update README.md --- README.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index eee0a71..d908b52 100644 --- a/README.md +++ b/README.md @@ -91,32 +91,37 @@ A unit test has the following stages: | Test file name | Coverage | Comments | | ------------- | ------------- | ---- | -| Total coverage | 88.9% | | | +| Total coverage | 90.6% | | | | | | | -| CDL.java | 98% | Reasonable test cases. | +| CDL.java | 98.8% | Reasonable test cases. | | Cookie.java | 98.9% | Reasonable test cases. | | CookieList.java |96.5% | Reasonable test cases. | | EnumTest.java | n/a | Just documenting how enums are handled. | | HTTP.java | 98.7%| Coverage > 90% | | HTTPTokener.java |93.2% | No test | -| JSONArray.java |95.9% | Coverage > 90% | +| JSONArray.java |95.9% | Reasonable test cases | | JSONException.java | 26.7% | No test | -| JSONML.java | 83.2%| In progress | -| JSONObject | 90.9% | Coverage > 90% | +| JSONML.java | 86.8%| In progress | +| JSONObject | 94.0% | Reasonable test cases | | JSONObject.Null | 87.5% | No test | | JSONString.java | | No test | | JSONStringer.java | 93.8%| Coverage > 90% | | JSONTokener.java | 72.1% | In progress | -| JSONWriter.java | 88.9% | No test | +| JSONWriter.java | 87.5% | No test | | Property.java | 94.8% | Coverage > 90% | -| XML.java | 85.1% | In progress | +| XML.java | 87.4% | In progress | | XMLTokener.java| 82.7%| No test | | Files used in test | | ------------- | +| MyBean.java | +| MyBigNumberBean.java | | MyEnum.java | | MyEnumClass.java | | MyEnumField.java | +| MyJsonString.java | +| MyPublicClass.java | +| PropertyTest.java | | JunitTestSuite.java | | StringsResourceBundle.java | | TestRunner.java | From fc318a765c02bb886f0fe12e1fce6f40e2dec751 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 30 Dec 2015 00:00:58 -0600 Subject: [PATCH 185/451] Fix some todos, clean up some tests, improve coverage --- CookieListTest.java | 5 +++ JSONObjectTest.java | 84 ++++++++++++++++++++++++++++----------------- 2 files changed, 58 insertions(+), 31 deletions(-) diff --git a/CookieListTest.java b/CookieListTest.java index 5b298e7..815c767 100644 --- a/CookieListTest.java +++ b/CookieListTest.java @@ -143,6 +143,11 @@ public class CookieListTest { "name5=myCookieValue5;"+ " name6=myCookieValue6;"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); + // exercise CookieList.toString() + String cookieListString = CookieList.toString(jsonObject); + // have to convert it back for validation + jsonObject = CookieList.toJSONObject(cookieListString); + // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); diff --git a/JSONObjectTest.java b/JSONObjectTest.java index 72a8f06..994c4b3 100644 --- a/JSONObjectTest.java +++ b/JSONObjectTest.java @@ -299,15 +299,6 @@ public class JSONObjectTest { when(myBean.isFalseKey()).thenReturn(false); when(myBean.getStringReaderKey()).thenReturn( new StringReader("") { - /** - * TODO: Need to understand why returning a string - * turns "this" into an empty JSONObject, - * but not overriding turns "this" into a string. - */ - @Override - public String toString(){ - return "Whatever"; - } }); JSONObject jsonObject = new JSONObject(myBean); @@ -349,11 +340,11 @@ public class JSONObjectTest { } /** - * Exercise the JSONObject from resource bundle functionality + * Exercise the JSONObject from resource bundle functionality. + * The test resource bundle is uncomplicated, but provides adequate test coverage. */ @Test public void jsonObjectByResourceBundle() { - // TODO: how to improve resource bundle testing? JSONObject jsonObject = new JSONObject("org.json.junit.StringsResourceBundle", Locale.getDefault()); @@ -374,7 +365,6 @@ public class JSONObjectTest { */ @Test public void jsonObjectAccumulate() { - // TODO: should include an unsupported object JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("myArray", true); @@ -383,6 +373,11 @@ public class JSONObjectTest { jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); jsonObject.accumulate("myArray", 42); jsonObject.accumulate("myArray", -23.45e7); + // include an unsupported object for coverage + try { + jsonObject.accumulate("myArray", Double.NaN); + assertTrue("Expected exception", false); + } catch (JSONException ignored) {} // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); @@ -401,7 +396,6 @@ public class JSONObjectTest { */ @Test public void jsonObjectAppend() { - // TODO: should include an unsupported object JSONObject jsonObject = new JSONObject(); jsonObject.append("myArray", true); jsonObject.append("myArray", false); @@ -409,6 +403,11 @@ public class JSONObjectTest { jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); jsonObject.append("myArray", 42); jsonObject.append("myArray", -23.45e7); + // include an unsupported object for coverage + try { + jsonObject.append("myArray", Double.NaN); + assertTrue("Expected exception", false); + } catch (JSONException ignored) {} // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); @@ -818,34 +817,49 @@ public class JSONObjectTest { /** * JSONObject put(String, Object) method stores and serializes * bigInt and bigDec correctly. Nothing needs to change. - * TODO: New methods - * get|optBigInteger|BigDecimal() should work like other supported - * objects. Uncomment the get/opt methods after JSONObject is updated. */ jsonObject = new JSONObject(); jsonObject.put("bigInt", bigInteger); assertTrue("jsonObject.put() handles bigInt correctly", jsonObject.get("bigInt").equals(bigInteger)); - // assertTrue("jsonObject.getBigInteger() handles bigInt correctly", - // jsonObject.getBigInteger("bigInt").equals(bigInteger)); - // assertTrue("jsonObject.optBigInteger() handles bigInt correctly", - // jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); + assertTrue("jsonObject.getBigInteger() handles bigInt correctly", + jsonObject.getBigInteger("bigInt").equals(bigInteger)); + assertTrue("jsonObject.optBigInteger() handles bigInt correctly", + jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); assertTrue("jsonObject serializes bigInt correctly", jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); jsonObject = new JSONObject(); jsonObject.put("bigDec", bigDecimal); assertTrue("jsonObject.put() handles bigDec correctly", jsonObject.get("bigDec").equals(bigDecimal)); - // assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", - // jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); - // assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", - // jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); + assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", + jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); + assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", + jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); assertTrue("jsonObject serializes bigDec correctly", jsonObject.toString().equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - JSONArray jsonArray = new JSONArray(); - + /** + * exercise some exceptions + */ + try { + jsonObject.getBigDecimal("bigInt"); + assertTrue("expected an exeption", false); + } catch (JSONException ignored) {} + obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); + assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); + try { + jsonObject.getBigInteger("bigDec"); + assertTrue("expected an exeption", false); + } catch (JSONException ignored) {} + jsonObject.put("stringKey", "abc"); + try { + jsonObject.getBigDecimal("stringKey"); + assertTrue("expected an exeption", false); + } catch (JSONException ignored) {} + obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); + assertTrue("expected BigInteger", obj.equals(BigInteger.ONE)); /** * JSONObject.numberToString() works correctly, nothing to change. @@ -904,7 +918,7 @@ public class JSONObjectTest { actualFromPutStr.equals( "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); // bigInt,bigDec put - jsonArray = new JSONArray(); + JSONArray jsonArray = new JSONArray(); jsonArray.put(bigInteger); jsonArray.put(bigDecimal); actualFromPutStr = jsonArray.toString(); @@ -1105,7 +1119,7 @@ public class JSONObjectTest { String str = "{"+ "\"keyLong\":9999999991,"+ - "\"keyDouble\":1.1,"+ + "\"keyDouble\":1.1"+ "}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("keyInt"); @@ -1115,16 +1129,26 @@ public class JSONObjectTest { jsonObject.increment("keyInt"); jsonObject.increment("keyLong"); jsonObject.increment("keyDouble"); + /** + * JSONObject constructor won't handle these types correctly, but + * adding them via put works. + */ jsonObject.put("keyFloat", new Float(1.1)); + jsonObject.put("keyBigInt", new BigInteger("123456789123456789123456789123456780")); + jsonObject.put("keyBigDec", new BigDecimal("123456789123456789123456789123456780.1")); jsonObject.increment("keyFloat"); jsonObject.increment("keyFloat"); + jsonObject.increment("keyBigInt"); + jsonObject.increment("keyBigDec"); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.keyInt"))); assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(JsonPath.read(doc, "$.keyLong"))); assertTrue("expected 3.1", Double.valueOf(3.1).equals(JsonPath.read(doc, "$.keyDouble"))); + assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(JsonPath.read(doc, "$.keyBigInt"))); + assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(JsonPath.read(doc, "$.keyBigDec"))); /** * Should work the same way on any platform! @see https://docs.oracle @@ -1526,8 +1550,6 @@ public class JSONObjectTest { assertTrue("expected val1", "val1".equals(JsonPath.read(doc, "$.key1"))); assertTrue("expected val2", "val2".equals(JsonPath.read(doc, "$.key2"))); assertTrue("expected val3", "val3".equals(JsonPath.read(doc, "$.key3"))); - - // TODO test wrap(package) } /** From c88d06eede9a50b2eb0ab8b705abc980b448207c Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 30 Dec 2015 01:01:43 -0600 Subject: [PATCH 186/451] util cleanup --- JSONMLTest.java | 4 +++- Util.java | 45 --------------------------------------------- 2 files changed, 3 insertions(+), 46 deletions(-) diff --git a/JSONMLTest.java b/JSONMLTest.java index a16f0ea..953a39d 100644 --- a/JSONMLTest.java +++ b/JSONMLTest.java @@ -655,7 +655,9 @@ public class JSONMLTest { // lastly, confirm the restored JSONObject XML and JSONArray XML look // reasonably similar - Util.compareXML(jsonObjectXmlToStr, jsonArrayXmlToStr); + JSONObject jsonObjectFromObject = JSONML.toJSONObject(jsonObjectXmlToStr); + JSONObject jsonObjectFromArray = JSONML.toJSONObject(jsonArrayXmlToStr); + Util.compareActualVsExpectedJsonObjects(jsonObjectFromObject, jsonObjectFromArray); } /** diff --git a/Util.java b/Util.java index eb33ab5..8446690 100644 --- a/Util.java +++ b/Util.java @@ -94,49 +94,4 @@ public class Util { value.toString().equals(expectedValue.toString())); } } - - /** - * Sometimes test completion requires comparison of JSONArray objects that - * were produced from a JSONObject, and so unordered. This method is - * imperfect since it only compares the array elements and won't catch - * JSON syntax errors but at least it does not rely on ordering - *

- * It is expected that the arrays to be compared come from JSONArray - * instances which have been rendered by toString(), and whose syntax - * chars have been removed. - *

- * TODO: why are we not simply comparing the JSONArrays? - *

- * @param names an array of strings for comparison - * @param expectedNames the other array of strings for comparison - */ - public static void compareActualVsExpectedStringArrays(String[] names, - String [] expectedNames) { - assertTrue("Array lengths should be equal", - names.length == expectedNames.length); - List lNames = new ArrayList(Arrays.asList(names)); - for (int i = 0; i < expectedNames.length; ++i) { - String expectedName = expectedNames[i]; - assertTrue("expected to find "+expectedName, - lNames.contains(expectedName)); - lNames.remove(expectedName); - } - } - - /** - * This is stopgap test utility. It is meant to compare strings - * of XML, but it does not take ordering into account and should - * not be expected to work correctly with complex XML. - * @param aXmlStr an XML doc to be compared - * @param bXmlStr the other XML doc to be compared - */ - public static void compareXML(String aXmlStr, String bXmlStr) { - // TODO For simple tests this may be adequate, but it won't work for - // elements with multiple attributes and possibly other cases as well. - // Should use XMLUnit or similar. - assertTrue("expected equal XML strings \naXmlStr: "+ - aXmlStr+ "\nbXmlStr: " +bXmlStr, aXmlStr.equals(bXmlStr)); - - } - } From 871a3e46d77bf6ec51cf3ae8654133ff4aca3597 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 30 Dec 2015 13:50:51 -0600 Subject: [PATCH 187/451] clean up a few more todos --- JSONStringerTest.java | 70 +++++++++++++++++++++---------------------- Util.java | 15 +++++----- 2 files changed, 43 insertions(+), 42 deletions(-) diff --git a/JSONStringerTest.java b/JSONStringerTest.java index c9419df..631d792 100644 --- a/JSONStringerTest.java +++ b/JSONStringerTest.java @@ -11,8 +11,7 @@ import com.jayway.jsonpath.*; /** - * Tests for JSON-Java JSONStringer. - * TODO: Could use a lot more testing. For example, cascade-style productions. + * Tests for JSON-Java JSONStringer and JSONWriter. */ public class JSONStringerTest { @@ -234,43 +233,44 @@ public class JSONStringerTest { } /** - * Build a nested JSON doc using JSONString API calls, - * then convert to JSONObject + * Build a nested JSON doc using JSONString API calls, then convert to + * JSONObject. Will create a long cascade of output by reusing the + * returned values.. */ @Test public void complexObjectString() { JSONStringer jsonStringer = new JSONStringer(); - jsonStringer.object(); - jsonStringer.key("trueValue").value(true); - jsonStringer.key("falseValue").value(false); - jsonStringer.key("nullValue").value(null); - jsonStringer.key("stringValue").value("hello world!"); - jsonStringer.key("object2").object(); - jsonStringer.key("k1").value("v1"); - jsonStringer.key("k2").value("v2"); - jsonStringer.key("k3").value("v3"); - jsonStringer.key("array1").array(); - jsonStringer.value(1); - jsonStringer.value(2); - jsonStringer.object(); - jsonStringer.key("k4").value("v4"); - jsonStringer.key("k5").value("v5"); - jsonStringer.key("k6").value("v6"); - jsonStringer.key("array2").array(); - jsonStringer.value(5); - jsonStringer.value(6); - jsonStringer.value(7); - jsonStringer.value(8); - jsonStringer.endArray(); - jsonStringer.endObject(); - jsonStringer.value(3); - jsonStringer.value(4); - jsonStringer.endArray(); - jsonStringer.endObject(); - jsonStringer.key("complexStringValue").value("h\be\tllo w\u1234orld!"); - jsonStringer.key("intValue").value(42); - jsonStringer.key("doubleValue").value(-23.45e67); - jsonStringer.endObject(); + jsonStringer.object(). + key("trueValue").value(true). + key("falseValue").value(false). + key("nullValue").value(null). + key("stringValue").value("hello world!"). + key("object2").object(). + key("k1").value("v1"). + key("k2").value("v2"). + key("k3").value("v3"). + key("array1").array(). + value(1). + value(2). + object(). + key("k4").value("v4"). + key("k5").value("v5"). + key("k6").value("v6"). + key("array2").array(). + value(5). + value(6). + value(7). + value(8). + endArray(). + endObject(). + value(3). + value(4). + endArray(). + endObject(). + key("complexStringValue").value("h\be\tllo w\u1234orld!"). + key("intValue").value(42). + key("doubleValue").value(-23.45e67). + endObject(); String str = jsonStringer.toString(); JSONObject jsonObject = new JSONObject(str); diff --git a/Util.java b/Util.java index 8446690..6b23d00 100644 --- a/Util.java +++ b/Util.java @@ -59,24 +59,26 @@ public class Util { private static void compareActualVsExpectedObjects(Object value, Object expectedValue) { if (value instanceof JSONObject && expectedValue instanceof JSONObject) { + // Compare JSONObjects JSONObject jsonObject = (JSONObject)value; JSONObject expectedJsonObject = (JSONObject)expectedValue; compareActualVsExpectedJsonObjects( jsonObject, expectedJsonObject); } else if (value instanceof JSONArray && expectedValue instanceof JSONArray) { + // Compare JSONArrays JSONArray jsonArray = (JSONArray)value; JSONArray expectedJsonArray = (JSONArray)expectedValue; compareActualVsExpectedJsonArrays( jsonArray, expectedJsonArray); } else { /** - * Certain helper classes (e.g. XML) may create Long instead of - * Integer for small int values. As long as both are Numbers, - * just compare the toString() values. - * TODO: this may not work in the case where the underlying types - * do not have the same precision. + * Compare all other types using toString(). First, the types must + * also be equal, unless both are Number type. Certain helper + * classes (e.g. XML) may create Long instead of Integer for small + * int values. */ if (!(value instanceof Number && expectedValue instanceof Number)) { + // Non-Number and non-matching types assertTrue("object types should be equal for actual: "+ value.toString()+" ("+ value.getClass().toString()+") expected: "+ @@ -86,8 +88,7 @@ public class Util { expectedValue.getClass().toString())); } /** - * When in doubt, compare by string - * TODO: should not this be an else to the previous condition? + * Same types or both Numbers, compare by toString() */ assertTrue("string values should be equal for actual: "+ value.toString()+" expected: "+expectedValue.toString(), From 280ce7128586d6418b2319a491cdec4d5e9327b9 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 1 Jan 2016 13:54:47 -0600 Subject: [PATCH 188/451] tabs to spaces --- XMLTest.java | 72 ++++++++++++++++++++++++++-------------------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/XMLTest.java b/XMLTest.java index 8069f70..d35c8ac 100644 --- a/XMLTest.java +++ b/XMLTest.java @@ -391,16 +391,16 @@ public class XMLTest { */ @Test public void shouldHandleEmptyArray(){ - final JSONObject jo1 = new JSONObject(); - jo1.put("array",new Object[]{}); - final JSONObject jo2 = new JSONObject(); - jo2.put("array",new JSONArray()); + final JSONObject jo1 = new JSONObject(); + jo1.put("array",new Object[]{}); + final JSONObject jo2 = new JSONObject(); + jo2.put("array",new JSONArray()); - final String expected = ""; - String output1 = XML.toString(jo1,"jo"); - assertTrue("Expected an empty root tag", expected.equals(output1)); - String output2 = XML.toString(jo2,"jo"); - assertTrue("Expected an empty root tag", expected.equals(output2)); + final String expected = ""; + String output1 = XML.toString(jo1,"jo"); + assertTrue("Expected an empty root tag", expected.equals(output1)); + String output2 = XML.toString(jo2,"jo"); + assertTrue("Expected an empty root tag", expected.equals(output2)); } /** @@ -408,16 +408,16 @@ public class XMLTest { */ @Test public void shouldHandleEmptyMultiArray(){ - final JSONObject jo1 = new JSONObject(); - jo1.put("arr",new Object[]{"One", new String[]{}, "Four"}); - final JSONObject jo2 = new JSONObject(); - jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{}), "Four"})); + final JSONObject jo1 = new JSONObject(); + jo1.put("arr",new Object[]{"One", new String[]{}, "Four"}); + final JSONObject jo2 = new JSONObject(); + jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{}), "Four"})); - final String expected = "OneFour"; - String output1 = XML.toString(jo1,"jo"); - assertTrue("Expected a matching array", expected.equals(output1)); - String output2 = XML.toString(jo2,"jo"); - assertTrue("Expected a matching array", expected.equals(output2)); + final String expected = "OneFour"; + String output1 = XML.toString(jo1,"jo"); + assertTrue("Expected a matching array", expected.equals(output1)); + String output2 = XML.toString(jo2,"jo"); + assertTrue("Expected a matching array", expected.equals(output2)); } /** @@ -425,16 +425,16 @@ public class XMLTest { */ @Test public void shouldHandleNonEmptyArray(){ - final JSONObject jo1 = new JSONObject(); - jo1.put("arr",new String[]{"One", "Two", "Three"}); - final JSONObject jo2 = new JSONObject(); - jo2.put("arr",new JSONArray(new String[]{"One", "Two", "Three"})); + final JSONObject jo1 = new JSONObject(); + jo1.put("arr",new String[]{"One", "Two", "Three"}); + final JSONObject jo2 = new JSONObject(); + jo2.put("arr",new JSONArray(new String[]{"One", "Two", "Three"})); - final String expected = "OneTwoThree"; - String output1 = XML.toString(jo1,"jo"); - assertTrue("Expected a non empty root tag", expected.equals(output1)); - String output2 = XML.toString(jo2,"jo"); - assertTrue("Expected a non empty root tag", expected.equals(output2)); + final String expected = "OneTwoThree"; + String output1 = XML.toString(jo1,"jo"); + assertTrue("Expected a non empty root tag", expected.equals(output1)); + String output2 = XML.toString(jo2,"jo"); + assertTrue("Expected a non empty root tag", expected.equals(output2)); } /** @@ -442,16 +442,16 @@ public class XMLTest { */ @Test public void shouldHandleMultiArray(){ - final JSONObject jo1 = new JSONObject(); - jo1.put("arr",new Object[]{"One", new String[]{"Two", "Three"}, "Four"}); - final JSONObject jo2 = new JSONObject(); - jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{"Two", "Three"}), "Four"})); + final JSONObject jo1 = new JSONObject(); + jo1.put("arr",new Object[]{"One", new String[]{"Two", "Three"}, "Four"}); + final JSONObject jo2 = new JSONObject(); + jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{"Two", "Three"}), "Four"})); - final String expected = "OneTwoThreeFour"; - String output1 = XML.toString(jo1,"jo"); - assertTrue("Expected a matching array", expected.equals(output1)); - String output2 = XML.toString(jo2,"jo"); - assertTrue("Expected a matching array", expected.equals(output2)); + final String expected = "OneTwoThreeFour"; + String output1 = XML.toString(jo1,"jo"); + assertTrue("Expected a matching array", expected.equals(output1)); + String output2 = XML.toString(jo2,"jo"); + assertTrue("Expected a matching array", expected.equals(output2)); } /** From ace08f19449f1f62fe5aff201e5dc4140613be36 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 3 Jan 2016 21:39:30 -0600 Subject: [PATCH 189/451] latest --- build.gradle | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 build.gradle diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..2544a69 --- /dev/null +++ b/build.gradle @@ -0,0 +1,26 @@ +apply plugin: 'java' +apply plugin: 'eclipse' + +jar.baseName = 'JSON-java' + +sourceSets { + test { + java { + srcDir 'src/test' + } + } +} + +repositories { + mavenCentral() +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.+' + testCompile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.1.0' + testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' + // Use this line if you are testing a JSON-Java release. + // Otherwise add an external jar from your local repository in Eclipse + // (The gradle build won't work unless you add a main sourceSets entry and a jar.baseName entry + // testCompile group: 'org.json', name: 'json', version: '20151123' +} From 706d898648e3c747740547e78e71ffe48ad8aed7 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 3 Jan 2016 21:39:44 -0600 Subject: [PATCH 190/451] latest --- CDLTest.java => src/test/org/json/junit/CDLTest.java | 0 .../test/org/json/junit/CookieListTest.java | 0 CookieTest.java => src/test/org/json/junit/CookieTest.java | 0 EnumTest.java => src/test/org/json/junit/EnumTest.java | 0 HTTPTest.java => src/test/org/json/junit/HTTPTest.java | 0 JSONArrayTest.java => src/test/org/json/junit/JSONArrayTest.java | 0 JSONMLTest.java => src/test/org/json/junit/JSONMLTest.java | 0 .../test/org/json/junit/JSONObjectTest.java | 0 .../test/org/json/junit/JSONStringerTest.java | 0 .../test/org/json/junit/JunitTestSuite.java | 0 MyBean.java => src/test/org/json/junit/MyBean.java | 0 .../test/org/json/junit/MyBigNumberBean.java | 0 MyEnum.java => src/test/org/json/junit/MyEnum.java | 0 MyEnumClass.java => src/test/org/json/junit/MyEnumClass.java | 0 MyEnumField.java => src/test/org/json/junit/MyEnumField.java | 0 MyJsonString.java => src/test/org/json/junit/MyJsonString.java | 0 MyPublicClass.java => src/test/org/json/junit/MyPublicClass.java | 0 PropertyTest.java => src/test/org/json/junit/PropertyTest.java | 0 .../test/org/json/junit/StringsResourceBundle.java | 0 TestRunner.java => src/test/org/json/junit/TestRunner.java | 0 Util.java => src/test/org/json/junit/Util.java | 0 XMLTest.java => src/test/org/json/junit/XMLTest.java | 0 22 files changed, 0 insertions(+), 0 deletions(-) rename CDLTest.java => src/test/org/json/junit/CDLTest.java (100%) rename CookieListTest.java => src/test/org/json/junit/CookieListTest.java (100%) rename CookieTest.java => src/test/org/json/junit/CookieTest.java (100%) rename EnumTest.java => src/test/org/json/junit/EnumTest.java (100%) rename HTTPTest.java => src/test/org/json/junit/HTTPTest.java (100%) rename JSONArrayTest.java => src/test/org/json/junit/JSONArrayTest.java (100%) rename JSONMLTest.java => src/test/org/json/junit/JSONMLTest.java (100%) rename JSONObjectTest.java => src/test/org/json/junit/JSONObjectTest.java (100%) rename JSONStringerTest.java => src/test/org/json/junit/JSONStringerTest.java (100%) rename JunitTestSuite.java => src/test/org/json/junit/JunitTestSuite.java (100%) rename MyBean.java => src/test/org/json/junit/MyBean.java (100%) rename MyBigNumberBean.java => src/test/org/json/junit/MyBigNumberBean.java (100%) rename MyEnum.java => src/test/org/json/junit/MyEnum.java (100%) rename MyEnumClass.java => src/test/org/json/junit/MyEnumClass.java (100%) rename MyEnumField.java => src/test/org/json/junit/MyEnumField.java (100%) rename MyJsonString.java => src/test/org/json/junit/MyJsonString.java (100%) rename MyPublicClass.java => src/test/org/json/junit/MyPublicClass.java (100%) rename PropertyTest.java => src/test/org/json/junit/PropertyTest.java (100%) rename StringsResourceBundle.java => src/test/org/json/junit/StringsResourceBundle.java (100%) rename TestRunner.java => src/test/org/json/junit/TestRunner.java (100%) rename Util.java => src/test/org/json/junit/Util.java (100%) rename XMLTest.java => src/test/org/json/junit/XMLTest.java (100%) diff --git a/CDLTest.java b/src/test/org/json/junit/CDLTest.java similarity index 100% rename from CDLTest.java rename to src/test/org/json/junit/CDLTest.java diff --git a/CookieListTest.java b/src/test/org/json/junit/CookieListTest.java similarity index 100% rename from CookieListTest.java rename to src/test/org/json/junit/CookieListTest.java diff --git a/CookieTest.java b/src/test/org/json/junit/CookieTest.java similarity index 100% rename from CookieTest.java rename to src/test/org/json/junit/CookieTest.java diff --git a/EnumTest.java b/src/test/org/json/junit/EnumTest.java similarity index 100% rename from EnumTest.java rename to src/test/org/json/junit/EnumTest.java diff --git a/HTTPTest.java b/src/test/org/json/junit/HTTPTest.java similarity index 100% rename from HTTPTest.java rename to src/test/org/json/junit/HTTPTest.java diff --git a/JSONArrayTest.java b/src/test/org/json/junit/JSONArrayTest.java similarity index 100% rename from JSONArrayTest.java rename to src/test/org/json/junit/JSONArrayTest.java diff --git a/JSONMLTest.java b/src/test/org/json/junit/JSONMLTest.java similarity index 100% rename from JSONMLTest.java rename to src/test/org/json/junit/JSONMLTest.java diff --git a/JSONObjectTest.java b/src/test/org/json/junit/JSONObjectTest.java similarity index 100% rename from JSONObjectTest.java rename to src/test/org/json/junit/JSONObjectTest.java diff --git a/JSONStringerTest.java b/src/test/org/json/junit/JSONStringerTest.java similarity index 100% rename from JSONStringerTest.java rename to src/test/org/json/junit/JSONStringerTest.java diff --git a/JunitTestSuite.java b/src/test/org/json/junit/JunitTestSuite.java similarity index 100% rename from JunitTestSuite.java rename to src/test/org/json/junit/JunitTestSuite.java diff --git a/MyBean.java b/src/test/org/json/junit/MyBean.java similarity index 100% rename from MyBean.java rename to src/test/org/json/junit/MyBean.java diff --git a/MyBigNumberBean.java b/src/test/org/json/junit/MyBigNumberBean.java similarity index 100% rename from MyBigNumberBean.java rename to src/test/org/json/junit/MyBigNumberBean.java diff --git a/MyEnum.java b/src/test/org/json/junit/MyEnum.java similarity index 100% rename from MyEnum.java rename to src/test/org/json/junit/MyEnum.java diff --git a/MyEnumClass.java b/src/test/org/json/junit/MyEnumClass.java similarity index 100% rename from MyEnumClass.java rename to src/test/org/json/junit/MyEnumClass.java diff --git a/MyEnumField.java b/src/test/org/json/junit/MyEnumField.java similarity index 100% rename from MyEnumField.java rename to src/test/org/json/junit/MyEnumField.java diff --git a/MyJsonString.java b/src/test/org/json/junit/MyJsonString.java similarity index 100% rename from MyJsonString.java rename to src/test/org/json/junit/MyJsonString.java diff --git a/MyPublicClass.java b/src/test/org/json/junit/MyPublicClass.java similarity index 100% rename from MyPublicClass.java rename to src/test/org/json/junit/MyPublicClass.java diff --git a/PropertyTest.java b/src/test/org/json/junit/PropertyTest.java similarity index 100% rename from PropertyTest.java rename to src/test/org/json/junit/PropertyTest.java diff --git a/StringsResourceBundle.java b/src/test/org/json/junit/StringsResourceBundle.java similarity index 100% rename from StringsResourceBundle.java rename to src/test/org/json/junit/StringsResourceBundle.java diff --git a/TestRunner.java b/src/test/org/json/junit/TestRunner.java similarity index 100% rename from TestRunner.java rename to src/test/org/json/junit/TestRunner.java diff --git a/Util.java b/src/test/org/json/junit/Util.java similarity index 100% rename from Util.java rename to src/test/org/json/junit/Util.java diff --git a/XMLTest.java b/src/test/org/json/junit/XMLTest.java similarity index 100% rename from XMLTest.java rename to src/test/org/json/junit/XMLTest.java From 67d888e9becd116f1e5e28bd3a572f01e4b1268d Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 27 Jan 2016 11:32:11 -0500 Subject: [PATCH 191/451] Adds test cases to verify that -0 and -0.0 are processed as Double --- .gitignore | 5 + src/test/org/json/junit/JSONObjectTest.java | 3283 ++++++++++--------- 2 files changed, 1734 insertions(+), 1554 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9e7b59c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/bin/ +build +.classpath +.project +.settings/ diff --git a/src/test/org/json/junit/JSONObjectTest.java b/src/test/org/json/junit/JSONObjectTest.java index 994c4b3..dc74459 100644 --- a/src/test/org/json/junit/JSONObjectTest.java +++ b/src/test/org/json/junit/JSONObjectTest.java @@ -10,7 +10,14 @@ import java.io.StringWriter; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import org.json.CDL; import org.json.JSONArray; @@ -19,783 +26,29 @@ import org.json.JSONObject; import org.json.XML; import org.junit.Test; -import com.jayway.jsonpath.*; +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.JsonPath; /** - * JSONObject, along with JSONArray, are the central classes of the reference app. - * All of the other classes interact with them, and JSON functionality would - * otherwise be impossible. + * JSONObject, along with JSONArray, are the central classes of the reference + * app. All of the other classes interact with them, and JSON functionality + * would otherwise be impossible. */ public class JSONObjectTest { /** - * JSONObject built from a bean, but only using a null value. - * Nothing good is expected to happen. - * Expects NullPointerException - */ - @Test(expected=NullPointerException.class) - public void jsonObjectByNullBean() { - MyBean myBean = null; - new JSONObject(myBean); - } - - /** - * A JSONObject can be created with no content - */ - @Test - public void emptyJsonObject() { - JSONObject jsonObject = new JSONObject(); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); - } - - /** - * A JSONObject can be created from another JSONObject plus a list of names. - * In this test, some of the starting JSONObject keys are not in the - * names list. - */ - @Test - public void jsonObjectByNames() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"nullKey\":null,"+ - "\"stringKey\":\"hello world!\","+ - "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ - "\"intKey\":42,"+ - "\"doubleKey\":-23.45e67"+ - "}"; - String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"}; - JSONObject jsonObject = new JSONObject(str); - - // validate JSON - JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"nullKey\":null", null == JsonPath.read(doc, "$.nullKey")); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); - } - - /** - * JSONObjects can be built from a Map. - * In this test the map is null. - * the JSONObject(JsonTokener) ctor is not tested directly since it already - * has full coverage from other tests. - */ - @Test - public void jsonObjectByNullMap() { - Map map = null; - JSONObject jsonObject = new JSONObject(map); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); - } - - /** - * JSONObjects can be built from a Map. - * In this test all of the map entries are valid JSON types. - */ - @Test - public void jsonObjectByMap() { - Map map = new HashMap(); - map.put("trueKey", new Boolean(true)); - map.put("falseKey", new Boolean(false)); - map.put("stringKey", "hello world!"); - map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); - map.put("intKey", new Long(42)); - map.put("doubleKey", new Double(-23.45e67)); - JSONObject jsonObject = new JSONObject(map); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); - } - - /** - * Verifies that the constructor has backwards compatability with RAW types pre-java5. - */ - @Test - public void verifyConstructor() { - - final JSONObject expected = new JSONObject("{\"myKey\":10}"); - - @SuppressWarnings("rawtypes") - Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); - JSONObject jaRaw = new JSONObject(myRawC); - - Map myCStrObj = Collections.singletonMap("myKey", - (Object) Integer.valueOf(10)); - JSONObject jaStrObj = new JSONObject(myCStrObj); - - Map myCStrInt = Collections.singletonMap("myKey", - Integer.valueOf(10)); - JSONObject jaStrInt = new JSONObject(myCStrInt); - - Map myCObjObj = Collections.singletonMap((Object) "myKey", - (Object) Integer.valueOf(10)); - JSONObject jaObjObj = new JSONObject(myCObjObj); - - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); - } - - /** - * Verifies that the put Collection has backwards compatability with RAW types pre-java5. - */ - @Test - public void verifyPutCollection() { - - final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); - - @SuppressWarnings("rawtypes") - Collection myRawC = Collections.singleton(Integer.valueOf(10)); - JSONObject jaRaw = new JSONObject(); - jaRaw.put("myCollection", myRawC); - - Collection myCObj = Collections.singleton((Object) Integer - .valueOf(10)); - JSONObject jaObj = new JSONObject(); - jaObj.put("myCollection", myCObj); - - Collection myCInt = Collections.singleton(Integer - .valueOf(10)); - JSONObject jaInt = new JSONObject(); - jaInt.put("myCollection", myCInt); - - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaInt)); - } - - - /** - * Verifies that the put Map has backwards compatability with RAW types pre-java5. - */ - @Test - public void verifyPutMap() { - - final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); - - @SuppressWarnings("rawtypes") - Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); - JSONObject jaRaw = new JSONObject(); - jaRaw.put("myMap", myRawC); - - Map myCStrObj = Collections.singletonMap("myKey", - (Object) Integer.valueOf(10)); - JSONObject jaStrObj = new JSONObject(); - jaStrObj.put("myMap", myCStrObj); - - Map myCStrInt = Collections.singletonMap("myKey", - Integer.valueOf(10)); - JSONObject jaStrInt = new JSONObject(); - jaStrInt.put("myMap", myCStrInt); - - Map myCObjObj = Collections.singletonMap((Object) "myKey", - (Object) Integer.valueOf(10)); - JSONObject jaObjObj = new JSONObject(); - jaObjObj.put("myMap", myCObjObj); - - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); - } - - - /** - * JSONObjects can be built from a Map. - * In this test the map entries are not valid JSON types. - * The actual conversion is kind of interesting. - */ - @Test - public void jsonObjectByMapWithUnsupportedValues() { - Map jsonMap = new HashMap(); - // Just insert some random objects - jsonMap.put("key1", new CDL()); - jsonMap.put("key2", new Exception()); - - JSONObject jsonObject = new JSONObject(jsonMap); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(JsonPath.read(doc, "$.key2"))); - assertTrue("expected 0 key1 items", ((Map)(JsonPath.read(doc, "$.key1"))).size() == 0); - } - - /** - * JSONObjects can be built from a Map. - * In this test one of the map values is null - */ - @Test - public void jsonObjectByMapWithNullValue() { - Map map = new HashMap(); - map.put("trueKey", new Boolean(true)); - map.put("falseKey", new Boolean(false)); - map.put("stringKey", "hello world!"); - map.put("nullKey", null); - map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); - map.put("intKey", new Long(42)); - map.put("doubleKey", new Double(-23.45e67)); - JSONObject jsonObject = new JSONObject(map); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); - assertTrue("expected \"intKey\":42", Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); - } - - /** - * JSONObject built from a bean. In this case all but one of the - * bean getters return valid JSON types - */ - @Test - public void jsonObjectByBean() { - /** - * Default access classes have to be mocked since JSONObject, which is - * not in the same package, cannot call MyBean methods by reflection. - */ - MyBean myBean = mock(MyBean.class); - when(myBean.getDoubleKey()).thenReturn(-23.45e7); - when(myBean.getIntKey()).thenReturn(42); - when(myBean.getStringKey()).thenReturn("hello world!"); - when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!"); - when(myBean.isTrueKey()).thenReturn(true); - when(myBean.isFalseKey()).thenReturn(false); - when(myBean.getStringReaderKey()).thenReturn( - new StringReader("") { - }); - - JSONObject jsonObject = new JSONObject(myBean); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected hello world!","hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); - assertTrue("expected 42", Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); - assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(JsonPath.read(doc, "$.doubleKey"))); - assertTrue("expected 0 items in stringReaderKey", ((Map) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); - // sorry, mockito artifact - assertTrue("expected 2 callbacks items", ((List)(JsonPath.read(doc, "$.callbacks"))).size() == 2); - assertTrue("expected 0 handler items", ((Map)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0); - assertTrue("expected 0 callbacks[1] items", ((Map)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0); - } - - /** - * A bean is also an object. But in order to test the JSONObject - * ctor that takes an object and a list of names, - * this particular bean needs some public - * data members, which have been added to the class. - */ - @Test - public void jsonObjectByObjectAndNames() { - String[] keys = {"publicString", "publicInt"}; - // just need a class that has public data members - MyPublicClass myPublicClass = new MyPublicClass(); - JSONObject jsonObject = new JSONObject(myPublicClass, keys); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected \"publicString\":\"abc\"", "abc".equals(JsonPath.read(doc, "$.publicString"))); - assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.publicInt"))); - } - - /** - * Exercise the JSONObject from resource bundle functionality. - * The test resource bundle is uncomplicated, but provides adequate test coverage. - */ - @Test - public void jsonObjectByResourceBundle() { - JSONObject jsonObject = new - JSONObject("org.json.junit.StringsResourceBundle", - Locale.getDefault()); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected 2 greetings items", ((Map)(JsonPath.read(doc, "$.greetings"))).size() == 2); - assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(JsonPath.read(doc, "$.greetings.hello"))); - assertTrue("expected \"world\":\"World!\"", "World!".equals(JsonPath.read(doc, "$.greetings.world"))); - assertTrue("expected 2 farewells items", ((Map)(JsonPath.read(doc, "$.farewells"))).size() == 2); - assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(JsonPath.read(doc, "$.farewells.later"))); - assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(JsonPath.read(doc, "$.farewells.gator"))); - } - - /** - * Exercise the JSONObject.accumulate() method - */ - @Test - public void jsonObjectAccumulate() { - - JSONObject jsonObject = new JSONObject(); - jsonObject.accumulate("myArray", true); - jsonObject.accumulate("myArray", false); - jsonObject.accumulate("myArray", "hello world!"); - jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); - jsonObject.accumulate("myArray", 42); - jsonObject.accumulate("myArray", -23.45e7); - // include an unsupported object for coverage - try { - jsonObject.accumulate("myArray", Double.NaN); - assertTrue("Expected exception", false); - } catch (JSONException ignored) {} - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); - assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.myArray[3]"))); - assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); - assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(JsonPath.read(doc, "$.myArray[5]"))); - } - - /** - * Exercise the JSONObject append() functionality - */ - @Test - public void jsonObjectAppend() { - JSONObject jsonObject = new JSONObject(); - jsonObject.append("myArray", true); - jsonObject.append("myArray", false); - jsonObject.append("myArray", "hello world!"); - jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); - jsonObject.append("myArray", 42); - jsonObject.append("myArray", -23.45e7); - // include an unsupported object for coverage - try { - jsonObject.append("myArray", Double.NaN); - assertTrue("Expected exception", false); - } catch (JSONException ignored) {} - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); - assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.myArray[3]"))); - assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); - assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(JsonPath.read(doc, "$.myArray[5]"))); - } - - /** - * Exercise the JSONObject doubleToString() method - */ - @Test - public void jsonObjectDoubleToString() { - String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; - Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, - Double.NaN, Double.NEGATIVE_INFINITY }; - for (int i = 0; i < expectedStrs.length; ++i) { - String actualStr = JSONObject.doubleToString(doubles[i]); - assertTrue("value expected ["+expectedStrs[i]+ - "] found ["+actualStr+ "]", - expectedStrs[i].equals(actualStr)); - } - } - - /** - * Exercise some JSONObject get[type] and opt[type] methods - */ - @Test - public void jsonObjectValues() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"trueStrKey\":\"true\","+ - "\"falseStrKey\":\"false\","+ - "\"stringKey\":\"hello world!\","+ - "\"intKey\":42,"+ - "\"intStrKey\":\"43\","+ - "\"longKey\":1234567890123456789,"+ - "\"longStrKey\":\"987654321098765432\","+ - "\"doubleKey\":-23.45e7,"+ - "\"doubleStrKey\":\"00001.000\","+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{\"myKey\":\"myVal\"}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); - assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); - assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); - assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); - assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); - assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); - assertTrue("stringKey should be string", - jsonObject.getString("stringKey").equals("hello world!")); - assertTrue("doubleKey should be double", - jsonObject.getDouble("doubleKey") == -23.45e7); - assertTrue("doubleStrKey should be double", - jsonObject.getDouble("doubleStrKey") == 1); - assertTrue("opt doubleKey should be double", - jsonObject.optDouble("doubleKey") == -23.45e7); - assertTrue("opt doubleKey with Default should be double", - jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); - assertTrue("intKey should be int", - jsonObject.optInt("intKey") == 42); - assertTrue("opt intKey should be int", - jsonObject.optInt("intKey", 0) == 42); - assertTrue("opt intKey with default should be int", - jsonObject.getInt("intKey") == 42); - assertTrue("intStrKey should be int", - jsonObject.getInt("intStrKey") == 43); - assertTrue("longKey should be long", - jsonObject.getLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey should be long", - jsonObject.optLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey with default should be long", - jsonObject.optLong("longKey", 0) == 1234567890123456789L); - assertTrue("longStrKey should be long", - jsonObject.getLong("longStrKey") == 987654321098765432L); - assertTrue("xKey should not exist", - jsonObject.isNull("xKey")); - assertTrue("stringKey should exist", - jsonObject.has("stringKey")); - assertTrue("opt stringKey should string", - jsonObject.optString("stringKey").equals("hello world!")); - assertTrue("opt stringKey with default should string", - jsonObject.optString("stringKey", "not found").equals("hello world!")); - JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); - assertTrue("arrayKey should be JSONArray", - jsonArray.getInt(0) == 0 && - jsonArray.getInt(1) == 1 && - jsonArray.getInt(2) == 2); - jsonArray = jsonObject.optJSONArray("arrayKey"); - assertTrue("opt arrayKey should be JSONArray", - jsonArray.getInt(0) == 0 && - jsonArray.getInt(1) == 1 && - jsonArray.getInt(2) == 2); - JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); - assertTrue("objectKey should be JSONObject", - jsonObjectInner.get("myKey").equals("myVal")); - } - - /** - * Check whether JSONObject handles large or high precision numbers correctly - */ - @Test - public void stringToValueNumbersTest() { - - assertTrue( "0.2 should be a Double!", - JSONObject.stringToValue( "0.2" ) instanceof Double ); - assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", - JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double ); - /** - * This test documents a need for BigDecimal conversion. - */ - Object obj = JSONObject.stringToValue( "299792.457999999984" ); - assertTrue( "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!", - obj.equals(new Double(299792.458)) ); - assertTrue( "1 should be an Integer!", - JSONObject.stringToValue( "1" ) instanceof Integer ); - assertTrue( "Integer.MAX_VALUE should still be an Integer!", - JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); - assertTrue( "Large integers should be a Long!", - JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); - assertTrue( "Long.MAX_VALUE should still be an Integer!", - JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); - - String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString(); - assertTrue( "Really large integers currently evaluate to string", - JSONObject.stringToValue(str).equals("9223372036854775808")); - } - - /** - * This test documents numeric values which could be numerically - * handled as BigDecimal or BigInteger. It helps determine what outputs - * will change if those types are supported. - */ - @Test - public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { - // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects - String str = - "{"+ - "\"numberWithDecimals\":299792.457999999984,"+ - "\"largeNumber\":12345678901234567890,"+ - "\"preciseNumber\":0.2000000000000000111,"+ - "\"largeExponent\":-23.45e2327"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - // Comes back as a double, but loses precision - assertTrue( "numberWithDecimals currently evaluates to double 299792.458", - jsonObject.get( "numberWithDecimals" ).equals( new Double( "299792.458" ) ) ); - Object obj = jsonObject.get( "largeNumber" ); - assertTrue("largeNumber currently evaluates to string", - "12345678901234567890".equals(obj)); - // comes back as a double but loses precision - assertTrue( "preciseNumber currently evaluates to double 0.2", - jsonObject.get( "preciseNumber" ).equals(new Double(0.2))); - obj = jsonObject.get( "largeExponent" ); - assertTrue("largeExponent should currently evaluates as a string", - "-23.45e2327".equals(obj)); - } - - /** - * This test documents how JSON-Java handles invalid numeric input. - */ - @Test - public void jsonInvalidNumberValues() { - // Number-notations supported by Java and invalid as JSON - String str = - "{"+ - "\"hexNumber\":-0x123,"+ - "\"tooManyZeros\":00,"+ - "\"negativeInfinite\":-Infinity,"+ - "\"negativeNaN\":-NaN,"+ - "\"negativeFraction\":-.01,"+ - "\"tooManyZerosFraction\":00.001,"+ - "\"negativeHexFloat\":-0x1.fffp1,"+ - "\"hexFloat\":0x1.0P-1074,"+ - "\"floatIdentifier\":0.1f,"+ - "\"doubleIdentifier\":0.1d"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - Object obj; - obj = jsonObject.get( "hexNumber" ); - assertFalse( "hexNumber must not be a number (should throw exception!?)", - obj instanceof Number ); - assertTrue("hexNumber currently evaluates to string", - obj.equals("-0x123")); - assertTrue( "tooManyZeros currently evaluates to string", - jsonObject.get( "tooManyZeros" ).equals("00")); - obj = jsonObject.get("negativeInfinite"); - assertTrue( "negativeInfinite currently evaluates to string", - obj.equals("-Infinity")); - obj = jsonObject.get("negativeNaN"); - assertTrue( "negativeNaN currently evaluates to string", - obj.equals("-NaN")); - assertTrue( "negativeFraction currently evaluates to double -0.01", - jsonObject.get( "negativeFraction" ).equals(new Double(-0.01))); - assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", - jsonObject.get( "tooManyZerosFraction" ).equals(new Double(0.001))); - assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875", - jsonObject.get( "negativeHexFloat" ).equals(new Double(-3.99951171875))); - assertTrue("hexFloat currently evaluates to double 4.9E-324", - jsonObject.get("hexFloat").equals(new Double(4.9E-324))); - assertTrue("floatIdentifier currently evaluates to double 0.1", - jsonObject.get("floatIdentifier").equals(new Double(0.1))); - assertTrue("doubleIdentifier currently evaluates to double 0.1", - jsonObject.get("doubleIdentifier").equals(new Double(0.1))); - } - - /** - * Tests how JSONObject get[type] handles incorrect types - */ - @Test - public void jsonObjectNonAndWrongValues() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"trueStrKey\":\"true\","+ - "\"falseStrKey\":\"false\","+ - "\"stringKey\":\"hello world!\","+ - "\"intKey\":42,"+ - "\"intStrKey\":\"43\","+ - "\"longKey\":1234567890123456789,"+ - "\"longStrKey\":\"987654321098765432\","+ - "\"doubleKey\":-23.45e7,"+ - "\"doubleStrKey\":\"00001.000\","+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{\"myKey\":\"myVal\"}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - try { - jsonObject.getBoolean("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("expecting an exception message", - "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); - } - try { - jsonObject.getBoolean("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a Boolean.". - equals(e.getMessage())); - } - try { - jsonObject.getString("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getString("trueKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"trueKey\"] not a string.". - equals(e.getMessage())); - } - try { - jsonObject.getDouble("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getDouble("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a number.". - equals(e.getMessage())); - } - try { - jsonObject.getInt("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getInt("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not an int.". - equals(e.getMessage())); - } - try { - jsonObject.getLong("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getLong("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a long.". - equals(e.getMessage())); - } - try { - jsonObject.getJSONArray("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getJSONArray("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a JSONArray.". - equals(e.getMessage())); - } - try { - jsonObject.getJSONObject("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getJSONObject("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a JSONObject.". - equals(e.getMessage())); - } - } - - /** - * This test documents an unexpected numeric behavior. - * A double that ends with .0 is parsed, serialized, then - * parsed again. On the second parse, it has become an int. - */ - @Test - public void unexpectedDoubleToIntConversion() { - String key30 = "key30"; - String key31 = "key31"; - JSONObject jsonObject = new JSONObject(); - jsonObject.put(key30, new Double(3.0)); - jsonObject.put(key31, new Double(3.1)); - - assertTrue("3.0 should remain a double", - jsonObject.getDouble(key30) == 3); - assertTrue("3.1 should remain a double", - jsonObject.getDouble(key31) == 3.1); - - // turns 3.0 into 3. - String serializedString = jsonObject.toString(); - JSONObject deserialized = new JSONObject(serializedString); - assertTrue("3.0 is now an int", deserialized.get(key30) instanceof Integer); - assertTrue("3.0 can still be interpreted as a double", - deserialized.getDouble(key30) == 3.0); - assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); - } - - /** - * Document behaviors of big numbers. Includes both JSONObject - * and JSONArray tests + * Document behaviors of big numbers. Includes both JSONObject and JSONArray + * tests */ @Test public void bigNumberOperations() { /** - * JSONObject tries to parse BigInteger as a bean, but it only has - * one getter, getLowestBitSet(). The value is lost and an unhelpful - * value is stored. This should be fixed. + * JSONObject tries to parse BigInteger as a bean, but it only has one + * getter, getLowestBitSet(). The value is lost and an unhelpful value + * is stored. This should be fixed. */ - BigInteger bigInteger = new BigInteger("123456789012345678901234567890"); + final BigInteger bigInteger = new BigInteger( + "123456789012345678901234567890"); JSONObject jsonObject = new JSONObject(bigInteger); Object obj = jsonObject.get("lowestSetBit"); assertTrue("JSONObject only has 1 value", jsonObject.length() == 1); @@ -805,18 +58,18 @@ public class JSONObjectTest { obj.equals(1)); /** - * JSONObject tries to parse BigDecimal as a bean, but it has - * no getters, The value is lost and no value is stored. - * This should be fixed. + * JSONObject tries to parse BigDecimal as a bean, but it has no + * getters, The value is lost and no value is stored. This should be + * fixed. */ - BigDecimal bigDecimal = new BigDecimal( + final BigDecimal bigDecimal = new BigDecimal( "123456789012345678901234567890.12345678901234567890123456789"); jsonObject = new JSONObject(bigDecimal); assertTrue("large bigDecimal is not stored", jsonObject.length() == 0); /** - * JSONObject put(String, Object) method stores and serializes - * bigInt and bigDec correctly. Nothing needs to change. + * JSONObject put(String, Object) method stores and serializes bigInt + * and bigDec correctly. Nothing needs to change. */ jsonObject = new JSONObject(); jsonObject.put("bigInt", bigInteger); @@ -824,21 +77,29 @@ public class JSONObjectTest { jsonObject.get("bigInt").equals(bigInteger)); assertTrue("jsonObject.getBigInteger() handles bigInt correctly", jsonObject.getBigInteger("bigInt").equals(bigInteger)); - assertTrue("jsonObject.optBigInteger() handles bigInt correctly", - jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); - assertTrue("jsonObject serializes bigInt correctly", - jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); + assertTrue( + "jsonObject.optBigInteger() handles bigInt correctly", + jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals( + bigInteger)); + assertTrue( + "jsonObject serializes bigInt correctly", + jsonObject.toString().equals( + "{\"bigInt\":123456789012345678901234567890}")); jsonObject = new JSONObject(); jsonObject.put("bigDec", bigDecimal); assertTrue("jsonObject.put() handles bigDec correctly", jsonObject.get("bigDec").equals(bigDecimal)); assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); - assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", - jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); - assertTrue("jsonObject serializes bigDec correctly", - jsonObject.toString().equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + assertTrue( + "jsonObject.optBigDecimal() handles bigDec correctly", + jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals( + bigDecimal)); + assertTrue( + "jsonObject serializes bigDec correctly", + jsonObject + .toString() + .equals("{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); /** * exercise some exceptions @@ -846,18 +107,21 @@ public class JSONObjectTest { try { jsonObject.getBigDecimal("bigInt"); assertTrue("expected an exeption", false); - } catch (JSONException ignored) {} + } catch (final JSONException ignored) { + } obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); try { jsonObject.getBigInteger("bigDec"); assertTrue("expected an exeption", false); - } catch (JSONException ignored) {} - jsonObject.put("stringKey", "abc"); + } catch (final JSONException ignored) { + } + jsonObject.put("stringKey", "abc"); try { jsonObject.getBigDecimal("stringKey"); assertTrue("expected an exeption", false); - } catch (JSONException ignored) {} + } catch (final JSONException ignored) { + } obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); assertTrue("expected BigInteger", obj.equals(BigInteger.ONE)); @@ -868,117 +132,730 @@ public class JSONObjectTest { assertTrue("numberToString() handles bigInteger correctly", str.equals("123456789012345678901234567890")); str = JSONObject.numberToString(bigDecimal); - assertTrue("numberToString() handles bigDecimal correctly", + assertTrue( + "numberToString() handles bigDecimal correctly", str.equals("123456789012345678901234567890.12345678901234567890123456789")); /** - * JSONObject.stringToValue() turns bigInt into an accurate string, - * and rounds bigDec. This incorrect, but users may have come to - * expect this behavior. Change would be marginally better, but - * might inconvenience users. + * JSONObject.stringToValue() turns bigInt into an accurate string, and + * rounds bigDec. This incorrect, but users may have come to expect this + * behavior. Change would be marginally better, but might inconvenience + * users. */ obj = JSONObject.stringToValue(bigInteger.toString()); assertTrue("stringToValue() turns bigInteger string into string", obj instanceof String); obj = JSONObject.stringToValue(bigDecimal.toString()); - assertTrue("stringToValue() changes bigDecimal string", - !obj.toString().equals(bigDecimal.toString())); + assertTrue("stringToValue() changes bigDecimal string", !obj.toString() + .equals(bigDecimal.toString())); /** * wrap() vs put() big number behavior is now the same. */ - // bigInt map ctor + // bigInt map ctor Map map = new HashMap(); map.put("bigInt", bigInteger); jsonObject = new JSONObject(map); String actualFromMapStr = jsonObject.toString(); assertTrue("bigInt in map (or array or bean) is a string", - actualFromMapStr.equals( - "{\"bigInt\":123456789012345678901234567890}")); + actualFromMapStr + .equals("{\"bigInt\":123456789012345678901234567890}")); // bigInt put jsonObject = new JSONObject(); jsonObject.put("bigInt", bigInteger); String actualFromPutStr = jsonObject.toString(); assertTrue("bigInt from put is a number", - actualFromPutStr.equals( - "{\"bigInt\":123456789012345678901234567890}")); + actualFromPutStr + .equals("{\"bigInt\":123456789012345678901234567890}")); // bigDec map ctor map = new HashMap(); map.put("bigDec", bigDecimal); jsonObject = new JSONObject(map); actualFromMapStr = jsonObject.toString(); - assertTrue("bigDec in map (or array or bean) is a bigDec", - actualFromMapStr.equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + assertTrue( + "bigDec in map (or array or bean) is a bigDec", + actualFromMapStr + .equals("{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); // bigDec put jsonObject = new JSONObject(); jsonObject.put("bigDec", bigDecimal); actualFromPutStr = jsonObject.toString(); - assertTrue("bigDec from put is a number", - actualFromPutStr.equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - // bigInt,bigDec put + assertTrue( + "bigDec from put is a number", + actualFromPutStr + .equals("{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + // bigInt,bigDec put JSONArray jsonArray = new JSONArray(); jsonArray.put(bigInteger); jsonArray.put(bigDecimal); actualFromPutStr = jsonArray.toString(); - assertTrue("bigInt, bigDec from put is a number", - actualFromPutStr.equals( - "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); - assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger)); - assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal)); - assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); - assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); + assertTrue( + "bigInt, bigDec from put is a number", + actualFromPutStr + .equals("[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); + assertTrue("getBigInt is bigInt", + jsonArray.getBigInteger(0).equals(bigInteger)); + assertTrue("getBigDec is bigDec", + jsonArray.getBigDecimal(1).equals(bigDecimal)); + assertTrue("optBigInt is bigInt", + jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); + assertTrue("optBigDec is bigDec", + jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); jsonArray.put(Boolean.TRUE); try { jsonArray.getBigInteger(2); assertTrue("should not be able to get big int", false); - } catch (Exception ignored) {} + } catch (final Exception ignored) { + } try { jsonArray.getBigDecimal(2); assertTrue("should not be able to get big dec", false); - } catch (Exception ignored) {} - assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); - assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); + } catch (final Exception ignored) { + } + assertTrue( + "optBigInt is default", + jsonArray.optBigInteger(2, BigInteger.ONE).equals( + BigInteger.ONE)); + assertTrue( + "optBigDec is default", + jsonArray.optBigDecimal(2, BigDecimal.ONE).equals( + BigDecimal.ONE)); // bigInt,bigDec list ctor - List list = new ArrayList(); + final List list = new ArrayList(); list.add(bigInteger); list.add(bigDecimal); jsonArray = new JSONArray(list); - String actualFromListStr = jsonArray.toString(); - assertTrue("bigInt, bigDec in list is a bigInt, bigDec", - actualFromListStr.equals( - "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); + final String actualFromListStr = jsonArray.toString(); + assertTrue( + "bigInt, bigDec in list is a bigInt, bigDec", + actualFromListStr + .equals("[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); // bigInt bean ctor MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); - when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); + when(myBigNumberBean.getBigInteger()).thenReturn( + new BigInteger("123456789012345678901234567890")); jsonObject = new JSONObject(myBigNumberBean); String actualFromBeanStr = jsonObject.toString(); - // can't do a full string compare because mockery adds an extra key/value + // can't do a full string compare because mockery adds an extra + // key/value assertTrue("bigInt from bean ctor is a bigInt", actualFromBeanStr.contains("123456789012345678901234567890")); // bigDec bean ctor myBigNumberBean = mock(MyBigNumberBean.class); - when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); + when(myBigNumberBean.getBigDecimal()) + .thenReturn( + new BigDecimal( + "123456789012345678901234567890.12345678901234567890123456789")); jsonObject = new JSONObject(myBigNumberBean); actualFromBeanStr = jsonObject.toString(); - // can't do a full string compare because mockery adds an extra key/value - assertTrue("bigDec from bean ctor is a bigDec", - actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789")); + // can't do a full string compare because mockery adds an extra + // key/value + assertTrue( + "bigDec from bean ctor is a bigDec", + actualFromBeanStr + .contains("123456789012345678901234567890.12345678901234567890123456789")); // bigInt,bigDec wrap() obj = JSONObject.wrap(bigInteger); - assertTrue("wrap() returns big num",obj.equals(bigInteger)); + assertTrue("wrap() returns big num", obj.equals(bigInteger)); obj = JSONObject.wrap(bigDecimal); - assertTrue("wrap() returns string",obj.equals(bigDecimal)); + assertTrue("wrap() returns string", obj.equals(bigDecimal)); } /** - * The purpose for the static method getNames() methods are not clear. - * This method is not called from within JSON-Java. Most likely - * uses are to prep names arrays for: - * JSONObject(JSONObject jo, String[] names) + * A JSONObject can be created with no content + */ + @Test + public void emptyJsonObject() { + final JSONObject jsonObject = new JSONObject(); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + /** + * Populate a JSONArray from an empty JSONObject names() method. It should + * be empty. + */ + @Test + public void emptyJsonObjectNamesToJsonAray() { + final JSONObject jsonObject = new JSONObject(); + final JSONArray jsonArray = jsonObject.names(); + assertTrue("jsonArray should be null", jsonArray == null); + } + + /** + * Exercise the JSONObject equals() method + */ + @Test + public void equals() { + final String str = "{\"key\":\"value\"}"; + final JSONObject aJsonObject = new JSONObject(str); + assertTrue("Same JSONObject should be equal to itself", + aJsonObject.equals(aJsonObject)); + } + + /** + * This test documents how JSON-Java handles invalid numeric input. + */ + @Test + public void jsonInvalidNumberValues() { + // Number-notations supported by Java and invalid as JSON + final String str = "{" + "\"hexNumber\":-0x123," + + "\"tooManyZeros\":00," + "\"negativeInfinite\":-Infinity," + + "\"negativeNaN\":-NaN," + "\"negativeFraction\":-.01," + + "\"tooManyZerosFraction\":00.001," + + "\"negativeHexFloat\":-0x1.fffp1," + + "\"hexFloat\":0x1.0P-1074," + "\"floatIdentifier\":0.1f," + + "\"doubleIdentifier\":0.1d" + "}"; + final JSONObject jsonObject = new JSONObject(str); + Object obj; + obj = jsonObject.get("hexNumber"); + assertFalse( + "hexNumber must not be a number (should throw exception!?)", + obj instanceof Number); + assertTrue("hexNumber currently evaluates to string", + obj.equals("-0x123")); + assertTrue("tooManyZeros currently evaluates to string", jsonObject + .get("tooManyZeros").equals("00")); + obj = jsonObject.get("negativeInfinite"); + assertTrue("negativeInfinite currently evaluates to string", + obj.equals("-Infinity")); + obj = jsonObject.get("negativeNaN"); + assertTrue("negativeNaN currently evaluates to string", + obj.equals("-NaN")); + assertTrue("negativeFraction currently evaluates to double -0.01", + jsonObject.get("negativeFraction").equals(new Double(-0.01))); + assertTrue("tooManyZerosFraction currently evaluates to double 0.001", + jsonObject.get("tooManyZerosFraction") + .equals(new Double(0.001))); + assertTrue( + "negativeHexFloat currently evaluates to double -3.99951171875", + jsonObject.get("negativeHexFloat").equals( + new Double(-3.99951171875))); + assertTrue("hexFloat currently evaluates to double 4.9E-324", + jsonObject.get("hexFloat").equals(new Double(4.9E-324))); + assertTrue("floatIdentifier currently evaluates to double 0.1", + jsonObject.get("floatIdentifier").equals(new Double(0.1))); + assertTrue("doubleIdentifier currently evaluates to double 0.1", + jsonObject.get("doubleIdentifier").equals(new Double(0.1))); + } + + /** + * Exercise the JSONObject.accumulate() method + */ + @Test + public void jsonObjectAccumulate() { + + final JSONObject jsonObject = new JSONObject(); + jsonObject.accumulate("myArray", true); + jsonObject.accumulate("myArray", false); + jsonObject.accumulate("myArray", "hello world!"); + jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); + jsonObject.accumulate("myArray", 42); + jsonObject.accumulate("myArray", -23.45e7); + // include an unsupported object for coverage + try { + jsonObject.accumulate("myArray", Double.NaN); + assertTrue("Expected exception", false); + } catch (final JSONException ignored) { + } + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 1 top level item", + ((Map) JsonPath.read(doc, "$")).size() == 1); + assertTrue("expected 6 myArray items", + ((List) JsonPath.read(doc, "$.myArray")).size() == 6); + assertTrue("expected true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); + assertTrue("expected false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); + assertTrue("expected hello world!", + "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); + assertTrue("expected h\be\tllo w\u1234orld!", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.myArray[3]"))); + assertTrue("expected 42", + Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); + assertTrue( + "expected -23.45e7", + Double.valueOf(-23.45e7).equals( + JsonPath.read(doc, "$.myArray[5]"))); + } + + /** + * Exercise the JSONObject append() functionality + */ + @Test + public void jsonObjectAppend() { + final JSONObject jsonObject = new JSONObject(); + jsonObject.append("myArray", true); + jsonObject.append("myArray", false); + jsonObject.append("myArray", "hello world!"); + jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); + jsonObject.append("myArray", 42); + jsonObject.append("myArray", -23.45e7); + // include an unsupported object for coverage + try { + jsonObject.append("myArray", Double.NaN); + assertTrue("Expected exception", false); + } catch (final JSONException ignored) { + } + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 1 top level item", + ((Map) JsonPath.read(doc, "$")).size() == 1); + assertTrue("expected 6 myArray items", + ((List) JsonPath.read(doc, "$.myArray")).size() == 6); + assertTrue("expected true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); + assertTrue("expected false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); + assertTrue("expected hello world!", + "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); + assertTrue("expected h\be\tllo w\u1234orld!", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.myArray[3]"))); + assertTrue("expected 42", + Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); + assertTrue( + "expected -23.45e7", + Double.valueOf(-23.45e7).equals( + JsonPath.read(doc, "$.myArray[5]"))); + } + + /** + * JSONObject built from a bean. In this case all but one of the bean + * getters return valid JSON types + */ + @Test + public void jsonObjectByBean() { + /** + * Default access classes have to be mocked since JSONObject, which is + * not in the same package, cannot call MyBean methods by reflection. + */ + final MyBean myBean = mock(MyBean.class); + when(myBean.getDoubleKey()).thenReturn(-23.45e7); + when(myBean.getIntKey()).thenReturn(42); + when(myBean.getStringKey()).thenReturn("hello world!"); + when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!"); + when(myBean.isTrueKey()).thenReturn(true); + when(myBean.isFalseKey()).thenReturn(false); + when(myBean.getStringReaderKey()).thenReturn(new StringReader("") { + }); + + final JSONObject jsonObject = new JSONObject(myBean); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 8 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 8); + assertTrue("expected true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected hello world!", + "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected h\be\tllo w\u1234orld!", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.escapeStringKey"))); + assertTrue("expected 42", + Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); + assertTrue( + "expected -23.45e7", + Double.valueOf("-23.45e7").equals( + JsonPath.read(doc, "$.doubleKey"))); + assertTrue( + "expected 0 items in stringReaderKey", + ((Map) JsonPath.read(doc, "$.stringReaderKey")).size() == 0); + // sorry, mockito artifact + assertTrue("expected 2 callbacks items", + ((List) JsonPath.read(doc, "$.callbacks")).size() == 2); + assertTrue("expected 0 handler items", ((Map) JsonPath.read(doc, + "$.callbacks[0].handler")).size() == 0); + assertTrue("expected 0 callbacks[1] items", + ((Map) JsonPath.read(doc, "$.callbacks[1]")).size() == 0); + } + + /** + * JSONObjects can be built from a Map. In this test all of + * the map entries are valid JSON types. + */ + @Test + public void jsonObjectByMap() { + final Map map = new HashMap(); + map.put("trueKey", new Boolean(true)); + map.put("falseKey", new Boolean(false)); + map.put("stringKey", "hello world!"); + map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); + map.put("intKey", new Long(42)); + map.put("doubleKey", new Double(-23.45e67)); + final JSONObject jsonObject = new JSONObject(map); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 6 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 6); + assertTrue("expected \"trueKey\":true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected \"falseKey\":false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", + "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.escapeStringKey"))); + assertTrue( + "expected \"doubleKey\":-23.45e67", + Double.valueOf("-23.45e67").equals( + JsonPath.read(doc, "$.doubleKey"))); + } + + /** + * JSONObjects can be built from a Map. In this test one of + * the map values is null + */ + @Test + public void jsonObjectByMapWithNullValue() { + final Map map = new HashMap(); + map.put("trueKey", new Boolean(true)); + map.put("falseKey", new Boolean(false)); + map.put("stringKey", "hello world!"); + map.put("nullKey", null); + map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); + map.put("intKey", new Long(42)); + map.put("doubleKey", new Double(-23.45e67)); + final JSONObject jsonObject = new JSONObject(map); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 6 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 6); + assertTrue("expected \"trueKey\":true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected \"falseKey\":false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", + "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", + "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, + "$.escapeStringKey"))); + assertTrue("expected \"intKey\":42", + Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); + assertTrue( + "expected \"doubleKey\":-23.45e67", + Double.valueOf("-23.45e67").equals( + JsonPath.read(doc, "$.doubleKey"))); + } + + /** + * JSONObjects can be built from a Map. In this test the map + * entries are not valid JSON types. The actual conversion is kind of + * interesting. + */ + @Test + public void jsonObjectByMapWithUnsupportedValues() { + final Map jsonMap = new HashMap(); + // Just insert some random objects + jsonMap.put("key1", new CDL()); + jsonMap.put("key2", new Exception()); + + final JSONObject jsonObject = new JSONObject(jsonMap); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 2 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 2); + assertTrue("expected \"key2\":java.lang.Exception", + "java.lang.Exception".equals(JsonPath.read(doc, "$.key2"))); + assertTrue("expected 0 key1 items", + ((Map) JsonPath.read(doc, "$.key1")).size() == 0); + } + + /** + * A JSONObject can be created from another JSONObject plus a list of names. + * In this test, some of the starting JSONObject keys are not in the names + * list. + */ + @Test + public void jsonObjectByNames() { + final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," + + "\"nullKey\":null," + "\"stringKey\":\"hello world!\"," + + "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\"," + + "\"intKey\":42," + "\"doubleKey\":-23.45e67" + "}"; + final String[] keys = { "falseKey", "stringKey", "nullKey", "doubleKey" }; + final JSONObject jsonObject = new JSONObject(str); + + // validate JSON + final JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObjectByName.toString()); + assertTrue("expected 4 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 4); + assertTrue("expected \"falseKey\":false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"nullKey\":null", + null == JsonPath.read(doc, "$.nullKey")); + assertTrue("expected \"stringKey\":\"hello world!\"", + "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue( + "expected \"doubleKey\":-23.45e67", + Double.valueOf("-23.45e67").equals( + JsonPath.read(doc, "$.doubleKey"))); + } + + /** + * JSONObject built from a bean, but only using a null value. Nothing good + * is expected to happen. Expects NullPointerException + */ + @Test(expected = NullPointerException.class) + public void jsonObjectByNullBean() { + final MyBean myBean = null; + new JSONObject(myBean); + } + + /** + * JSONObjects can be built from a Map. In this test the map + * is null. the JSONObject(JsonTokener) ctor is not tested directly since it + * already has full coverage from other tests. + */ + @Test + public void jsonObjectByNullMap() { + final Map map = null; + final JSONObject jsonObject = new JSONObject(map); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + /** + * A bean is also an object. But in order to test the JSONObject ctor that + * takes an object and a list of names, this particular bean needs some + * public data members, which have been added to the class. + */ + @Test + public void jsonObjectByObjectAndNames() { + final String[] keys = { "publicString", "publicInt" }; + // just need a class that has public data members + final MyPublicClass myPublicClass = new MyPublicClass(); + final JSONObject jsonObject = new JSONObject(myPublicClass, keys); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 2 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 2); + assertTrue("expected \"publicString\":\"abc\"", + "abc".equals(JsonPath.read(doc, "$.publicString"))); + assertTrue("expected \"publicInt\":42", + Integer.valueOf(42).equals(JsonPath.read(doc, "$.publicInt"))); + } + + /** + * Exercise the JSONObject from resource bundle functionality. The test + * resource bundle is uncomplicated, but provides adequate test coverage. + */ + @Test + public void jsonObjectByResourceBundle() { + final JSONObject jsonObject = new JSONObject( + "org.json.junit.StringsResourceBundle", Locale.getDefault()); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 2 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 2); + assertTrue("expected 2 greetings items", + ((Map) JsonPath.read(doc, "$.greetings")).size() == 2); + assertTrue("expected \"hello\":\"Hello, \"", + "Hello, ".equals(JsonPath.read(doc, "$.greetings.hello"))); + assertTrue("expected \"world\":\"World!\"", + "World!".equals(JsonPath.read(doc, "$.greetings.world"))); + assertTrue("expected 2 farewells items", + ((Map) JsonPath.read(doc, "$.farewells")).size() == 2); + assertTrue("expected \"later\":\"Later, \"", + "Later, ".equals(JsonPath.read(doc, "$.farewells.later"))); + assertTrue("expected \"world\":\"World!\"", + "Alligator!".equals(JsonPath.read(doc, "$.farewells.gator"))); + } + + /** + * Exercise the JSONObject doubleToString() method + */ + @Test + public void jsonObjectDoubleToString() { + final String[] expectedStrs = { "1", "1", "-23.4", "-2.345E68", "null", + "null" }; + final Double[] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, + Double.NaN, Double.NEGATIVE_INFINITY }; + for (int i = 0; i < expectedStrs.length; ++i) { + final String actualStr = JSONObject.doubleToString(doubles[i]); + assertTrue("value expected [" + expectedStrs[i] + "] found [" + + actualStr + "]", expectedStrs[i].equals(actualStr)); + } + } + + /** + * Exercise the JSONObject increment() method. + */ + @Test + public void jsonObjectIncrement() { + final String str = "{" + "\"keyLong\":9999999991," + + "\"keyDouble\":1.1" + "}"; + final JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("keyInt"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); + /** + * JSONObject constructor won't handle these types correctly, but adding + * them via put works. + */ + jsonObject.put("keyFloat", new Float(1.1)); + jsonObject.put("keyBigInt", new BigInteger( + "123456789123456789123456789123456780")); + jsonObject.put("keyBigDec", new BigDecimal( + "123456789123456789123456789123456780.1")); + jsonObject.increment("keyFloat"); + jsonObject.increment("keyFloat"); + jsonObject.increment("keyBigInt"); + jsonObject.increment("keyBigDec"); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 6 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 6); + assertTrue("expected 3", + Integer.valueOf(3).equals(JsonPath.read(doc, "$.keyInt"))); + assertTrue( + "expected 9999999993", + Long.valueOf(9999999993L).equals( + JsonPath.read(doc, "$.keyLong"))); + assertTrue("expected 3.1", + Double.valueOf(3.1).equals(JsonPath.read(doc, "$.keyDouble"))); + assertTrue("expected 123456789123456789123456789123456781", + new BigInteger("123456789123456789123456789123456781") + .equals(JsonPath.read(doc, "$.keyBigInt"))); + assertTrue("expected 123456789123456789123456789123456781.1", + new BigDecimal("123456789123456789123456789123456781.1") + .equals(JsonPath.read(doc, "$.keyBigDec"))); + + /** + * Should work the same way on any platform! @see https://docs.oracle + * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is the + * effect of a float to double conversion and is inherent to the + * shortcomings of the IEEE 754 format, when converting 32-bit into + * double-precision 64-bit. Java type-casts float to double. A 32 bit + * float is type-casted to 64 bit double by simply appending zero-bits + * to the mantissa (and extended the signed exponent by 3 bits.) and + * there is no way to obtain more information than it is stored in the + * 32-bits float. + * + * Like 1/3 cannot be represented as base10 number because it is + * periodically, 1/5 (for example) cannot be represented as base2 number + * since it is periodically in base2 (take a look at + * http://www.h-schmidt.net/FloatConverter/) The same happens to 3.1, + * that decimal number (base10 representation) is periodic in base2 + * representation, therefore appending zero-bits is inaccurate. Only + * repeating the periodically occuring bits (0110) would be a proper + * conversion. However one cannot detect from a 32 bit IEE754 + * representation which bits would "repeat infinitely", since the + * missing bits would not fit into the 32 bit float, i.e. the + * information needed simply is not there! + */ + assertTrue( + "expected 3.0999999046325684", + Double.valueOf(3.0999999046325684).equals( + JsonPath.read(doc, "$.keyFloat"))); + + /** + * float f = 3.1f; double df = (double) f; double d = 3.1d; + * System.out.println + * (Integer.toBinaryString(Float.floatToRawIntBits(f))); + * System.out.println + * (Long.toBinaryString(Double.doubleToRawLongBits(df))); + * System.out.println + * (Long.toBinaryString(Double.doubleToRawLongBits(d))); + * + * - Float: seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm + * 1000000010001100110011001100110 - Double + * seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + * 10000000 10001100110011001100110 + * 100000000001000110011001100110011000000000000000000000000000000 + * 100000000001000110011001100110011001100110011001100110011001101 + */ + + /** + * Examples of well documented but probably unexpected behavior in java + * / with 32-bit float to 64-bit float conversion. + */ + assertFalse( + "Document unexpected behaviour with explicit type-casting float as double!", + 0.2f == 0.2d); + assertFalse("Document unexpected behaviour with implicit type-cast!", + 0.2f == 0.2d); + final Double d1 = new Double(1.1f); + final Double d2 = new Double("1.1f"); + assertFalse( + "Document implicit type cast from float to double before calling Double(double d) constructor", + d1.equals(d2)); + + assertTrue( + "Correctly converting float to double via base10 (string) representation!", + new Double(3.1d).equals(new Double(new Float(3.1f).toString()))); + + // Pinpointing the not so obvious "buggy" conversion from float to + // double in JSONObject + final JSONObject jo = new JSONObject(); + jo.put("bug", 3.1f); // will call put( String key, double value ) with + // implicit and "buggy" type-cast from float to + // double + assertFalse( + "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", + jo.get("bug").equals(new Double(3.1d))); + + final JSONObject inc = new JSONObject(); + inc.put("bug", new Float(3.1f)); // This will put in instance of Float + // into JSONObject, i.e. call put( + // String key, Object value ) + assertTrue("Everything is ok here!", inc.get("bug") instanceof Float); + inc.increment("bug"); // after adding 1, increment will call put( String + // key, double value ) with implicit and "buggy" + // type-cast from float to double! + // this.put(key, (Float) value + 1); + // 1. The (Object)value will be typecasted to (Float)value since it is + // an instanceof Float actually nothing is done. + // 2. Float instance will be autoboxed into float because the + operator + // will work on primitives not Objects! + // 3. A float+float operation will be performed and results into a float + // primitive. + // 4. There is no method that matches the signature put( String key, + // float value), java-compiler will choose the method + // put( String key, double value) and does an implicit type-cast(!) by + // appending zero-bits to the mantissa + assertTrue("JSONObject increment converts Float to Double", + jo.get("bug") instanceof Double); + // correct implementation (with change of behavior) would be: + // this.put(key, new Float((Float) value + 1)); + // Probably it would be better to deprecate the method and remove some + // day, while convenient processing the "payload" is not + // really in the the scope of a JSON-library (IMHO.) + + } + + /** + * The purpose for the static method getNames() methods are not clear. This + * method is not called from within JSON-Java. Most likely uses are to prep + * names arrays for: JSONObject(JSONObject jo, String[] names) * JSONObject(Object object, String names[]), */ @Test @@ -986,32 +863,27 @@ public class JSONObjectTest { JSONObject jsonObject; // getNames() from null JSONObject - assertTrue("null names from null Object", - null == JSONObject.getNames((Object)null)); + assertTrue("null names from null Object", + null == JSONObject.getNames((Object) null)); // getNames() from object with no fields - assertTrue("null names from Object with no fields", + assertTrue("null names from Object with no fields", null == JSONObject.getNames(new MyJsonString())); // getNames from new JSONOjbect jsonObject = new JSONObject(); - String [] names = JSONObject.getNames(jsonObject); + String[] names = JSONObject.getNames(jsonObject); assertTrue("names should be null", names == null); - // getNames() from empty JSONObject - String emptyStr = "{}"; + final String emptyStr = "{}"; jsonObject = new JSONObject(emptyStr); assertTrue("empty JSONObject should have null names", null == JSONObject.getNames(jsonObject)); // getNames() from JSONObject - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "}"; + final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," + + "\"stringKey\":\"hello world!\"," + "}"; jsonObject = new JSONObject(str); names = JSONObject.getNames(jsonObject); JSONArray jsonArray = new JSONArray(names); @@ -1032,10 +904,10 @@ public class JSONObjectTest { ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); /** - * getNames() from an enum with properties has an interesting result. - * It returns the enum values, not the selected enum properties + * getNames() from an enum with properties has an interesting result. It + * returns the enum values, not the selected enum properties */ - MyEnumField myEnumField = MyEnumField.VAL1; + final MyEnumField myEnumField = MyEnumField.VAL1; names = JSONObject.getNames(myEnumField); // validate JSON @@ -1044,22 +916,18 @@ public class JSONObjectTest { .parse(jsonArray.toString()); docList = JsonPath.read(doc, "$"); assertTrue("expected 3 items", docList.size() == 3); - assertTrue( - "expected to find VAL1", + assertTrue("expected to find VAL1", ((List) JsonPath.read(doc, "$[?(@=='VAL1')]")).size() == 1); - assertTrue( - "expected to find VAL2", + assertTrue("expected to find VAL2", ((List) JsonPath.read(doc, "$[?(@=='VAL2')]")).size() == 1); - assertTrue( - "expected to find VAL3", + assertTrue("expected to find VAL3", ((List) JsonPath.read(doc, "$[?(@=='VAL3')]")).size() == 1); /** - * A bean is also an object. But in order to test the static - * method getNames(), this particular bean needs some public - * data members. + * A bean is also an object. But in order to test the static method + * getNames(), this particular bean needs some public data members. */ - MyPublicClass myPublicClass = new MyPublicClass(); + final MyPublicClass myPublicClass = new MyPublicClass(); names = JSONObject.getNames(myPublicClass); // validate JSON @@ -1068,165 +936,242 @@ public class JSONObjectTest { .parse(jsonArray.toString()); docList = JsonPath.read(doc, "$"); assertTrue("expected 2 items", docList.size() == 2); - assertTrue( - "expected to find publicString", - ((List) JsonPath.read(doc, "$[?(@=='publicString')]")).size() == 1); + assertTrue("expected to find publicString", ((List) JsonPath.read( + doc, "$[?(@=='publicString')]")).size() == 1); assertTrue( "expected to find publicInt", ((List) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1); } /** - * Populate a JSONArray from an empty JSONObject names() method. - * It should be empty. - */ - @Test - public void emptyJsonObjectNamesToJsonAray() { - JSONObject jsonObject = new JSONObject(); - JSONArray jsonArray = jsonObject.names(); - assertTrue("jsonArray should be null", jsonArray == null); - } - - /** - * Populate a JSONArray from a JSONObject names() method. - * Confirm that it contains the expected names. + * Populate a JSONArray from a JSONObject names() method. Confirm that it + * contains the expected names. */ @Test public void jsonObjectNamesToJsonAray() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "}"; + final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," + + "\"stringKey\":\"hello world!\"," + "}"; - JSONObject jsonObject = new JSONObject(str); - JSONArray jsonArray = jsonObject.names(); + final JSONObject jsonObject = new JSONObject(str); + final JSONArray jsonArray = jsonObject.names(); // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected to find trueKey", ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); - assertTrue("expected to find falseKey", ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); - assertTrue("expected to find stringKey", ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + assertTrue("expected 3 top level items", + ((List) JsonPath.read(doc, "$")).size() == 3); + assertTrue( + "expected to find trueKey", + ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); + assertTrue( + "expected to find falseKey", + ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); + assertTrue( + "expected to find stringKey", + ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); } /** - * Exercise the JSONObject increment() method. + * Tests how JSONObject get[type] handles incorrect types */ @Test - public void jsonObjectIncrement() { - String str = - "{"+ - "\"keyLong\":9999999991,"+ - "\"keyDouble\":1.1"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.increment("keyInt"); - jsonObject.increment("keyInt"); - jsonObject.increment("keyLong"); - jsonObject.increment("keyDouble"); - jsonObject.increment("keyInt"); - jsonObject.increment("keyLong"); - jsonObject.increment("keyDouble"); - /** - * JSONObject constructor won't handle these types correctly, but - * adding them via put works. - */ - jsonObject.put("keyFloat", new Float(1.1)); - jsonObject.put("keyBigInt", new BigInteger("123456789123456789123456789123456780")); - jsonObject.put("keyBigDec", new BigDecimal("123456789123456789123456789123456780.1")); - jsonObject.increment("keyFloat"); - jsonObject.increment("keyFloat"); - jsonObject.increment("keyBigInt"); - jsonObject.increment("keyBigDec"); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.keyInt"))); - assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(JsonPath.read(doc, "$.keyLong"))); - assertTrue("expected 3.1", Double.valueOf(3.1).equals(JsonPath.read(doc, "$.keyDouble"))); - assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(JsonPath.read(doc, "$.keyBigInt"))); - assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(JsonPath.read(doc, "$.keyBigDec"))); + public void jsonObjectNonAndWrongValues() { + final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," + + "\"trueStrKey\":\"true\"," + "\"falseStrKey\":\"false\"," + + "\"stringKey\":\"hello world!\"," + "\"intKey\":42," + + "\"intStrKey\":\"43\"," + "\"longKey\":1234567890123456789," + + "\"longStrKey\":\"987654321098765432\"," + + "\"doubleKey\":-23.45e7," + "\"doubleStrKey\":\"00001.000\"," + + "\"arrayKey\":[0,1,2]," + + "\"objectKey\":{\"myKey\":\"myVal\"}" + "}"; + final JSONObject jsonObject = new JSONObject(str); + try { + jsonObject.getBoolean("nonKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } + try { + jsonObject.getBoolean("stringKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a Boolean.".equals(e + .getMessage())); + } + try { + jsonObject.getString("nonKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } + try { + jsonObject.getString("trueKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"trueKey\"] not a string.".equals(e + .getMessage())); + } + try { + jsonObject.getDouble("nonKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } + try { + jsonObject.getDouble("stringKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a number.".equals(e + .getMessage())); + } + try { + jsonObject.getInt("nonKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } + try { + jsonObject.getInt("stringKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not an int.".equals(e + .getMessage())); + } + try { + jsonObject.getLong("nonKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } + try { + jsonObject.getLong("stringKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a long.".equals(e + .getMessage())); + } + try { + jsonObject.getJSONArray("nonKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } + try { + jsonObject.getJSONArray("stringKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a JSONArray.".equals(e + .getMessage())); + } + try { + jsonObject.getJSONObject("nonKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } + try { + jsonObject.getJSONObject("stringKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a JSONObject.".equals(e + .getMessage())); + } + } + /** + * JSON null is not the same as Java null. This test examines the + * differences in how they are handled by JSON-java. + */ + @Test + public void jsonObjectNullOperations() { /** - * Should work the same way on any platform! @see https://docs.oracle - * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is the - * effect of a float to double conversion and is inherent to the - * shortcomings of the IEEE 754 format, when converting 32-bit into - * double-precision 64-bit. Java type-casts float to double. A 32 bit - * float is type-casted to 64 bit double by simply appending zero-bits - * to the mantissa (and extended the signed exponent by 3 bits.) and - * there is no way to obtain more information than it is stored in the - * 32-bits float. - * - * Like 1/3 cannot be represented as base10 number because it is - * periodically, 1/5 (for example) cannot be represented as base2 number - * since it is periodically in base2 (take a look at - * http://www.h-schmidt.net/FloatConverter/) The same happens to 3.1, - * that decimal number (base10 representation) is periodic in base2 - * representation, therefore appending zero-bits is inaccurate. Only - * repeating the periodically occuring bits (0110) would be a proper - * conversion. However one cannot detect from a 32 bit IEE754 - * representation which bits would "repeat infinitely", since the - * missing bits would not fit into the 32 bit float, i.e. the - * information needed simply is not there! - */ - assertTrue("expected 3.0999999046325684", Double.valueOf(3.0999999046325684).equals(JsonPath.read(doc, "$.keyFloat"))); - - /** - * float f = 3.1f; double df = (double) f; double d = 3.1d; - * System.out.println - * (Integer.toBinaryString(Float.floatToRawIntBits(f))); - * System.out.println - * (Long.toBinaryString(Double.doubleToRawLongBits(df))); - * System.out.println - * (Long.toBinaryString(Double.doubleToRawLongBits(d))); - * - * - Float: - * seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm - * 1000000010001100110011001100110 - * - Double - * seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * 10000000 10001100110011001100110 - * 100000000001000110011001100110011000000000000000000000000000000 - * 100000000001000110011001100110011001100110011001100110011001101 + * The Javadoc for JSONObject.NULL states: "JSONObject.NULL is + * equivalent to the value that JavaScript calls null, whilst Java's + * null is equivalent to the value that JavaScript calls undefined." + * + * Standard ECMA-262 6th Edition / June 2015 (included to help explain + * the javadoc): undefined value: primitive value used when a variable + * has not been assigned a value Undefined type: type whose sole value + * is the undefined value null value: primitive value that represents + * the intentional absence of any object value Null type: type whose + * sole value is the null value Java SE8 language spec (included to help + * explain the javadoc): The Kinds of Types and Values ... There is also + * a special null type, the type of the expression null, which has no + * name. Because the null type has no name, it is impossible to declare + * a variable of the null type or to cast to the null type. The null + * reference is the only possible value of an expression of null type. + * The null reference can always be assigned or cast to any reference + * type. In practice, the programmer can ignore the null type and just + * pretend that null is merely a special literal that can be of any + * reference type. Extensible Markup Language (XML) 1.0 Fifth Edition / + * 26 November 2008 No mention of null ECMA-404 1st Edition / October + * 2013: JSON Text ... These are three literal name tokens: ... null + * + * There seems to be no best practice to follow, it's all about what we + * want the code to do. */ + // add JSONObject.NULL then convert to string in the manner of + // XML.toString() + final JSONObject jsonObjectJONull = new JSONObject(); + Object obj = JSONObject.NULL; + jsonObjectJONull.put("key", obj); + Object value = jsonObjectJONull.opt("key"); + assertTrue("opt() JSONObject.NULL should find JSONObject.NULL", + obj.equals(value)); + value = jsonObjectJONull.get("key"); + assertTrue("get() JSONObject.NULL should find JSONObject.NULL", + obj.equals(value)); + if (value == null) { + value = ""; + } + String string = value instanceof String ? (String) value : null; + assertTrue("XML toString() should convert JSONObject.NULL to null", + string == null); + + // now try it with null + final JSONObject jsonObjectNull = new JSONObject(); + obj = null; + jsonObjectNull.put("key", obj); + value = jsonObjectNull.opt("key"); + assertTrue("opt() null should find null", value == null); + if (value == null) { + value = ""; + } + string = value instanceof String ? (String) value : null; + assertTrue("should convert null to empty string", "".equals(string)); + try { + value = jsonObjectNull.get("key"); + assertTrue("get() null should throw exception", false); + } catch (final Exception ignored) { + } + /** - * Examples of well documented but probably unexpected behavior in - * java / with 32-bit float to 64-bit float conversion. - */ - assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d ); - assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d ); - Double d1 = new Double( 1.1f ); - Double d2 = new Double( "1.1f" ); - assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); - - assertTrue( "Correctly converting float to double via base10 (string) representation!", new Double( 3.1d ).equals( new Double( new Float( 3.1f ).toString() ) ) ); - - // Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject - JSONObject jo = new JSONObject(); - jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double - assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); - - JSONObject inc = new JSONObject(); - inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) - assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); - inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! - // this.put(key, (Float) value + 1); - // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. - // 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects! - // 3. A float+float operation will be performed and results into a float primitive. - // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method - // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa - assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Double ); - // correct implementation (with change of behavior) would be: - // this.put(key, new Float((Float) value + 1)); - // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not - // really in the the scope of a JSON-library (IMHO.) - + * XML.toString() then goes on to do something with the value if the key + * val is "content", then value.toString() will be called. This will + * evaluate to "null" for JSONObject.NULL, and the empty string for + * null. But if the key is anything else, then JSONObject.NULL will be + * emitted as null and null will be emitted as "" + */ + final String sJONull = XML.toString(jsonObjectJONull); + assertTrue("JSONObject.NULL should emit a null value", + "null".equals(sJONull)); + final String sNull = XML.toString(jsonObjectNull); + assertTrue("null should emit an empty string", "".equals(sNull)); } /** @@ -1236,449 +1181,22 @@ public class JSONObjectTest { public void jsonObjectNumberToString() { String str; Double dVal; - Integer iVal = 1; + final Integer iVal = 1; str = JSONObject.numberToString(iVal); - assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); + assertTrue("expected " + iVal + " actual " + str, iVal.toString() + .equals(str)); dVal = 12.34; str = JSONObject.numberToString(dVal); - assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + assertTrue("expected " + dVal + " actual " + str, dVal.toString() + .equals(str)); dVal = 12.34e27; str = JSONObject.numberToString(dVal); - assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + assertTrue("expected " + dVal + " actual " + str, dVal.toString() + .equals(str)); // trailing .0 is truncated, so it doesn't quite match toString() dVal = 5000000.0000000; str = JSONObject.numberToString(dVal); - assertTrue("expected 5000000 actual "+str, str.equals("5000000")); - } - - /** - * Exercise JSONObject put() and similar() methods - */ - @Test - public void jsonObjectPut() { - String expectedStr = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{"+ - "\"myKey1\":\"myVal1\","+ - "\"myKey2\":\"myVal2\","+ - "\"myKey3\":\"myVal3\","+ - "\"myKey4\":\"myVal4\""+ - "}"+ - "}"; - JSONObject jsonObject = new JSONObject(); - jsonObject.put("trueKey", true); - jsonObject.put("falseKey", false); - Integer [] intArray = { 0, 1, 2 }; - jsonObject.put("arrayKey", Arrays.asList(intArray)); - Map myMap = new HashMap(); - myMap.put("myKey1", "myVal1"); - myMap.put("myKey2", "myVal2"); - myMap.put("myKey3", "myVal3"); - myMap.put("myKey4", "myVal4"); - jsonObject.put("objectKey", myMap); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); - assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); - assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); - assertTrue("expected myVal1", "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); - assertTrue("expected myVal2", "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); - assertTrue("expected myVal3", "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); - assertTrue("expected myVal4", "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); - - jsonObject.remove("trueKey"); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - assertTrue("unequal jsonObjects should not be similar", - !jsonObject.similar(expectedJsonObject)); - assertTrue("jsonObject should not be similar to jsonArray", - !jsonObject.similar(new JSONArray())); - - String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; - String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; - JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); - JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); - assertTrue("different values should not be similar", - !aCompareValueJsonObject.similar(bCompareValueJsonObject)); - - String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; - String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; - JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); - JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); - assertTrue("different nested JSONObjects should not be similar", - !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); - - String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; - String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; - JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); - JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); - assertTrue("different nested JSONArrays should not be similar", - !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); - } - - /** - * Exercise JSONObject toString() method - */ - @Test - public void jsonObjectToString() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{"+ - "\"myKey1\":\"myVal1\","+ - "\"myKey2\":\"myVal2\","+ - "\"myKey3\":\"myVal3\","+ - "\"myKey4\":\"myVal4\""+ - "}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); - assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); - assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); - assertTrue("expected myVal1", "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); - assertTrue("expected myVal2", "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); - assertTrue("expected myVal3", "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); - assertTrue("expected myVal4", "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); - } - - /** - * Explores how JSONObject handles maps. Insert a string/string map - * as a value in a JSONObject. It will remain a map. Convert the - * JSONObject to string, then create a new JSONObject from the string. - * In the new JSONObject, the value will be stored as a nested JSONObject. - * Confirm that map and nested JSONObject have the same contents. - */ - @Test - public void jsonObjectToStringSuppressWarningOnCastToMap() { - JSONObject jsonObject = new JSONObject(); - Map map = new HashMap<>(); - map.put("abc", "def"); - jsonObject.put("key", map); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 1 key item", ((Map)(JsonPath.read(doc, "$.key"))).size() == 1); - assertTrue("expected def", "def".equals(JsonPath.read(doc, "$.key.abc"))); - } - - /** - * Explores how JSONObject handles collections. Insert a string collection - * as a value in a JSONObject. It will remain a collection. Convert the - * JSONObject to string, then create a new JSONObject from the string. - * In the new JSONObject, the value will be stored as a nested JSONArray. - * Confirm that collection and nested JSONArray have the same contents. - */ - @Test - public void jsonObjectToStringSuppressWarningOnCastToCollection() { - JSONObject jsonObject = new JSONObject(); - Collection collection = new ArrayList(); - collection.add("abc"); - // ArrayList will be added as an object - jsonObject.put("key", collection); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 1 key item", ((List)(JsonPath.read(doc, "$.key"))).size() == 1); - assertTrue("expected abc", "abc".equals(JsonPath.read(doc, "$.key[0]"))); - } - - /** - * Exercises the JSONObject.valueToString() method for various types - */ - @Test - public void valueToString() { - - assertTrue("null valueToString() incorrect", - "null".equals(JSONObject.valueToString(null))); - MyJsonString jsonString = new MyJsonString(); - assertTrue("jsonstring valueToString() incorrect", - "my string".equals(JSONObject.valueToString(jsonString))); - assertTrue("boolean valueToString() incorrect", - "true".equals(JSONObject.valueToString(Boolean.TRUE))); - assertTrue("non-numeric double", - "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); - String jsonObjectStr = - "{"+ - "\"key1\":\"val1\","+ - "\"key2\":\"val2\","+ - "\"key3\":\"val3\""+ - "}"; - JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("jsonObject valueToString() incorrect", - JSONObject.valueToString(jsonObject).equals(jsonObject.toString())); - String jsonArrayStr = - "[1,2,3]"; - JSONArray jsonArray = new JSONArray(jsonArrayStr); - assertTrue("jsonArra valueToString() incorrect", - JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); - Map map = new HashMap(); - map.put("key1", "val1"); - map.put("key2", "val2"); - map.put("key3", "val3"); - assertTrue("map valueToString() incorrect", - jsonObject.toString().equals(JSONObject.valueToString(map))); - Collection collection = new ArrayList(); - collection.add(new Integer(1)); - collection.add(new Integer(2)); - collection.add(new Integer(3)); - assertTrue("collection valueToString() expected: "+ - jsonArray.toString()+ " actual: "+ - JSONObject.valueToString(collection), - jsonArray.toString().equals(JSONObject.valueToString(collection))); - Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; - assertTrue("array valueToString() incorrect", - jsonArray.toString().equals(JSONObject.valueToString(array))); - } - - /** - * Confirm that https://github.com/douglascrockford/JSON-java/issues/167 is fixed. - * The following code was throwing a ClassCastException in the - * JSONObject(Map) constructor - */ - @Test - public void valueToStringConfirmException() { - Map myMap = new HashMap(); - myMap.put(1, "myValue"); - // this is the test, it should not throw an exception - String str = JSONObject.valueToString(myMap); - // confirm result, just in case - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1"))); - } - - /** - * Exercise the JSONObject wrap() method. Sometimes wrap() will change - * the object being wrapped, other times not. The purpose of wrap() is - * to ensure the value is packaged in a way that is compatible with how - * a JSONObject value or JSONArray value is supposed to be stored. - */ - @Test - public void wrapObject() { - // wrap(null) returns NULL - assertTrue("null wrap() incorrect", - JSONObject.NULL == JSONObject.wrap(null)); - - // wrap(Integer) returns Integer - Integer in = new Integer(1); - assertTrue("Integer wrap() incorrect", - in == JSONObject.wrap(in)); - - /** - * This test is to document the preferred behavior if BigDecimal is - * supported. Previously bd returned as a string, since it - * is recognized as being a Java package class. Now with explicit - * support for big numbers, it remains a BigDecimal - */ - Object bdWrap = JSONObject.wrap(BigDecimal.ONE); - assertTrue("BigDecimal.ONE evaluates to ONE", - bdWrap.equals(BigDecimal.ONE)); - - // wrap JSONObject returns JSONObject - String jsonObjectStr = - "{"+ - "\"key1\":\"val1\","+ - "\"key2\":\"val2\","+ - "\"key3\":\"val3\""+ - "}"; - JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("JSONObject wrap() incorrect", - jsonObject == JSONObject.wrap(jsonObject)); - - // wrap collection returns JSONArray - Collection collection = new ArrayList(); - collection.add(new Integer(1)); - collection.add(new Integer(2)); - collection.add(new Integer(3)); - JSONArray jsonArray = (JSONArray) (JSONObject.wrap(collection)); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); - - // wrap Array returns JSONArray - Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; - JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); - - // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); - - // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); - - // wrap map returns JSONObject - Map map = new HashMap(); - map.put("key1", "val1"); - map.put("key2", "val2"); - map.put("key3", "val3"); - JSONObject mapJsonObject = (JSONObject) (JSONObject.wrap(map)); - - // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString()); - assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected val1", "val1".equals(JsonPath.read(doc, "$.key1"))); - assertTrue("expected val2", "val2".equals(JsonPath.read(doc, "$.key2"))); - assertTrue("expected val3", "val3".equals(JsonPath.read(doc, "$.key3"))); - } - - /** - * Explore how JSONObject handles parsing errors. - */ - @Test - public void jsonObjectParsingErrors() { - try { - // does not start with '{' - String str = "abc"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "A JSONObject text must begin with '{' at 1 [character 2 line 1]". - equals(e.getMessage())); - } - try { - // does not end with '}' - String str = "{"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "A JSONObject text must end with '}' at 2 [character 3 line 1]". - equals(e.getMessage())); - } - try { - // key with no ':' - String str = "{\"myKey\" = true}"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Expected a ':' after a key at 10 [character 11 line 1]". - equals(e.getMessage())); - } - try { - // entries with no ',' separator - String str = "{\"myKey\":true \"myOtherKey\":false}"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Expected a ',' or '}' at 15 [character 16 line 1]". - equals(e.getMessage())); - } - try { - // append to wrong key - String str = "{\"myKey\":true, \"myOtherKey\":false}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.append("myKey", "hello"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[myKey] is not a JSONArray.". - equals(e.getMessage())); - } - try { - // increment wrong key - String str = "{\"myKey\":true, \"myOtherKey\":false}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.increment("myKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Unable to increment [\"myKey\"].". - equals(e.getMessage())); - } - try { - // invalid key - String str = "{\"myKey\":true, \"myOtherKey\":false}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.get(null); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Null key.". - equals(e.getMessage())); - } - try { - // invalid numberToString() - JSONObject.numberToString((Number)null); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Null pointer". - equals(e.getMessage())); - } - try { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, 0); - assertTrue("Expected an exception", false); - } catch (NullPointerException ignored) { - } - try { - // multiple putOnce key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.putOnce("hello", "world"); - jsonObject.putOnce("hello", "world!"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("", true); - } - try { - // test validity of invalid double - JSONObject.testValidity(Double.NaN); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("", true); - } - try { - // test validity of invalid float - JSONObject.testValidity(Float.NEGATIVE_INFINITY); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("", true); - } - } - - /** - * Confirm behavior when putOnce() is called with null parameters - */ - @Test - public void jsonObjectPutOnceNull() { - JSONObject jsonObject = new JSONObject(); - jsonObject.putOnce(null, null); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("expected 5000000 actual " + str, str.equals("5000000")); } /** @@ -1687,8 +1205,8 @@ public class JSONObjectTest { @Test public void jsonObjectOptDefault() { - String str = "{\"myKey\": \"myval\"}"; - JSONObject jsonObject = new JSONObject(str); + final String str = "{\"myKey\": \"myval\"}"; + final JSONObject jsonObject = new JSONObject(str); assertTrue("optBoolean() should return default boolean", Boolean.TRUE == jsonObject.optBoolean("myKey", Boolean.TRUE)); @@ -1704,6 +1222,207 @@ public class JSONObjectTest { "hi".equals(jsonObject.optString("hiKey", "hi"))); } + /** + * Explore how JSONObject handles parsing errors. + */ + @Test + public void jsonObjectParsingErrors() { + try { + // does not start with '{' + final String str = "abc"; + new JSONObject(str); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "A JSONObject text must begin with '{' at 1 [character 2 line 1]" + .equals(e.getMessage())); + } + try { + // does not end with '}' + final String str = "{"; + new JSONObject(str); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "A JSONObject text must end with '}' at 2 [character 3 line 1]" + .equals(e.getMessage())); + } + try { + // key with no ':' + final String str = "{\"myKey\" = true}"; + new JSONObject(str); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "Expected a ':' after a key at 10 [character 11 line 1]" + .equals(e.getMessage())); + } + try { + // entries with no ',' separator + final String str = "{\"myKey\":true \"myOtherKey\":false}"; + new JSONObject(str); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "Expected a ',' or '}' at 15 [character 16 line 1]" + .equals(e.getMessage())); + } + try { + // append to wrong key + final String str = "{\"myKey\":true, \"myOtherKey\":false}"; + final JSONObject jsonObject = new JSONObject(str); + jsonObject.append("myKey", "hello"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[myKey] is not a JSONArray.".equals(e + .getMessage())); + } + try { + // increment wrong key + final String str = "{\"myKey\":true, \"myOtherKey\":false}"; + final JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("myKey"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "Unable to increment [\"myKey\"].".equals(e.getMessage())); + } + try { + // invalid key + final String str = "{\"myKey\":true, \"myOtherKey\":false}"; + final JSONObject jsonObject = new JSONObject(str); + jsonObject.get(null); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "Null key.".equals(e.getMessage())); + } + try { + // invalid numberToString() + JSONObject.numberToString((Number) null); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("Expecting an exception message", + "Null pointer".equals(e.getMessage())); + } + try { + // null put key + final JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0); + assertTrue("Expected an exception", false); + } catch (final NullPointerException ignored) { + } + try { + // multiple putOnce key + final JSONObject jsonObject = new JSONObject("{}"); + jsonObject.putOnce("hello", "world"); + jsonObject.putOnce("hello", "world!"); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("", true); + } + try { + // test validity of invalid double + JSONObject.testValidity(Double.NaN); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("", true); + } + try { + // test validity of invalid float + JSONObject.testValidity(Float.NEGATIVE_INFINITY); + assertTrue("Expected an exception", false); + } catch (final JSONException e) { + assertTrue("", true); + } + } + + /** + * Exercise JSONObject put() and similar() methods + */ + @Test + public void jsonObjectPut() { + final String expectedStr = "{" + "\"trueKey\":true," + + "\"falseKey\":false," + "\"arrayKey\":[0,1,2]," + + "\"objectKey\":{" + "\"myKey1\":\"myVal1\"," + + "\"myKey2\":\"myVal2\"," + "\"myKey3\":\"myVal3\"," + + "\"myKey4\":\"myVal4\"" + "}" + "}"; + final JSONObject jsonObject = new JSONObject(); + jsonObject.put("trueKey", true); + jsonObject.put("falseKey", false); + final Integer[] intArray = { 0, 1, 2 }; + jsonObject.put("arrayKey", Arrays.asList(intArray)); + final Map myMap = new HashMap(); + myMap.put("myKey1", "myVal1"); + myMap.put("myKey2", "myVal2"); + myMap.put("myKey3", "myVal3"); + myMap.put("myKey4", "myVal4"); + jsonObject.put("objectKey", myMap); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 4 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 4); + assertTrue("expected true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected 3 arrayKey items", + ((List) JsonPath.read(doc, "$.arrayKey")).size() == 3); + assertTrue("expected 0", + Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); + assertTrue("expected 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); + assertTrue("expected 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + assertTrue("expected 4 objectKey items", + ((Map) JsonPath.read(doc, "$.objectKey")).size() == 4); + assertTrue("expected myVal1", + "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); + assertTrue("expected myVal2", + "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); + assertTrue("expected myVal3", + "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); + assertTrue("expected myVal4", + "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); + + jsonObject.remove("trueKey"); + final JSONObject expectedJsonObject = new JSONObject(expectedStr); + assertTrue("unequal jsonObjects should not be similar", + !jsonObject.similar(expectedJsonObject)); + assertTrue("jsonObject should not be similar to jsonArray", + !jsonObject.similar(new JSONArray())); + + final String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; + final String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; + final JSONObject aCompareValueJsonObject = new JSONObject( + aCompareValueStr); + final JSONObject bCompareValueJsonObject = new JSONObject( + bCompareValueStr); + assertTrue("different values should not be similar", + !aCompareValueJsonObject.similar(bCompareValueJsonObject)); + + final String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; + final String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; + final JSONObject aCompareObjectJsonObject = new JSONObject( + aCompareObjectStr); + final JSONObject bCompareObjectJsonObject = new JSONObject( + bCompareObjectStr); + assertTrue("different nested JSONObjects should not be similar", + !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); + + final String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; + final String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; + final JSONObject aCompareArrayJsonObject = new JSONObject( + aCompareArrayStr); + final JSONObject bCompareArrayJsonObject = new JSONObject( + bCompareArrayStr); + assertTrue("different nested JSONArrays should not be similar", + !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); + } + /** * Confirm behavior when JSONObject put(key, null object) is called */ @@ -1711,11 +1430,11 @@ public class JSONObjectTest { public void jsonObjectputNull() { // put null should remove the item. - String str = "{\"myKey\": \"myval\"}"; - JSONObject jsonObjectRemove = new JSONObject(str); + final String str = "{\"myKey\": \"myval\"}"; + final JSONObject jsonObjectRemove = new JSONObject(str); jsonObjectRemove.remove("myKey"); - JSONObject jsonObjectPutNull = new JSONObject(str); + final JSONObject jsonObjectPutNull = new JSONObject(str); jsonObjectPutNull.put("myKey", (Object) null); // validate JSON @@ -1724,9 +1443,18 @@ public class JSONObjectTest { } /** - * Exercise JSONObject quote() method - * This purpose of quote() is to ensure that for strings with embedded - * quotes, the quotes are properly escaped. + * Confirm behavior when putOnce() is called with null parameters + */ + @Test + public void jsonObjectPutOnceNull() { + final JSONObject jsonObject = new JSONObject(); + jsonObject.putOnce(null, null); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + /** + * Exercise JSONObject quote() method This purpose of quote() is to ensure + * that for strings with embedded quotes, the quotes are properly escaped. */ @Test public void jsonObjectQuote() { @@ -1734,50 +1462,281 @@ public class JSONObjectTest { str = ""; String quotedStr; quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found "+quotedStr, + assertTrue("quote() expected escaped quotes, found " + quotedStr, "\"\"".equals(quotedStr)); str = "\"\""; quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found "+quotedStr, + assertTrue("quote() expected escaped quotes, found " + quotedStr, "\"\\\"\\\"\"".equals(quotedStr)); str = ") JsonPath.read(doc, "$")).size() == 4); + assertTrue("expected true", + Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected false", + Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected 3 arrayKey items", + ((List) JsonPath.read(doc, "$.arrayKey")).size() == 3); + assertTrue("expected 0", + Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); + assertTrue("expected 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); + assertTrue("expected 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + assertTrue("expected 4 objectKey items", + ((Map) JsonPath.read(doc, "$.objectKey")).size() == 4); + assertTrue("expected myVal1", + "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); + assertTrue("expected myVal2", + "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); + assertTrue("expected myVal3", + "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); + assertTrue("expected myVal4", + "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); + } + + /** + * Explores how JSONObject handles collections. Insert a string collection + * as a value in a JSONObject. It will remain a collection. Convert the + * JSONObject to string, then create a new JSONObject from the string. In + * the new JSONObject, the value will be stored as a nested JSONArray. + * Confirm that collection and nested JSONArray have the same contents. + */ + @Test + public void jsonObjectToStringSuppressWarningOnCastToCollection() { + final JSONObject jsonObject = new JSONObject(); + final Collection collection = new ArrayList(); + collection.add("abc"); + // ArrayList will be added as an object + jsonObject.put("key", collection); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 1 top level item", + ((Map) JsonPath.read(doc, "$")).size() == 1); + assertTrue("expected 1 key item", + ((List) JsonPath.read(doc, "$.key")).size() == 1); + assertTrue("expected abc", "abc".equals(JsonPath.read(doc, "$.key[0]"))); + } + + /** + * Explores how JSONObject handles maps. Insert a string/string map as a + * value in a JSONObject. It will remain a map. Convert the JSONObject to + * string, then create a new JSONObject from the string. In the new + * JSONObject, the value will be stored as a nested JSONObject. Confirm that + * map and nested JSONObject have the same contents. + */ + @Test + public void jsonObjectToStringSuppressWarningOnCastToMap() { + final JSONObject jsonObject = new JSONObject(); + final Map map = new HashMap<>(); + map.put("abc", "def"); + jsonObject.put("key", map); + + // validate JSON + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonObject.toString()); + assertTrue("expected 1 top level item", + ((Map) JsonPath.read(doc, "$")).size() == 1); + assertTrue("expected 1 key item", + ((Map) JsonPath.read(doc, "$.key")).size() == 1); + assertTrue("expected def", + "def".equals(JsonPath.read(doc, "$.key.abc"))); + } + + /** + * Exercise some JSONObject get[type] and opt[type] methods + */ + @Test + public void jsonObjectValues() { + final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," + + "\"trueStrKey\":\"true\"," + "\"falseStrKey\":\"false\"," + + "\"stringKey\":\"hello world!\"," + "\"intKey\":42," + + "\"intStrKey\":\"43\"," + "\"longKey\":1234567890123456789," + + "\"longStrKey\":\"987654321098765432\"," + + "\"doubleKey\":-23.45e7," + "\"doubleStrKey\":\"00001.000\"," + + "\"arrayKey\":[0,1,2]," + + "\"objectKey\":{\"myKey\":\"myVal\"}" + "}"; + final JSONObject jsonObject = new JSONObject(str); + assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); + assertTrue("opt trueKey should be true", + jsonObject.optBoolean("trueKey")); + assertTrue("falseKey should be false", + !jsonObject.getBoolean("falseKey")); + assertTrue("trueStrKey should be true", + jsonObject.getBoolean("trueStrKey")); + assertTrue("trueStrKey should be true", + jsonObject.optBoolean("trueStrKey")); + assertTrue("falseStrKey should be false", + !jsonObject.getBoolean("falseStrKey")); + assertTrue("stringKey should be string", + jsonObject.getString("stringKey").equals("hello world!")); + assertTrue("doubleKey should be double", + jsonObject.getDouble("doubleKey") == -23.45e7); + assertTrue("doubleStrKey should be double", + jsonObject.getDouble("doubleStrKey") == 1); + assertTrue("opt doubleKey should be double", + jsonObject.optDouble("doubleKey") == -23.45e7); + assertTrue("opt doubleKey with Default should be double", + jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); + assertTrue("intKey should be int", jsonObject.optInt("intKey") == 42); + assertTrue("opt intKey should be int", + jsonObject.optInt("intKey", 0) == 42); + assertTrue("opt intKey with default should be int", + jsonObject.getInt("intKey") == 42); + assertTrue("intStrKey should be int", + jsonObject.getInt("intStrKey") == 43); + assertTrue("longKey should be long", + jsonObject.getLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey should be long", + jsonObject.optLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey with default should be long", + jsonObject.optLong("longKey", 0) == 1234567890123456789L); + assertTrue("longStrKey should be long", + jsonObject.getLong("longStrKey") == 987654321098765432L); + assertTrue("xKey should not exist", jsonObject.isNull("xKey")); + assertTrue("stringKey should exist", jsonObject.has("stringKey")); + assertTrue("opt stringKey should string", + jsonObject.optString("stringKey").equals("hello world!")); + assertTrue("opt stringKey with default should string", jsonObject + .optString("stringKey", "not found").equals("hello world!")); + JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); + assertTrue("arrayKey should be JSONArray", jsonArray.getInt(0) == 0 + && jsonArray.getInt(1) == 1 && jsonArray.getInt(2) == 2); + jsonArray = jsonObject.optJSONArray("arrayKey"); + assertTrue("opt arrayKey should be JSONArray", jsonArray.getInt(0) == 0 + && jsonArray.getInt(1) == 1 && jsonArray.getInt(2) == 2); + final JSONObject jsonObjectInner = jsonObject + .getJSONObject("objectKey"); + assertTrue("objectKey should be JSONObject", + jsonObjectInner.get("myKey").equals("myVal")); + } + + /** + * This test documents numeric values which could be numerically handled as + * BigDecimal or BigInteger. It helps determine what outputs will change if + * those types are supported. + */ + @Test + public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { + // Valid JSON Numbers, probably should return BigDecimal or BigInteger + // objects + final String str = "{" + "\"numberWithDecimals\":299792.457999999984," + + "\"largeNumber\":12345678901234567890," + + "\"preciseNumber\":0.2000000000000000111," + + "\"largeExponent\":-23.45e2327" + "}"; + final JSONObject jsonObject = new JSONObject(str); + // Comes back as a double, but loses precision + assertTrue( + "numberWithDecimals currently evaluates to double 299792.458", + jsonObject.get("numberWithDecimals").equals( + new Double("299792.458"))); + Object obj = jsonObject.get("largeNumber"); + assertTrue("largeNumber currently evaluates to string", + "12345678901234567890".equals(obj)); + // comes back as a double but loses precision + assertTrue("preciseNumber currently evaluates to double 0.2", + jsonObject.get("preciseNumber").equals(new Double(0.2))); + obj = jsonObject.get("largeExponent"); + assertTrue("largeExponent should currently evaluates as a string", + "-23.45e2327".equals(obj)); + } + + /** + * Confirm behavior when JSONObject stringToValue() is called for an empty + * string */ @Test public void stringToValue() { - String str = ""; - String valueStr = (String)(JSONObject.stringToValue(str)); - assertTrue("stringToValue() expected empty String, found "+valueStr, + final String str = ""; + final String valueStr = (String) JSONObject.stringToValue(str); + assertTrue("stringToValue() expected empty String, found " + valueStr, "".equals(valueStr)); } + /** + * Check whether JSONObject handles large or high precision numbers + * correctly + */ + @Test + public void stringToValueNumbersTest() { + assertTrue("-0 Should be a Double!", + JSONObject.stringToValue("-0") instanceof Double); + assertTrue("-0 Should be a Double!", + JSONObject.stringToValue("-0.0") instanceof Double); + assertTrue("'-' Should be a String!", + JSONObject.stringToValue("-") instanceof String); + assertTrue("0.2 should be a Double!", + JSONObject.stringToValue("0.2") instanceof Double); + assertTrue( + "Doubles should be Doubles, even when incorrectly converting floats!", + JSONObject.stringToValue(new Double("0.2f").toString()) instanceof Double); + /** + * This test documents a need for BigDecimal conversion. + */ + final Object obj = JSONObject.stringToValue("299792.457999999984"); + assertTrue( + "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!", + obj.equals(new Double(299792.458))); + assertTrue("1 should be an Integer!", + JSONObject.stringToValue("1") instanceof Integer); + assertTrue("Integer.MAX_VALUE should still be an Integer!", + JSONObject.stringToValue(new Integer(Integer.MAX_VALUE) + .toString()) instanceof Integer); + assertTrue("Large integers should be a Long!", + JSONObject.stringToValue(new Long(Long + .sum(Integer.MAX_VALUE, 1)).toString()) instanceof Long); + assertTrue( + "Long.MAX_VALUE should still be an Integer!", + JSONObject.stringToValue(new Long(Long.MAX_VALUE).toString()) instanceof Long); + + final String str = new BigInteger(new Long(Long.MAX_VALUE).toString()) + .add(BigInteger.ONE).toString(); + assertTrue("Really large integers currently evaluate to string", + JSONObject.stringToValue(str).equals("9223372036854775808")); + } + /** * Confirm behavior when toJSONArray is called with a null value */ @@ -1787,114 +1746,330 @@ public class JSONObjectTest { null == new JSONObject().toJSONArray(null)); } + /** + * This test documents an unexpected numeric behavior. A double that ends + * with .0 is parsed, serialized, then parsed again. On the second parse, it + * has become an int. + */ + @Test + public void unexpectedDoubleToIntConversion() { + final String key30 = "key30"; + final String key31 = "key31"; + final JSONObject jsonObject = new JSONObject(); + jsonObject.put(key30, new Double(3.0)); + jsonObject.put(key31, new Double(3.1)); + + assertTrue("3.0 should remain a double", + jsonObject.getDouble(key30) == 3); + assertTrue("3.1 should remain a double", + jsonObject.getDouble(key31) == 3.1); + + // turns 3.0 into 3. + final String serializedString = jsonObject.toString(); + final JSONObject deserialized = new JSONObject(serializedString); + assertTrue("3.0 is now an int", + deserialized.get(key30) instanceof Integer); + assertTrue("3.0 can still be interpreted as a double", + deserialized.getDouble(key30) == 3.0); + assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); + } + + /** + * Exercises the JSONObject.valueToString() method for various types + */ + @Test + public void valueToString() { + + assertTrue("null valueToString() incorrect", + "null".equals(JSONObject.valueToString(null))); + final MyJsonString jsonString = new MyJsonString(); + assertTrue("jsonstring valueToString() incorrect", + "my string".equals(JSONObject.valueToString(jsonString))); + assertTrue("boolean valueToString() incorrect", + "true".equals(JSONObject.valueToString(Boolean.TRUE))); + assertTrue("non-numeric double", "null".equals(JSONObject + .doubleToString(Double.POSITIVE_INFINITY))); + final String jsonObjectStr = "{" + "\"key1\":\"val1\"," + + "\"key2\":\"val2\"," + "\"key3\":\"val3\"" + "}"; + final JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("jsonObject valueToString() incorrect", JSONObject + .valueToString(jsonObject).equals(jsonObject.toString())); + final String jsonArrayStr = "[1,2,3]"; + final JSONArray jsonArray = new JSONArray(jsonArrayStr); + assertTrue("jsonArra valueToString() incorrect", JSONObject + .valueToString(jsonArray).equals(jsonArray.toString())); + final Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + assertTrue("map valueToString() incorrect", jsonObject.toString() + .equals(JSONObject.valueToString(map))); + final Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + assertTrue( + "collection valueToString() expected: " + jsonArray.toString() + + " actual: " + JSONObject.valueToString(collection), + jsonArray.toString().equals( + JSONObject.valueToString(collection))); + final Integer[] array = { new Integer(1), new Integer(2), + new Integer(3) }; + assertTrue("array valueToString() incorrect", jsonArray.toString() + .equals(JSONObject.valueToString(array))); + } + + /** + * Confirm that https://github.com/douglascrockford/JSON-java/issues/167 is + * fixed. The following code was throwing a ClassCastException in the + * JSONObject(Map) constructor + */ + @Test + public void valueToStringConfirmException() { + final Map myMap = new HashMap(); + myMap.put(1, "myValue"); + // this is the test, it should not throw an exception + final String str = JSONObject.valueToString(myMap); + // confirm result, just in case + final Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(str); + assertTrue("expected 1 top level item", + ((Map) JsonPath.read(doc, "$")).size() == 1); + assertTrue("expected myValue", + "myValue".equals(JsonPath.read(doc, "$.1"))); + } + + /** + * Verifies that the constructor has backwards compatability with RAW types + * pre-java5. + */ + @Test + public void verifyConstructor() { + + final JSONObject expected = new JSONObject("{\"myKey\":10}"); + + @SuppressWarnings("rawtypes") + final Map myRawC = Collections.singletonMap("myKey", + Integer.valueOf(10)); + final JSONObject jaRaw = new JSONObject(myRawC); + + final Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + final JSONObject jaStrObj = new JSONObject(myCStrObj); + + final Map myCStrInt = Collections.singletonMap( + "myKey", Integer.valueOf(10)); + final JSONObject jaStrInt = new JSONObject(myCStrInt); + + final Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + final JSONObject jaObjObj = new JSONObject(myCObjObj); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); + } + + /** + * Verifies that the put Collection has backwards compatability with RAW + * types pre-java5. + */ + @Test + public void verifyPutCollection() { + + final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); + + @SuppressWarnings("rawtypes") + final Collection myRawC = Collections.singleton(Integer.valueOf(10)); + final JSONObject jaRaw = new JSONObject(); + jaRaw.put("myCollection", myRawC); + + final Collection myCObj = Collections + .singleton((Object) Integer.valueOf(10)); + final JSONObject jaObj = new JSONObject(); + jaObj.put("myCollection", myCObj); + + final Collection myCInt = Collections.singleton(Integer + .valueOf(10)); + final JSONObject jaInt = new JSONObject(); + jaInt.put("myCollection", myCInt); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaInt)); + } + + /** + * Verifies that the put Map has backwards compatability with RAW types + * pre-java5. + */ + @Test + public void verifyPutMap() { + + final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); + + @SuppressWarnings("rawtypes") + final Map myRawC = Collections.singletonMap("myKey", + Integer.valueOf(10)); + final JSONObject jaRaw = new JSONObject(); + jaRaw.put("myMap", myRawC); + + final Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + final JSONObject jaStrObj = new JSONObject(); + jaStrObj.put("myMap", myCStrObj); + + final Map myCStrInt = Collections.singletonMap( + "myKey", Integer.valueOf(10)); + final JSONObject jaStrInt = new JSONObject(); + jaStrInt.put("myMap", myCStrInt); + + final Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + final JSONObject jaObjObj = new JSONObject(); + jaObjObj.put("myMap", myCObjObj); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); + } + + /** + * Exercise the JSONObject wrap() method. Sometimes wrap() will change the + * object being wrapped, other times not. The purpose of wrap() is to ensure + * the value is packaged in a way that is compatible with how a JSONObject + * value or JSONArray value is supposed to be stored. + */ + @Test + public void wrapObject() { + // wrap(null) returns NULL + assertTrue("null wrap() incorrect", + JSONObject.NULL == JSONObject.wrap(null)); + + // wrap(Integer) returns Integer + final Integer in = new Integer(1); + assertTrue("Integer wrap() incorrect", in == JSONObject.wrap(in)); + + /** + * This test is to document the preferred behavior if BigDecimal is + * supported. Previously bd returned as a string, since it is recognized + * as being a Java package class. Now with explicit support for big + * numbers, it remains a BigDecimal + */ + final Object bdWrap = JSONObject.wrap(BigDecimal.ONE); + assertTrue("BigDecimal.ONE evaluates to ONE", + bdWrap.equals(BigDecimal.ONE)); + + // wrap JSONObject returns JSONObject + final String jsonObjectStr = "{" + "\"key1\":\"val1\"," + + "\"key2\":\"val2\"," + "\"key3\":\"val3\"" + "}"; + final JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("JSONObject wrap() incorrect", + jsonObject == JSONObject.wrap(jsonObject)); + + // wrap collection returns JSONArray + final Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + final JSONArray jsonArray = (JSONArray) JSONObject.wrap(collection); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + assertTrue("expected 3 top level items", + ((List) JsonPath.read(doc, "$")).size() == 3); + assertTrue("expected 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", + Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + + // wrap Array returns JSONArray + final Integer[] array = { new Integer(1), new Integer(2), + new Integer(3) }; + final JSONArray integerArrayJsonArray = (JSONArray) JSONObject + .wrap(array); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + assertTrue("expected 3 top level items", + ((List) JsonPath.read(doc, "$")).size() == 3); + assertTrue("expected 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", + Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(integerArrayJsonArray.toString()); + assertTrue("expected 3 top level items", + ((List) JsonPath.read(doc, "$")).size() == 3); + assertTrue("expected 1", + Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", + Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", + Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + + // wrap map returns JSONObject + final Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + final JSONObject mapJsonObject = (JSONObject) JSONObject.wrap(map); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(mapJsonObject.toString()); + assertTrue("expected 3 top level items", + ((Map) JsonPath.read(doc, "$")).size() == 3); + assertTrue("expected val1", "val1".equals(JsonPath.read(doc, "$.key1"))); + assertTrue("expected val2", "val2".equals(JsonPath.read(doc, "$.key2"))); + assertTrue("expected val3", "val3".equals(JsonPath.read(doc, "$.key3"))); + } + /** * Exercise the JSONObject write() method */ @Test public void write() { - String str = "{\"key\":\"value\"}"; - String expectedStr = str; - JSONObject jsonObject = new JSONObject(str); - StringWriter stringWriter = new StringWriter(); - Writer writer = jsonObject.write(stringWriter); - String actualStr = writer.toString(); - assertTrue("write() expected " +expectedStr+ - "but found " +actualStr, + final String str = "{\"key\":\"value\"}"; + final String expectedStr = str; + final JSONObject jsonObject = new JSONObject(str); + final StringWriter stringWriter = new StringWriter(); + final Writer writer = jsonObject.write(stringWriter); + final String actualStr = writer.toString(); + assertTrue( + "write() expected " + expectedStr + "but found " + actualStr, expectedStr.equals(actualStr)); } - - /** - * Exercise the JSONObject equals() method - */ - @Test - public void equals() { - String str = "{\"key\":\"value\"}"; - JSONObject aJsonObject = new JSONObject(str); - assertTrue("Same JSONObject should be equal to itself", - aJsonObject.equals(aJsonObject)); - } - - /** - * JSON null is not the same as Java null. This test examines the differences - * in how they are handled by JSON-java. - */ - @Test - public void jsonObjectNullOperations() { - /** - * The Javadoc for JSONObject.NULL states: - * "JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined." - * - * Standard ECMA-262 6th Edition / June 2015 (included to help explain the javadoc): - * undefined value: primitive value used when a variable has not been assigned a value - * Undefined type: type whose sole value is the undefined value - * null value: primitive value that represents the intentional absence of any object value - * Null type: type whose sole value is the null value - * Java SE8 language spec (included to help explain the javadoc): - * The Kinds of Types and Values ... - * There is also a special null type, the type of the expression null, which has no name. - * Because the null type has no name, it is impossible to declare a variable of the null - * type or to cast to the null type. The null reference is the only possible value of an - * expression of null type. The null reference can always be assigned or cast to any reference type. - * In practice, the programmer can ignore the null type and just pretend that null is merely - * a special literal that can be of any reference type. - * Extensible Markup Language (XML) 1.0 Fifth Edition / 26 November 2008 - * No mention of null - * ECMA-404 1st Edition / October 2013: - * JSON Text ... - * These are three literal name tokens: ... - * null - * - * There seems to be no best practice to follow, it's all about what we - * want the code to do. - */ - - // add JSONObject.NULL then convert to string in the manner of XML.toString() - JSONObject jsonObjectJONull = new JSONObject(); - Object obj = JSONObject.NULL; - jsonObjectJONull.put("key", obj); - Object value = jsonObjectJONull.opt("key"); - assertTrue("opt() JSONObject.NULL should find JSONObject.NULL", - obj.equals(value)); - value = jsonObjectJONull.get("key"); - assertTrue("get() JSONObject.NULL should find JSONObject.NULL", - obj.equals(value)); - if (value == null) { - value = ""; - } - String string = value instanceof String ? (String)value : null; - assertTrue("XML toString() should convert JSONObject.NULL to null", - string == null); - - // now try it with null - JSONObject jsonObjectNull = new JSONObject(); - obj = null; - jsonObjectNull.put("key", obj); - value = jsonObjectNull.opt("key"); - assertTrue("opt() null should find null", value == null); - if (value == null) { - value = ""; - } - string = value instanceof String ? (String)value : null; - assertTrue("should convert null to empty string", "".equals(string)); - try { - value = jsonObjectNull.get("key"); - assertTrue("get() null should throw exception", false); - } catch (Exception ignored) {} - - /** - * XML.toString() then goes on to do something with the value - * if the key val is "content", then value.toString() will be - * called. This will evaluate to "null" for JSONObject.NULL, - * and the empty string for null. - * But if the key is anything else, then JSONObject.NULL will be emitted - * as null and null will be emitted as "" - */ - String sJONull = XML.toString(jsonObjectJONull); - assertTrue("JSONObject.NULL should emit a null value", - "null".equals(sJONull)); - String sNull = XML.toString(jsonObjectNull); - assertTrue("null should emit an empty string", "".equals(sNull)); - } } From bd958e08309ff1e29df90b0921e37886cb76b6af Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 27 Jan 2016 11:36:15 -0500 Subject: [PATCH 192/451] fixes formatting --- src/test/org/json/junit/JSONObjectTest.java | 3337 +++++++++---------- 1 file changed, 1582 insertions(+), 1755 deletions(-) diff --git a/src/test/org/json/junit/JSONObjectTest.java b/src/test/org/json/junit/JSONObjectTest.java index dc74459..5eedf1a 100644 --- a/src/test/org/json/junit/JSONObjectTest.java +++ b/src/test/org/json/junit/JSONObjectTest.java @@ -10,14 +10,7 @@ import java.io.StringWriter; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import java.util.*; import org.json.CDL; import org.json.JSONArray; @@ -26,241 +19,24 @@ import org.json.JSONObject; import org.json.XML; import org.junit.Test; -import com.jayway.jsonpath.Configuration; -import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.*; /** - * JSONObject, along with JSONArray, are the central classes of the reference - * app. All of the other classes interact with them, and JSON functionality - * would otherwise be impossible. + * JSONObject, along with JSONArray, are the central classes of the reference app. + * All of the other classes interact with them, and JSON functionality would + * otherwise be impossible. */ public class JSONObjectTest { /** - * Document behaviors of big numbers. Includes both JSONObject and JSONArray - * tests + * JSONObject built from a bean, but only using a null value. + * Nothing good is expected to happen. + * Expects NullPointerException */ - @Test - public void bigNumberOperations() { - /** - * JSONObject tries to parse BigInteger as a bean, but it only has one - * getter, getLowestBitSet(). The value is lost and an unhelpful value - * is stored. This should be fixed. - */ - final BigInteger bigInteger = new BigInteger( - "123456789012345678901234567890"); - JSONObject jsonObject = new JSONObject(bigInteger); - Object obj = jsonObject.get("lowestSetBit"); - assertTrue("JSONObject only has 1 value", jsonObject.length() == 1); - assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet", - obj instanceof Integer); - assertTrue("this bigInteger lowestBitSet happens to be 1", - obj.equals(1)); - - /** - * JSONObject tries to parse BigDecimal as a bean, but it has no - * getters, The value is lost and no value is stored. This should be - * fixed. - */ - final BigDecimal bigDecimal = new BigDecimal( - "123456789012345678901234567890.12345678901234567890123456789"); - jsonObject = new JSONObject(bigDecimal); - assertTrue("large bigDecimal is not stored", jsonObject.length() == 0); - - /** - * JSONObject put(String, Object) method stores and serializes bigInt - * and bigDec correctly. Nothing needs to change. - */ - jsonObject = new JSONObject(); - jsonObject.put("bigInt", bigInteger); - assertTrue("jsonObject.put() handles bigInt correctly", - jsonObject.get("bigInt").equals(bigInteger)); - assertTrue("jsonObject.getBigInteger() handles bigInt correctly", - jsonObject.getBigInteger("bigInt").equals(bigInteger)); - assertTrue( - "jsonObject.optBigInteger() handles bigInt correctly", - jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals( - bigInteger)); - assertTrue( - "jsonObject serializes bigInt correctly", - jsonObject.toString().equals( - "{\"bigInt\":123456789012345678901234567890}")); - jsonObject = new JSONObject(); - jsonObject.put("bigDec", bigDecimal); - assertTrue("jsonObject.put() handles bigDec correctly", - jsonObject.get("bigDec").equals(bigDecimal)); - assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", - jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); - assertTrue( - "jsonObject.optBigDecimal() handles bigDec correctly", - jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals( - bigDecimal)); - assertTrue( - "jsonObject serializes bigDec correctly", - jsonObject - .toString() - .equals("{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - - /** - * exercise some exceptions - */ - try { - jsonObject.getBigDecimal("bigInt"); - assertTrue("expected an exeption", false); - } catch (final JSONException ignored) { - } - obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); - assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); - try { - jsonObject.getBigInteger("bigDec"); - assertTrue("expected an exeption", false); - } catch (final JSONException ignored) { - } - jsonObject.put("stringKey", "abc"); - try { - jsonObject.getBigDecimal("stringKey"); - assertTrue("expected an exeption", false); - } catch (final JSONException ignored) { - } - obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); - assertTrue("expected BigInteger", obj.equals(BigInteger.ONE)); - - /** - * JSONObject.numberToString() works correctly, nothing to change. - */ - String str = JSONObject.numberToString(bigInteger); - assertTrue("numberToString() handles bigInteger correctly", - str.equals("123456789012345678901234567890")); - str = JSONObject.numberToString(bigDecimal); - assertTrue( - "numberToString() handles bigDecimal correctly", - str.equals("123456789012345678901234567890.12345678901234567890123456789")); - - /** - * JSONObject.stringToValue() turns bigInt into an accurate string, and - * rounds bigDec. This incorrect, but users may have come to expect this - * behavior. Change would be marginally better, but might inconvenience - * users. - */ - obj = JSONObject.stringToValue(bigInteger.toString()); - assertTrue("stringToValue() turns bigInteger string into string", - obj instanceof String); - obj = JSONObject.stringToValue(bigDecimal.toString()); - assertTrue("stringToValue() changes bigDecimal string", !obj.toString() - .equals(bigDecimal.toString())); - - /** - * wrap() vs put() big number behavior is now the same. - */ - // bigInt map ctor - Map map = new HashMap(); - map.put("bigInt", bigInteger); - jsonObject = new JSONObject(map); - String actualFromMapStr = jsonObject.toString(); - assertTrue("bigInt in map (or array or bean) is a string", - actualFromMapStr - .equals("{\"bigInt\":123456789012345678901234567890}")); - // bigInt put - jsonObject = new JSONObject(); - jsonObject.put("bigInt", bigInteger); - String actualFromPutStr = jsonObject.toString(); - assertTrue("bigInt from put is a number", - actualFromPutStr - .equals("{\"bigInt\":123456789012345678901234567890}")); - // bigDec map ctor - map = new HashMap(); - map.put("bigDec", bigDecimal); - jsonObject = new JSONObject(map); - actualFromMapStr = jsonObject.toString(); - assertTrue( - "bigDec in map (or array or bean) is a bigDec", - actualFromMapStr - .equals("{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - // bigDec put - jsonObject = new JSONObject(); - jsonObject.put("bigDec", bigDecimal); - actualFromPutStr = jsonObject.toString(); - assertTrue( - "bigDec from put is a number", - actualFromPutStr - .equals("{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - // bigInt,bigDec put - JSONArray jsonArray = new JSONArray(); - jsonArray.put(bigInteger); - jsonArray.put(bigDecimal); - actualFromPutStr = jsonArray.toString(); - assertTrue( - "bigInt, bigDec from put is a number", - actualFromPutStr - .equals("[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); - assertTrue("getBigInt is bigInt", - jsonArray.getBigInteger(0).equals(bigInteger)); - assertTrue("getBigDec is bigDec", - jsonArray.getBigDecimal(1).equals(bigDecimal)); - assertTrue("optBigInt is bigInt", - jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); - assertTrue("optBigDec is bigDec", - jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); - jsonArray.put(Boolean.TRUE); - try { - jsonArray.getBigInteger(2); - assertTrue("should not be able to get big int", false); - } catch (final Exception ignored) { - } - try { - jsonArray.getBigDecimal(2); - assertTrue("should not be able to get big dec", false); - } catch (final Exception ignored) { - } - assertTrue( - "optBigInt is default", - jsonArray.optBigInteger(2, BigInteger.ONE).equals( - BigInteger.ONE)); - assertTrue( - "optBigDec is default", - jsonArray.optBigDecimal(2, BigDecimal.ONE).equals( - BigDecimal.ONE)); - - // bigInt,bigDec list ctor - final List list = new ArrayList(); - list.add(bigInteger); - list.add(bigDecimal); - jsonArray = new JSONArray(list); - final String actualFromListStr = jsonArray.toString(); - assertTrue( - "bigInt, bigDec in list is a bigInt, bigDec", - actualFromListStr - .equals("[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); - // bigInt bean ctor - MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); - when(myBigNumberBean.getBigInteger()).thenReturn( - new BigInteger("123456789012345678901234567890")); - jsonObject = new JSONObject(myBigNumberBean); - String actualFromBeanStr = jsonObject.toString(); - // can't do a full string compare because mockery adds an extra - // key/value - assertTrue("bigInt from bean ctor is a bigInt", - actualFromBeanStr.contains("123456789012345678901234567890")); - // bigDec bean ctor - myBigNumberBean = mock(MyBigNumberBean.class); - when(myBigNumberBean.getBigDecimal()) - .thenReturn( - new BigDecimal( - "123456789012345678901234567890.12345678901234567890123456789")); - jsonObject = new JSONObject(myBigNumberBean); - actualFromBeanStr = jsonObject.toString(); - // can't do a full string compare because mockery adds an extra - // key/value - assertTrue( - "bigDec from bean ctor is a bigDec", - actualFromBeanStr - .contains("123456789012345678901234567890.12345678901234567890123456789")); - // bigInt,bigDec wrap() - obj = JSONObject.wrap(bigInteger); - assertTrue("wrap() returns big num", obj.equals(bigInteger)); - obj = JSONObject.wrap(bigDecimal); - assertTrue("wrap() returns string", obj.equals(bigDecimal)); - + @Test(expected=NullPointerException.class) + public void jsonObjectByNullBean() { + MyBean myBean = null; + new JSONObject(myBean); } /** @@ -268,76 +44,320 @@ public class JSONObjectTest { */ @Test public void emptyJsonObject() { - final JSONObject jsonObject = new JSONObject(); + JSONObject jsonObject = new JSONObject(); assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** - * Populate a JSONArray from an empty JSONObject names() method. It should - * be empty. + * A JSONObject can be created from another JSONObject plus a list of names. + * In this test, some of the starting JSONObject keys are not in the + * names list. */ @Test - public void emptyJsonObjectNamesToJsonAray() { - final JSONObject jsonObject = new JSONObject(); - final JSONArray jsonArray = jsonObject.names(); - assertTrue("jsonArray should be null", jsonArray == null); + public void jsonObjectByNames() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"nullKey\":null,"+ + "\"stringKey\":\"hello world!\","+ + "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"intKey\":42,"+ + "\"doubleKey\":-23.45e67"+ + "}"; + String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"}; + JSONObject jsonObject = new JSONObject(str); + + // validate JSON + JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"nullKey\":null", null == JsonPath.read(doc, "$.nullKey")); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); } /** - * Exercise the JSONObject equals() method + * JSONObjects can be built from a Map. + * In this test the map is null. + * the JSONObject(JsonTokener) ctor is not tested directly since it already + * has full coverage from other tests. */ @Test - public void equals() { - final String str = "{\"key\":\"value\"}"; - final JSONObject aJsonObject = new JSONObject(str); - assertTrue("Same JSONObject should be equal to itself", - aJsonObject.equals(aJsonObject)); + public void jsonObjectByNullMap() { + Map map = null; + JSONObject jsonObject = new JSONObject(map); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** - * This test documents how JSON-Java handles invalid numeric input. + * JSONObjects can be built from a Map. + * In this test all of the map entries are valid JSON types. */ @Test - public void jsonInvalidNumberValues() { - // Number-notations supported by Java and invalid as JSON - final String str = "{" + "\"hexNumber\":-0x123," - + "\"tooManyZeros\":00," + "\"negativeInfinite\":-Infinity," - + "\"negativeNaN\":-NaN," + "\"negativeFraction\":-.01," - + "\"tooManyZerosFraction\":00.001," - + "\"negativeHexFloat\":-0x1.fffp1," - + "\"hexFloat\":0x1.0P-1074," + "\"floatIdentifier\":0.1f," - + "\"doubleIdentifier\":0.1d" + "}"; - final JSONObject jsonObject = new JSONObject(str); - Object obj; - obj = jsonObject.get("hexNumber"); - assertFalse( - "hexNumber must not be a number (should throw exception!?)", - obj instanceof Number); - assertTrue("hexNumber currently evaluates to string", - obj.equals("-0x123")); - assertTrue("tooManyZeros currently evaluates to string", jsonObject - .get("tooManyZeros").equals("00")); - obj = jsonObject.get("negativeInfinite"); - assertTrue("negativeInfinite currently evaluates to string", - obj.equals("-Infinity")); - obj = jsonObject.get("negativeNaN"); - assertTrue("negativeNaN currently evaluates to string", - obj.equals("-NaN")); - assertTrue("negativeFraction currently evaluates to double -0.01", - jsonObject.get("negativeFraction").equals(new Double(-0.01))); - assertTrue("tooManyZerosFraction currently evaluates to double 0.001", - jsonObject.get("tooManyZerosFraction") - .equals(new Double(0.001))); + public void jsonObjectByMap() { + Map map = new HashMap(); + map.put("trueKey", new Boolean(true)); + map.put("falseKey", new Boolean(false)); + map.put("stringKey", "hello world!"); + map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); + map.put("intKey", new Long(42)); + map.put("doubleKey", new Double(-23.45e67)); + JSONObject jsonObject = new JSONObject(map); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); + } + + /** + * Verifies that the constructor has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyConstructor() { + + final JSONObject expected = new JSONObject("{\"myKey\":10}"); + + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(myRawC); + + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONObject jaStrObj = new JSONObject(myCStrObj); + + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONObject jaStrInt = new JSONObject(myCStrInt); + + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONObject jaObjObj = new JSONObject(myCObjObj); + assertTrue( - "negativeHexFloat currently evaluates to double -3.99951171875", - jsonObject.get("negativeHexFloat").equals( - new Double(-3.99951171875))); - assertTrue("hexFloat currently evaluates to double 4.9E-324", - jsonObject.get("hexFloat").equals(new Double(4.9E-324))); - assertTrue("floatIdentifier currently evaluates to double 0.1", - jsonObject.get("floatIdentifier").equals(new Double(0.1))); - assertTrue("doubleIdentifier currently evaluates to double 0.1", - jsonObject.get("doubleIdentifier").equals(new Double(0.1))); + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); + } + + /** + * Verifies that the put Collection has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyPutCollection() { + + final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); + + @SuppressWarnings("rawtypes") + Collection myRawC = Collections.singleton(Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(); + jaRaw.put("myCollection", myRawC); + + Collection myCObj = Collections.singleton((Object) Integer + .valueOf(10)); + JSONObject jaObj = new JSONObject(); + jaObj.put("myCollection", myCObj); + + Collection myCInt = Collections.singleton(Integer + .valueOf(10)); + JSONObject jaInt = new JSONObject(); + jaInt.put("myCollection", myCInt); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaInt)); + } + + + /** + * Verifies that the put Map has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyPutMap() { + + final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); + + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(); + jaRaw.put("myMap", myRawC); + + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONObject jaStrObj = new JSONObject(); + jaStrObj.put("myMap", myCStrObj); + + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONObject jaStrInt = new JSONObject(); + jaStrInt.put("myMap", myCStrInt); + + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONObject jaObjObj = new JSONObject(); + jaObjObj.put("myMap", myCObjObj); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); + } + + + /** + * JSONObjects can be built from a Map. + * In this test the map entries are not valid JSON types. + * The actual conversion is kind of interesting. + */ + @Test + public void jsonObjectByMapWithUnsupportedValues() { + Map jsonMap = new HashMap(); + // Just insert some random objects + jsonMap.put("key1", new CDL()); + jsonMap.put("key2", new Exception()); + + JSONObject jsonObject = new JSONObject(jsonMap); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(JsonPath.read(doc, "$.key2"))); + assertTrue("expected 0 key1 items", ((Map)(JsonPath.read(doc, "$.key1"))).size() == 0); + } + + /** + * JSONObjects can be built from a Map. + * In this test one of the map values is null + */ + @Test + public void jsonObjectByMapWithNullValue() { + Map map = new HashMap(); + map.put("trueKey", new Boolean(true)); + map.put("falseKey", new Boolean(false)); + map.put("stringKey", "hello world!"); + map.put("nullKey", null); + map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); + map.put("intKey", new Long(42)); + map.put("doubleKey", new Double(-23.45e67)); + JSONObject jsonObject = new JSONObject(map); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); + assertTrue("expected \"intKey\":42", Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); + } + + /** + * JSONObject built from a bean. In this case all but one of the + * bean getters return valid JSON types + */ + @Test + public void jsonObjectByBean() { + /** + * Default access classes have to be mocked since JSONObject, which is + * not in the same package, cannot call MyBean methods by reflection. + */ + MyBean myBean = mock(MyBean.class); + when(myBean.getDoubleKey()).thenReturn(-23.45e7); + when(myBean.getIntKey()).thenReturn(42); + when(myBean.getStringKey()).thenReturn("hello world!"); + when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!"); + when(myBean.isTrueKey()).thenReturn(true); + when(myBean.isFalseKey()).thenReturn(false); + when(myBean.getStringReaderKey()).thenReturn( + new StringReader("") { + }); + + JSONObject jsonObject = new JSONObject(myBean); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected hello world!","hello world!".equals(JsonPath.read(doc, "$.stringKey"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); + assertTrue("expected 42", Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); + assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(JsonPath.read(doc, "$.doubleKey"))); + assertTrue("expected 0 items in stringReaderKey", ((Map) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); + // sorry, mockito artifact + assertTrue("expected 2 callbacks items", ((List)(JsonPath.read(doc, "$.callbacks"))).size() == 2); + assertTrue("expected 0 handler items", ((Map)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0); + assertTrue("expected 0 callbacks[1] items", ((Map)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0); + } + + /** + * A bean is also an object. But in order to test the JSONObject + * ctor that takes an object and a list of names, + * this particular bean needs some public + * data members, which have been added to the class. + */ + @Test + public void jsonObjectByObjectAndNames() { + String[] keys = {"publicString", "publicInt"}; + // just need a class that has public data members + MyPublicClass myPublicClass = new MyPublicClass(); + JSONObject jsonObject = new JSONObject(myPublicClass, keys); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected \"publicString\":\"abc\"", "abc".equals(JsonPath.read(doc, "$.publicString"))); + assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.publicInt"))); + } + + /** + * Exercise the JSONObject from resource bundle functionality. + * The test resource bundle is uncomplicated, but provides adequate test coverage. + */ + @Test + public void jsonObjectByResourceBundle() { + JSONObject jsonObject = new + JSONObject("org.json.junit.StringsResourceBundle", + Locale.getDefault()); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected 2 greetings items", ((Map)(JsonPath.read(doc, "$.greetings"))).size() == 2); + assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(JsonPath.read(doc, "$.greetings.hello"))); + assertTrue("expected \"world\":\"World!\"", "World!".equals(JsonPath.read(doc, "$.greetings.world"))); + assertTrue("expected 2 farewells items", ((Map)(JsonPath.read(doc, "$.farewells"))).size() == 2); + assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(JsonPath.read(doc, "$.farewells.later"))); + assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(JsonPath.read(doc, "$.farewells.gator"))); } /** @@ -346,7 +366,7 @@ public class JSONObjectTest { @Test public void jsonObjectAccumulate() { - final JSONObject jsonObject = new JSONObject(); + JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("myArray", true); jsonObject.accumulate("myArray", false); jsonObject.accumulate("myArray", "hello world!"); @@ -357,31 +377,18 @@ public class JSONObjectTest { try { jsonObject.accumulate("myArray", Double.NaN); assertTrue("Expected exception", false); - } catch (final JSONException ignored) { - } + } catch (JSONException ignored) {} // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 1 top level item", - ((Map) JsonPath.read(doc, "$")).size() == 1); - assertTrue("expected 6 myArray items", - ((List) JsonPath.read(doc, "$.myArray")).size() == 6); - assertTrue("expected true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); - assertTrue("expected false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); - assertTrue("expected hello world!", - "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); - assertTrue("expected h\be\tllo w\u1234orld!", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.myArray[3]"))); - assertTrue("expected 42", - Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); - assertTrue( - "expected -23.45e7", - Double.valueOf(-23.45e7).equals( - JsonPath.read(doc, "$.myArray[5]"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); + assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.myArray[3]"))); + assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); + assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(JsonPath.read(doc, "$.myArray[5]"))); } /** @@ -389,7 +396,7 @@ public class JSONObjectTest { */ @Test public void jsonObjectAppend() { - final JSONObject jsonObject = new JSONObject(); + JSONObject jsonObject = new JSONObject(); jsonObject.append("myArray", true); jsonObject.append("myArray", false); jsonObject.append("myArray", "hello world!"); @@ -400,288 +407,18 @@ public class JSONObjectTest { try { jsonObject.append("myArray", Double.NaN); assertTrue("Expected exception", false); - } catch (final JSONException ignored) { - } + } catch (JSONException ignored) {} // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 1 top level item", - ((Map) JsonPath.read(doc, "$")).size() == 1); - assertTrue("expected 6 myArray items", - ((List) JsonPath.read(doc, "$.myArray")).size() == 6); - assertTrue("expected true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); - assertTrue("expected false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); - assertTrue("expected hello world!", - "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); - assertTrue("expected h\be\tllo w\u1234orld!", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.myArray[3]"))); - assertTrue("expected 42", - Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); - assertTrue( - "expected -23.45e7", - Double.valueOf(-23.45e7).equals( - JsonPath.read(doc, "$.myArray[5]"))); - } - - /** - * JSONObject built from a bean. In this case all but one of the bean - * getters return valid JSON types - */ - @Test - public void jsonObjectByBean() { - /** - * Default access classes have to be mocked since JSONObject, which is - * not in the same package, cannot call MyBean methods by reflection. - */ - final MyBean myBean = mock(MyBean.class); - when(myBean.getDoubleKey()).thenReturn(-23.45e7); - when(myBean.getIntKey()).thenReturn(42); - when(myBean.getStringKey()).thenReturn("hello world!"); - when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!"); - when(myBean.isTrueKey()).thenReturn(true); - when(myBean.isFalseKey()).thenReturn(false); - when(myBean.getStringReaderKey()).thenReturn(new StringReader("") { - }); - - final JSONObject jsonObject = new JSONObject(myBean); - - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 8 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 8); - assertTrue("expected true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected hello world!", - "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected h\be\tllo w\u1234orld!", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.escapeStringKey"))); - assertTrue("expected 42", - Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); - assertTrue( - "expected -23.45e7", - Double.valueOf("-23.45e7").equals( - JsonPath.read(doc, "$.doubleKey"))); - assertTrue( - "expected 0 items in stringReaderKey", - ((Map) JsonPath.read(doc, "$.stringReaderKey")).size() == 0); - // sorry, mockito artifact - assertTrue("expected 2 callbacks items", - ((List) JsonPath.read(doc, "$.callbacks")).size() == 2); - assertTrue("expected 0 handler items", ((Map) JsonPath.read(doc, - "$.callbacks[0].handler")).size() == 0); - assertTrue("expected 0 callbacks[1] items", - ((Map) JsonPath.read(doc, "$.callbacks[1]")).size() == 0); - } - - /** - * JSONObjects can be built from a Map. In this test all of - * the map entries are valid JSON types. - */ - @Test - public void jsonObjectByMap() { - final Map map = new HashMap(); - map.put("trueKey", new Boolean(true)); - map.put("falseKey", new Boolean(false)); - map.put("stringKey", "hello world!"); - map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); - map.put("intKey", new Long(42)); - map.put("doubleKey", new Double(-23.45e67)); - final JSONObject jsonObject = new JSONObject(map); - - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 6 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 6); - assertTrue("expected \"trueKey\":true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected \"falseKey\":false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", - "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.escapeStringKey"))); - assertTrue( - "expected \"doubleKey\":-23.45e67", - Double.valueOf("-23.45e67").equals( - JsonPath.read(doc, "$.doubleKey"))); - } - - /** - * JSONObjects can be built from a Map. In this test one of - * the map values is null - */ - @Test - public void jsonObjectByMapWithNullValue() { - final Map map = new HashMap(); - map.put("trueKey", new Boolean(true)); - map.put("falseKey", new Boolean(false)); - map.put("stringKey", "hello world!"); - map.put("nullKey", null); - map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); - map.put("intKey", new Long(42)); - map.put("doubleKey", new Double(-23.45e67)); - final JSONObject jsonObject = new JSONObject(map); - - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 6 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 6); - assertTrue("expected \"trueKey\":true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected \"falseKey\":false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", - "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", - "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, - "$.escapeStringKey"))); - assertTrue("expected \"intKey\":42", - Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); - assertTrue( - "expected \"doubleKey\":-23.45e67", - Double.valueOf("-23.45e67").equals( - JsonPath.read(doc, "$.doubleKey"))); - } - - /** - * JSONObjects can be built from a Map. In this test the map - * entries are not valid JSON types. The actual conversion is kind of - * interesting. - */ - @Test - public void jsonObjectByMapWithUnsupportedValues() { - final Map jsonMap = new HashMap(); - // Just insert some random objects - jsonMap.put("key1", new CDL()); - jsonMap.put("key2", new Exception()); - - final JSONObject jsonObject = new JSONObject(jsonMap); - - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 2 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 2); - assertTrue("expected \"key2\":java.lang.Exception", - "java.lang.Exception".equals(JsonPath.read(doc, "$.key2"))); - assertTrue("expected 0 key1 items", - ((Map) JsonPath.read(doc, "$.key1")).size() == 0); - } - - /** - * A JSONObject can be created from another JSONObject plus a list of names. - * In this test, some of the starting JSONObject keys are not in the names - * list. - */ - @Test - public void jsonObjectByNames() { - final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," - + "\"nullKey\":null," + "\"stringKey\":\"hello world!\"," - + "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\"," - + "\"intKey\":42," + "\"doubleKey\":-23.45e67" + "}"; - final String[] keys = { "falseKey", "stringKey", "nullKey", "doubleKey" }; - final JSONObject jsonObject = new JSONObject(str); - - // validate JSON - final JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObjectByName.toString()); - assertTrue("expected 4 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 4); - assertTrue("expected \"falseKey\":false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"nullKey\":null", - null == JsonPath.read(doc, "$.nullKey")); - assertTrue("expected \"stringKey\":\"hello world!\"", - "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue( - "expected \"doubleKey\":-23.45e67", - Double.valueOf("-23.45e67").equals( - JsonPath.read(doc, "$.doubleKey"))); - } - - /** - * JSONObject built from a bean, but only using a null value. Nothing good - * is expected to happen. Expects NullPointerException - */ - @Test(expected = NullPointerException.class) - public void jsonObjectByNullBean() { - final MyBean myBean = null; - new JSONObject(myBean); - } - - /** - * JSONObjects can be built from a Map. In this test the map - * is null. the JSONObject(JsonTokener) ctor is not tested directly since it - * already has full coverage from other tests. - */ - @Test - public void jsonObjectByNullMap() { - final Map map = null; - final JSONObject jsonObject = new JSONObject(map); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); - } - - /** - * A bean is also an object. But in order to test the JSONObject ctor that - * takes an object and a list of names, this particular bean needs some - * public data members, which have been added to the class. - */ - @Test - public void jsonObjectByObjectAndNames() { - final String[] keys = { "publicString", "publicInt" }; - // just need a class that has public data members - final MyPublicClass myPublicClass = new MyPublicClass(); - final JSONObject jsonObject = new JSONObject(myPublicClass, keys); - - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 2 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 2); - assertTrue("expected \"publicString\":\"abc\"", - "abc".equals(JsonPath.read(doc, "$.publicString"))); - assertTrue("expected \"publicInt\":42", - Integer.valueOf(42).equals(JsonPath.read(doc, "$.publicInt"))); - } - - /** - * Exercise the JSONObject from resource bundle functionality. The test - * resource bundle is uncomplicated, but provides adequate test coverage. - */ - @Test - public void jsonObjectByResourceBundle() { - final JSONObject jsonObject = new JSONObject( - "org.json.junit.StringsResourceBundle", Locale.getDefault()); - - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 2 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 2); - assertTrue("expected 2 greetings items", - ((Map) JsonPath.read(doc, "$.greetings")).size() == 2); - assertTrue("expected \"hello\":\"Hello, \"", - "Hello, ".equals(JsonPath.read(doc, "$.greetings.hello"))); - assertTrue("expected \"world\":\"World!\"", - "World!".equals(JsonPath.read(doc, "$.greetings.world"))); - assertTrue("expected 2 farewells items", - ((Map) JsonPath.read(doc, "$.farewells")).size() == 2); - assertTrue("expected \"later\":\"Later, \"", - "Later, ".equals(JsonPath.read(doc, "$.farewells.later"))); - assertTrue("expected \"world\":\"World!\"", - "Alligator!".equals(JsonPath.read(doc, "$.farewells.gator"))); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); + assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.myArray[3]"))); + assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); + assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(JsonPath.read(doc, "$.myArray[5]"))); } /** @@ -689,173 +426,561 @@ public class JSONObjectTest { */ @Test public void jsonObjectDoubleToString() { - final String[] expectedStrs = { "1", "1", "-23.4", "-2.345E68", "null", - "null" }; - final Double[] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, - Double.NaN, Double.NEGATIVE_INFINITY }; + String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; + Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, + Double.NaN, Double.NEGATIVE_INFINITY }; for (int i = 0; i < expectedStrs.length; ++i) { - final String actualStr = JSONObject.doubleToString(doubles[i]); - assertTrue("value expected [" + expectedStrs[i] + "] found [" - + actualStr + "]", expectedStrs[i].equals(actualStr)); + String actualStr = JSONObject.doubleToString(doubles[i]); + assertTrue("value expected ["+expectedStrs[i]+ + "] found ["+actualStr+ "]", + expectedStrs[i].equals(actualStr)); } } /** - * Exercise the JSONObject increment() method. + * Exercise some JSONObject get[type] and opt[type] methods */ @Test - public void jsonObjectIncrement() { - final String str = "{" + "\"keyLong\":9999999991," - + "\"keyDouble\":1.1" + "}"; - final JSONObject jsonObject = new JSONObject(str); - jsonObject.increment("keyInt"); - jsonObject.increment("keyInt"); - jsonObject.increment("keyLong"); - jsonObject.increment("keyDouble"); - jsonObject.increment("keyInt"); - jsonObject.increment("keyLong"); - jsonObject.increment("keyDouble"); - /** - * JSONObject constructor won't handle these types correctly, but adding - * them via put works. - */ - jsonObject.put("keyFloat", new Float(1.1)); - jsonObject.put("keyBigInt", new BigInteger( - "123456789123456789123456789123456780")); - jsonObject.put("keyBigDec", new BigDecimal( - "123456789123456789123456789123456780.1")); - jsonObject.increment("keyFloat"); - jsonObject.increment("keyFloat"); - jsonObject.increment("keyBigInt"); - jsonObject.increment("keyBigDec"); + public void jsonObjectValues() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"trueStrKey\":\"true\","+ + "\"falseStrKey\":\"false\","+ + "\"stringKey\":\"hello world!\","+ + "\"intKey\":42,"+ + "\"intStrKey\":\"43\","+ + "\"longKey\":1234567890123456789,"+ + "\"longStrKey\":\"987654321098765432\","+ + "\"doubleKey\":-23.45e7,"+ + "\"doubleStrKey\":\"00001.000\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{\"myKey\":\"myVal\"}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); + assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); + assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); + assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); + assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); + assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); + assertTrue("stringKey should be string", + jsonObject.getString("stringKey").equals("hello world!")); + assertTrue("doubleKey should be double", + jsonObject.getDouble("doubleKey") == -23.45e7); + assertTrue("doubleStrKey should be double", + jsonObject.getDouble("doubleStrKey") == 1); + assertTrue("opt doubleKey should be double", + jsonObject.optDouble("doubleKey") == -23.45e7); + assertTrue("opt doubleKey with Default should be double", + jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); + assertTrue("intKey should be int", + jsonObject.optInt("intKey") == 42); + assertTrue("opt intKey should be int", + jsonObject.optInt("intKey", 0) == 42); + assertTrue("opt intKey with default should be int", + jsonObject.getInt("intKey") == 42); + assertTrue("intStrKey should be int", + jsonObject.getInt("intStrKey") == 43); + assertTrue("longKey should be long", + jsonObject.getLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey should be long", + jsonObject.optLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey with default should be long", + jsonObject.optLong("longKey", 0) == 1234567890123456789L); + assertTrue("longStrKey should be long", + jsonObject.getLong("longStrKey") == 987654321098765432L); + assertTrue("xKey should not exist", + jsonObject.isNull("xKey")); + assertTrue("stringKey should exist", + jsonObject.has("stringKey")); + assertTrue("opt stringKey should string", + jsonObject.optString("stringKey").equals("hello world!")); + assertTrue("opt stringKey with default should string", + jsonObject.optString("stringKey", "not found").equals("hello world!")); + JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); + assertTrue("arrayKey should be JSONArray", + jsonArray.getInt(0) == 0 && + jsonArray.getInt(1) == 1 && + jsonArray.getInt(2) == 2); + jsonArray = jsonObject.optJSONArray("arrayKey"); + assertTrue("opt arrayKey should be JSONArray", + jsonArray.getInt(0) == 0 && + jsonArray.getInt(1) == 1 && + jsonArray.getInt(2) == 2); + JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); + assertTrue("objectKey should be JSONObject", + jsonObjectInner.get("myKey").equals("myVal")); + } - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 6 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 6); - assertTrue("expected 3", - Integer.valueOf(3).equals(JsonPath.read(doc, "$.keyInt"))); - assertTrue( - "expected 9999999993", - Long.valueOf(9999999993L).equals( - JsonPath.read(doc, "$.keyLong"))); - assertTrue("expected 3.1", - Double.valueOf(3.1).equals(JsonPath.read(doc, "$.keyDouble"))); - assertTrue("expected 123456789123456789123456789123456781", - new BigInteger("123456789123456789123456789123456781") - .equals(JsonPath.read(doc, "$.keyBigInt"))); - assertTrue("expected 123456789123456789123456789123456781.1", - new BigDecimal("123456789123456789123456789123456781.1") - .equals(JsonPath.read(doc, "$.keyBigDec"))); + /** + * Check whether JSONObject handles large or high precision numbers correctly + */ + @Test + public void stringToValueNumbersTest() { + assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0") instanceof Double); + assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double); + assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String); + assertTrue( "0.2 should be a Double!", + JSONObject.stringToValue( "0.2" ) instanceof Double ); + assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", + JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double ); + /** + * This test documents a need for BigDecimal conversion. + */ + Object obj = JSONObject.stringToValue( "299792.457999999984" ); + assertTrue( "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!", + obj.equals(new Double(299792.458)) ); + assertTrue( "1 should be an Integer!", + JSONObject.stringToValue( "1" ) instanceof Integer ); + assertTrue( "Integer.MAX_VALUE should still be an Integer!", + JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); + assertTrue( "Large integers should be a Long!", + JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); + assertTrue( "Long.MAX_VALUE should still be an Integer!", + JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); + + String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString(); + assertTrue( "Really large integers currently evaluate to string", + JSONObject.stringToValue(str).equals("9223372036854775808")); + } + + /** + * This test documents numeric values which could be numerically + * handled as BigDecimal or BigInteger. It helps determine what outputs + * will change if those types are supported. + */ + @Test + public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { + // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects + String str = + "{"+ + "\"numberWithDecimals\":299792.457999999984,"+ + "\"largeNumber\":12345678901234567890,"+ + "\"preciseNumber\":0.2000000000000000111,"+ + "\"largeExponent\":-23.45e2327"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + // Comes back as a double, but loses precision + assertTrue( "numberWithDecimals currently evaluates to double 299792.458", + jsonObject.get( "numberWithDecimals" ).equals( new Double( "299792.458" ) ) ); + Object obj = jsonObject.get( "largeNumber" ); + assertTrue("largeNumber currently evaluates to string", + "12345678901234567890".equals(obj)); + // comes back as a double but loses precision + assertTrue( "preciseNumber currently evaluates to double 0.2", + jsonObject.get( "preciseNumber" ).equals(new Double(0.2))); + obj = jsonObject.get( "largeExponent" ); + assertTrue("largeExponent should currently evaluates as a string", + "-23.45e2327".equals(obj)); + } + + /** + * This test documents how JSON-Java handles invalid numeric input. + */ + @Test + public void jsonInvalidNumberValues() { + // Number-notations supported by Java and invalid as JSON + String str = + "{"+ + "\"hexNumber\":-0x123,"+ + "\"tooManyZeros\":00,"+ + "\"negativeInfinite\":-Infinity,"+ + "\"negativeNaN\":-NaN,"+ + "\"negativeFraction\":-.01,"+ + "\"tooManyZerosFraction\":00.001,"+ + "\"negativeHexFloat\":-0x1.fffp1,"+ + "\"hexFloat\":0x1.0P-1074,"+ + "\"floatIdentifier\":0.1f,"+ + "\"doubleIdentifier\":0.1d"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + Object obj; + obj = jsonObject.get( "hexNumber" ); + assertFalse( "hexNumber must not be a number (should throw exception!?)", + obj instanceof Number ); + assertTrue("hexNumber currently evaluates to string", + obj.equals("-0x123")); + assertTrue( "tooManyZeros currently evaluates to string", + jsonObject.get( "tooManyZeros" ).equals("00")); + obj = jsonObject.get("negativeInfinite"); + assertTrue( "negativeInfinite currently evaluates to string", + obj.equals("-Infinity")); + obj = jsonObject.get("negativeNaN"); + assertTrue( "negativeNaN currently evaluates to string", + obj.equals("-NaN")); + assertTrue( "negativeFraction currently evaluates to double -0.01", + jsonObject.get( "negativeFraction" ).equals(new Double(-0.01))); + assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", + jsonObject.get( "tooManyZerosFraction" ).equals(new Double(0.001))); + assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875", + jsonObject.get( "negativeHexFloat" ).equals(new Double(-3.99951171875))); + assertTrue("hexFloat currently evaluates to double 4.9E-324", + jsonObject.get("hexFloat").equals(new Double(4.9E-324))); + assertTrue("floatIdentifier currently evaluates to double 0.1", + jsonObject.get("floatIdentifier").equals(new Double(0.1))); + assertTrue("doubleIdentifier currently evaluates to double 0.1", + jsonObject.get("doubleIdentifier").equals(new Double(0.1))); + } + + /** + * Tests how JSONObject get[type] handles incorrect types + */ + @Test + public void jsonObjectNonAndWrongValues() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"trueStrKey\":\"true\","+ + "\"falseStrKey\":\"false\","+ + "\"stringKey\":\"hello world!\","+ + "\"intKey\":42,"+ + "\"intStrKey\":\"43\","+ + "\"longKey\":1234567890123456789,"+ + "\"longStrKey\":\"987654321098765432\","+ + "\"doubleKey\":-23.45e7,"+ + "\"doubleStrKey\":\"00001.000\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{\"myKey\":\"myVal\"}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + try { + jsonObject.getBoolean("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } + try { + jsonObject.getBoolean("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a Boolean.". + equals(e.getMessage())); + } + try { + jsonObject.getString("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getString("trueKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"trueKey\"] not a string.". + equals(e.getMessage())); + } + try { + jsonObject.getDouble("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getDouble("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a number.". + equals(e.getMessage())); + } + try { + jsonObject.getInt("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getInt("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not an int.". + equals(e.getMessage())); + } + try { + jsonObject.getLong("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getLong("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a long.". + equals(e.getMessage())); + } + try { + jsonObject.getJSONArray("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getJSONArray("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a JSONArray.". + equals(e.getMessage())); + } + try { + jsonObject.getJSONObject("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getJSONObject("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a JSONObject.". + equals(e.getMessage())); + } + } + + /** + * This test documents an unexpected numeric behavior. + * A double that ends with .0 is parsed, serialized, then + * parsed again. On the second parse, it has become an int. + */ + @Test + public void unexpectedDoubleToIntConversion() { + String key30 = "key30"; + String key31 = "key31"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put(key30, new Double(3.0)); + jsonObject.put(key31, new Double(3.1)); + + assertTrue("3.0 should remain a double", + jsonObject.getDouble(key30) == 3); + assertTrue("3.1 should remain a double", + jsonObject.getDouble(key31) == 3.1); + + // turns 3.0 into 3. + String serializedString = jsonObject.toString(); + JSONObject deserialized = new JSONObject(serializedString); + assertTrue("3.0 is now an int", deserialized.get(key30) instanceof Integer); + assertTrue("3.0 can still be interpreted as a double", + deserialized.getDouble(key30) == 3.0); + assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); + } + + /** + * Document behaviors of big numbers. Includes both JSONObject + * and JSONArray tests + */ + @Test + public void bigNumberOperations() { + /** + * JSONObject tries to parse BigInteger as a bean, but it only has + * one getter, getLowestBitSet(). The value is lost and an unhelpful + * value is stored. This should be fixed. + */ + BigInteger bigInteger = new BigInteger("123456789012345678901234567890"); + JSONObject jsonObject = new JSONObject(bigInteger); + Object obj = jsonObject.get("lowestSetBit"); + assertTrue("JSONObject only has 1 value", jsonObject.length() == 1); + assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet", + obj instanceof Integer); + assertTrue("this bigInteger lowestBitSet happens to be 1", + obj.equals(1)); /** - * Should work the same way on any platform! @see https://docs.oracle - * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is the - * effect of a float to double conversion and is inherent to the - * shortcomings of the IEEE 754 format, when converting 32-bit into - * double-precision 64-bit. Java type-casts float to double. A 32 bit - * float is type-casted to 64 bit double by simply appending zero-bits - * to the mantissa (and extended the signed exponent by 3 bits.) and - * there is no way to obtain more information than it is stored in the - * 32-bits float. - * - * Like 1/3 cannot be represented as base10 number because it is - * periodically, 1/5 (for example) cannot be represented as base2 number - * since it is periodically in base2 (take a look at - * http://www.h-schmidt.net/FloatConverter/) The same happens to 3.1, - * that decimal number (base10 representation) is periodic in base2 - * representation, therefore appending zero-bits is inaccurate. Only - * repeating the periodically occuring bits (0110) would be a proper - * conversion. However one cannot detect from a 32 bit IEE754 - * representation which bits would "repeat infinitely", since the - * missing bits would not fit into the 32 bit float, i.e. the - * information needed simply is not there! + * JSONObject tries to parse BigDecimal as a bean, but it has + * no getters, The value is lost and no value is stored. + * This should be fixed. */ - assertTrue( - "expected 3.0999999046325684", - Double.valueOf(3.0999999046325684).equals( - JsonPath.read(doc, "$.keyFloat"))); + BigDecimal bigDecimal = new BigDecimal( + "123456789012345678901234567890.12345678901234567890123456789"); + jsonObject = new JSONObject(bigDecimal); + assertTrue("large bigDecimal is not stored", jsonObject.length() == 0); /** - * float f = 3.1f; double df = (double) f; double d = 3.1d; - * System.out.println - * (Integer.toBinaryString(Float.floatToRawIntBits(f))); - * System.out.println - * (Long.toBinaryString(Double.doubleToRawLongBits(df))); - * System.out.println - * (Long.toBinaryString(Double.doubleToRawLongBits(d))); - * - * - Float: seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm - * 1000000010001100110011001100110 - Double - * seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * 10000000 10001100110011001100110 - * 100000000001000110011001100110011000000000000000000000000000000 - * 100000000001000110011001100110011001100110011001100110011001101 + * JSONObject put(String, Object) method stores and serializes + * bigInt and bigDec correctly. Nothing needs to change. */ + jsonObject = new JSONObject(); + jsonObject.put("bigInt", bigInteger); + assertTrue("jsonObject.put() handles bigInt correctly", + jsonObject.get("bigInt").equals(bigInteger)); + assertTrue("jsonObject.getBigInteger() handles bigInt correctly", + jsonObject.getBigInteger("bigInt").equals(bigInteger)); + assertTrue("jsonObject.optBigInteger() handles bigInt correctly", + jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); + assertTrue("jsonObject serializes bigInt correctly", + jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); + jsonObject = new JSONObject(); + jsonObject.put("bigDec", bigDecimal); + assertTrue("jsonObject.put() handles bigDec correctly", + jsonObject.get("bigDec").equals(bigDecimal)); + assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", + jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); + assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", + jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); + assertTrue("jsonObject serializes bigDec correctly", + jsonObject.toString().equals( + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); /** - * Examples of well documented but probably unexpected behavior in java - * / with 32-bit float to 64-bit float conversion. + * exercise some exceptions */ - assertFalse( - "Document unexpected behaviour with explicit type-casting float as double!", - 0.2f == 0.2d); - assertFalse("Document unexpected behaviour with implicit type-cast!", - 0.2f == 0.2d); - final Double d1 = new Double(1.1f); - final Double d2 = new Double("1.1f"); - assertFalse( - "Document implicit type cast from float to double before calling Double(double d) constructor", - d1.equals(d2)); + try { + jsonObject.getBigDecimal("bigInt"); + assertTrue("expected an exeption", false); + } catch (JSONException ignored) {} + obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); + assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); + try { + jsonObject.getBigInteger("bigDec"); + assertTrue("expected an exeption", false); + } catch (JSONException ignored) {} + jsonObject.put("stringKey", "abc"); + try { + jsonObject.getBigDecimal("stringKey"); + assertTrue("expected an exeption", false); + } catch (JSONException ignored) {} + obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); + assertTrue("expected BigInteger", obj.equals(BigInteger.ONE)); - assertTrue( - "Correctly converting float to double via base10 (string) representation!", - new Double(3.1d).equals(new Double(new Float(3.1f).toString()))); + /** + * JSONObject.numberToString() works correctly, nothing to change. + */ + String str = JSONObject.numberToString(bigInteger); + assertTrue("numberToString() handles bigInteger correctly", + str.equals("123456789012345678901234567890")); + str = JSONObject.numberToString(bigDecimal); + assertTrue("numberToString() handles bigDecimal correctly", + str.equals("123456789012345678901234567890.12345678901234567890123456789")); - // Pinpointing the not so obvious "buggy" conversion from float to - // double in JSONObject - final JSONObject jo = new JSONObject(); - jo.put("bug", 3.1f); // will call put( String key, double value ) with - // implicit and "buggy" type-cast from float to - // double - assertFalse( - "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", - jo.get("bug").equals(new Double(3.1d))); + /** + * JSONObject.stringToValue() turns bigInt into an accurate string, + * and rounds bigDec. This incorrect, but users may have come to + * expect this behavior. Change would be marginally better, but + * might inconvenience users. + */ + obj = JSONObject.stringToValue(bigInteger.toString()); + assertTrue("stringToValue() turns bigInteger string into string", + obj instanceof String); + obj = JSONObject.stringToValue(bigDecimal.toString()); + assertTrue("stringToValue() changes bigDecimal string", + !obj.toString().equals(bigDecimal.toString())); - final JSONObject inc = new JSONObject(); - inc.put("bug", new Float(3.1f)); // This will put in instance of Float - // into JSONObject, i.e. call put( - // String key, Object value ) - assertTrue("Everything is ok here!", inc.get("bug") instanceof Float); - inc.increment("bug"); // after adding 1, increment will call put( String - // key, double value ) with implicit and "buggy" - // type-cast from float to double! - // this.put(key, (Float) value + 1); - // 1. The (Object)value will be typecasted to (Float)value since it is - // an instanceof Float actually nothing is done. - // 2. Float instance will be autoboxed into float because the + operator - // will work on primitives not Objects! - // 3. A float+float operation will be performed and results into a float - // primitive. - // 4. There is no method that matches the signature put( String key, - // float value), java-compiler will choose the method - // put( String key, double value) and does an implicit type-cast(!) by - // appending zero-bits to the mantissa - assertTrue("JSONObject increment converts Float to Double", - jo.get("bug") instanceof Double); - // correct implementation (with change of behavior) would be: - // this.put(key, new Float((Float) value + 1)); - // Probably it would be better to deprecate the method and remove some - // day, while convenient processing the "payload" is not - // really in the the scope of a JSON-library (IMHO.) + /** + * wrap() vs put() big number behavior is now the same. + */ + // bigInt map ctor + Map map = new HashMap(); + map.put("bigInt", bigInteger); + jsonObject = new JSONObject(map); + String actualFromMapStr = jsonObject.toString(); + assertTrue("bigInt in map (or array or bean) is a string", + actualFromMapStr.equals( + "{\"bigInt\":123456789012345678901234567890}")); + // bigInt put + jsonObject = new JSONObject(); + jsonObject.put("bigInt", bigInteger); + String actualFromPutStr = jsonObject.toString(); + assertTrue("bigInt from put is a number", + actualFromPutStr.equals( + "{\"bigInt\":123456789012345678901234567890}")); + // bigDec map ctor + map = new HashMap(); + map.put("bigDec", bigDecimal); + jsonObject = new JSONObject(map); + actualFromMapStr = jsonObject.toString(); + assertTrue("bigDec in map (or array or bean) is a bigDec", + actualFromMapStr.equals( + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + // bigDec put + jsonObject = new JSONObject(); + jsonObject.put("bigDec", bigDecimal); + actualFromPutStr = jsonObject.toString(); + assertTrue("bigDec from put is a number", + actualFromPutStr.equals( + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + // bigInt,bigDec put + JSONArray jsonArray = new JSONArray(); + jsonArray.put(bigInteger); + jsonArray.put(bigDecimal); + actualFromPutStr = jsonArray.toString(); + assertTrue("bigInt, bigDec from put is a number", + actualFromPutStr.equals( + "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); + assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger)); + assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal)); + assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); + assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); + jsonArray.put(Boolean.TRUE); + try { + jsonArray.getBigInteger(2); + assertTrue("should not be able to get big int", false); + } catch (Exception ignored) {} + try { + jsonArray.getBigDecimal(2); + assertTrue("should not be able to get big dec", false); + } catch (Exception ignored) {} + assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); + assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); + + // bigInt,bigDec list ctor + List list = new ArrayList(); + list.add(bigInteger); + list.add(bigDecimal); + jsonArray = new JSONArray(list); + String actualFromListStr = jsonArray.toString(); + assertTrue("bigInt, bigDec in list is a bigInt, bigDec", + actualFromListStr.equals( + "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); + // bigInt bean ctor + MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); + when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); + jsonObject = new JSONObject(myBigNumberBean); + String actualFromBeanStr = jsonObject.toString(); + // can't do a full string compare because mockery adds an extra key/value + assertTrue("bigInt from bean ctor is a bigInt", + actualFromBeanStr.contains("123456789012345678901234567890")); + // bigDec bean ctor + myBigNumberBean = mock(MyBigNumberBean.class); + when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); + jsonObject = new JSONObject(myBigNumberBean); + actualFromBeanStr = jsonObject.toString(); + // can't do a full string compare because mockery adds an extra key/value + assertTrue("bigDec from bean ctor is a bigDec", + actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789")); + // bigInt,bigDec wrap() + obj = JSONObject.wrap(bigInteger); + assertTrue("wrap() returns big num",obj.equals(bigInteger)); + obj = JSONObject.wrap(bigDecimal); + assertTrue("wrap() returns string",obj.equals(bigDecimal)); } /** - * The purpose for the static method getNames() methods are not clear. This - * method is not called from within JSON-Java. Most likely uses are to prep - * names arrays for: JSONObject(JSONObject jo, String[] names) + * The purpose for the static method getNames() methods are not clear. + * This method is not called from within JSON-Java. Most likely + * uses are to prep names arrays for: + * JSONObject(JSONObject jo, String[] names) * JSONObject(Object object, String names[]), */ @Test @@ -863,27 +988,32 @@ public class JSONObjectTest { JSONObject jsonObject; // getNames() from null JSONObject - assertTrue("null names from null Object", - null == JSONObject.getNames((Object) null)); + assertTrue("null names from null Object", + null == JSONObject.getNames((Object)null)); // getNames() from object with no fields - assertTrue("null names from Object with no fields", + assertTrue("null names from Object with no fields", null == JSONObject.getNames(new MyJsonString())); // getNames from new JSONOjbect jsonObject = new JSONObject(); - String[] names = JSONObject.getNames(jsonObject); + String [] names = JSONObject.getNames(jsonObject); assertTrue("names should be null", names == null); + // getNames() from empty JSONObject - final String emptyStr = "{}"; + String emptyStr = "{}"; jsonObject = new JSONObject(emptyStr); assertTrue("empty JSONObject should have null names", null == JSONObject.getNames(jsonObject)); // getNames() from JSONObject - final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," - + "\"stringKey\":\"hello world!\"," + "}"; + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; jsonObject = new JSONObject(str); names = JSONObject.getNames(jsonObject); JSONArray jsonArray = new JSONArray(names); @@ -904,10 +1034,10 @@ public class JSONObjectTest { ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); /** - * getNames() from an enum with properties has an interesting result. It - * returns the enum values, not the selected enum properties + * getNames() from an enum with properties has an interesting result. + * It returns the enum values, not the selected enum properties */ - final MyEnumField myEnumField = MyEnumField.VAL1; + MyEnumField myEnumField = MyEnumField.VAL1; names = JSONObject.getNames(myEnumField); // validate JSON @@ -916,18 +1046,22 @@ public class JSONObjectTest { .parse(jsonArray.toString()); docList = JsonPath.read(doc, "$"); assertTrue("expected 3 items", docList.size() == 3); - assertTrue("expected to find VAL1", + assertTrue( + "expected to find VAL1", ((List) JsonPath.read(doc, "$[?(@=='VAL1')]")).size() == 1); - assertTrue("expected to find VAL2", + assertTrue( + "expected to find VAL2", ((List) JsonPath.read(doc, "$[?(@=='VAL2')]")).size() == 1); - assertTrue("expected to find VAL3", + assertTrue( + "expected to find VAL3", ((List) JsonPath.read(doc, "$[?(@=='VAL3')]")).size() == 1); /** - * A bean is also an object. But in order to test the static method - * getNames(), this particular bean needs some public data members. + * A bean is also an object. But in order to test the static + * method getNames(), this particular bean needs some public + * data members. */ - final MyPublicClass myPublicClass = new MyPublicClass(); + MyPublicClass myPublicClass = new MyPublicClass(); names = JSONObject.getNames(myPublicClass); // validate JSON @@ -936,242 +1070,165 @@ public class JSONObjectTest { .parse(jsonArray.toString()); docList = JsonPath.read(doc, "$"); assertTrue("expected 2 items", docList.size() == 2); - assertTrue("expected to find publicString", ((List) JsonPath.read( - doc, "$[?(@=='publicString')]")).size() == 1); + assertTrue( + "expected to find publicString", + ((List) JsonPath.read(doc, "$[?(@=='publicString')]")).size() == 1); assertTrue( "expected to find publicInt", ((List) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1); } /** - * Populate a JSONArray from a JSONObject names() method. Confirm that it - * contains the expected names. + * Populate a JSONArray from an empty JSONObject names() method. + * It should be empty. + */ + @Test + public void emptyJsonObjectNamesToJsonAray() { + JSONObject jsonObject = new JSONObject(); + JSONArray jsonArray = jsonObject.names(); + assertTrue("jsonArray should be null", jsonArray == null); + } + + /** + * Populate a JSONArray from a JSONObject names() method. + * Confirm that it contains the expected names. */ @Test public void jsonObjectNamesToJsonAray() { - final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," - + "\"stringKey\":\"hello world!\"," + "}"; + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; - final JSONObject jsonObject = new JSONObject(str); - final JSONArray jsonArray = jsonObject.names(); + JSONObject jsonObject = new JSONObject(str); + JSONArray jsonArray = jsonObject.names(); // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - assertTrue("expected 3 top level items", - ((List) JsonPath.read(doc, "$")).size() == 3); - assertTrue( - "expected to find trueKey", - ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); - assertTrue( - "expected to find falseKey", - ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); - assertTrue( - "expected to find stringKey", - ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected to find trueKey", ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); + assertTrue("expected to find falseKey", ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); + assertTrue("expected to find stringKey", ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); } /** - * Tests how JSONObject get[type] handles incorrect types + * Exercise the JSONObject increment() method. */ @Test - public void jsonObjectNonAndWrongValues() { - final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," - + "\"trueStrKey\":\"true\"," + "\"falseStrKey\":\"false\"," - + "\"stringKey\":\"hello world!\"," + "\"intKey\":42," - + "\"intStrKey\":\"43\"," + "\"longKey\":1234567890123456789," - + "\"longStrKey\":\"987654321098765432\"," - + "\"doubleKey\":-23.45e7," + "\"doubleStrKey\":\"00001.000\"," - + "\"arrayKey\":[0,1,2]," - + "\"objectKey\":{\"myKey\":\"myVal\"}" + "}"; - final JSONObject jsonObject = new JSONObject(str); - try { - jsonObject.getBoolean("nonKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("expecting an exception message", - "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); - } - try { - jsonObject.getBoolean("stringKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a Boolean.".equals(e - .getMessage())); - } - try { - jsonObject.getString("nonKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); - } - try { - jsonObject.getString("trueKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"trueKey\"] not a string.".equals(e - .getMessage())); - } - try { - jsonObject.getDouble("nonKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); - } - try { - jsonObject.getDouble("stringKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a number.".equals(e - .getMessage())); - } - try { - jsonObject.getInt("nonKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); - } - try { - jsonObject.getInt("stringKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not an int.".equals(e - .getMessage())); - } - try { - jsonObject.getLong("nonKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); - } - try { - jsonObject.getLong("stringKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a long.".equals(e - .getMessage())); - } - try { - jsonObject.getJSONArray("nonKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); - } - try { - jsonObject.getJSONArray("stringKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a JSONArray.".equals(e - .getMessage())); - } - try { - jsonObject.getJSONObject("nonKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); - } - try { - jsonObject.getJSONObject("stringKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a JSONObject.".equals(e - .getMessage())); - } - } - - /** - * JSON null is not the same as Java null. This test examines the - * differences in how they are handled by JSON-java. - */ - @Test - public void jsonObjectNullOperations() { + public void jsonObjectIncrement() { + String str = + "{"+ + "\"keyLong\":9999999991,"+ + "\"keyDouble\":1.1"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("keyInt"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); /** - * The Javadoc for JSONObject.NULL states: "JSONObject.NULL is - * equivalent to the value that JavaScript calls null, whilst Java's - * null is equivalent to the value that JavaScript calls undefined." - * - * Standard ECMA-262 6th Edition / June 2015 (included to help explain - * the javadoc): undefined value: primitive value used when a variable - * has not been assigned a value Undefined type: type whose sole value - * is the undefined value null value: primitive value that represents - * the intentional absence of any object value Null type: type whose - * sole value is the null value Java SE8 language spec (included to help - * explain the javadoc): The Kinds of Types and Values ... There is also - * a special null type, the type of the expression null, which has no - * name. Because the null type has no name, it is impossible to declare - * a variable of the null type or to cast to the null type. The null - * reference is the only possible value of an expression of null type. - * The null reference can always be assigned or cast to any reference - * type. In practice, the programmer can ignore the null type and just - * pretend that null is merely a special literal that can be of any - * reference type. Extensible Markup Language (XML) 1.0 Fifth Edition / - * 26 November 2008 No mention of null ECMA-404 1st Edition / October - * 2013: JSON Text ... These are three literal name tokens: ... null - * - * There seems to be no best practice to follow, it's all about what we - * want the code to do. + * JSONObject constructor won't handle these types correctly, but + * adding them via put works. */ + jsonObject.put("keyFloat", new Float(1.1)); + jsonObject.put("keyBigInt", new BigInteger("123456789123456789123456789123456780")); + jsonObject.put("keyBigDec", new BigDecimal("123456789123456789123456789123456780.1")); + jsonObject.increment("keyFloat"); + jsonObject.increment("keyFloat"); + jsonObject.increment("keyBigInt"); + jsonObject.increment("keyBigDec"); - // add JSONObject.NULL then convert to string in the manner of - // XML.toString() - final JSONObject jsonObjectJONull = new JSONObject(); - Object obj = JSONObject.NULL; - jsonObjectJONull.put("key", obj); - Object value = jsonObjectJONull.opt("key"); - assertTrue("opt() JSONObject.NULL should find JSONObject.NULL", - obj.equals(value)); - value = jsonObjectJONull.get("key"); - assertTrue("get() JSONObject.NULL should find JSONObject.NULL", - obj.equals(value)); - if (value == null) { - value = ""; - } - String string = value instanceof String ? (String) value : null; - assertTrue("XML toString() should convert JSONObject.NULL to null", - string == null); - - // now try it with null - final JSONObject jsonObjectNull = new JSONObject(); - obj = null; - jsonObjectNull.put("key", obj); - value = jsonObjectNull.opt("key"); - assertTrue("opt() null should find null", value == null); - if (value == null) { - value = ""; - } - string = value instanceof String ? (String) value : null; - assertTrue("should convert null to empty string", "".equals(string)); - try { - value = jsonObjectNull.get("key"); - assertTrue("get() null should throw exception", false); - } catch (final Exception ignored) { - } + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.keyInt"))); + assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(JsonPath.read(doc, "$.keyLong"))); + assertTrue("expected 3.1", Double.valueOf(3.1).equals(JsonPath.read(doc, "$.keyDouble"))); + assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(JsonPath.read(doc, "$.keyBigInt"))); + assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(JsonPath.read(doc, "$.keyBigDec"))); /** - * XML.toString() then goes on to do something with the value if the key - * val is "content", then value.toString() will be called. This will - * evaluate to "null" for JSONObject.NULL, and the empty string for - * null. But if the key is anything else, then JSONObject.NULL will be - * emitted as null and null will be emitted as "" + * Should work the same way on any platform! @see https://docs.oracle + * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is the + * effect of a float to double conversion and is inherent to the + * shortcomings of the IEEE 754 format, when converting 32-bit into + * double-precision 64-bit. Java type-casts float to double. A 32 bit + * float is type-casted to 64 bit double by simply appending zero-bits + * to the mantissa (and extended the signed exponent by 3 bits.) and + * there is no way to obtain more information than it is stored in the + * 32-bits float. + * + * Like 1/3 cannot be represented as base10 number because it is + * periodically, 1/5 (for example) cannot be represented as base2 number + * since it is periodically in base2 (take a look at + * http://www.h-schmidt.net/FloatConverter/) The same happens to 3.1, + * that decimal number (base10 representation) is periodic in base2 + * representation, therefore appending zero-bits is inaccurate. Only + * repeating the periodically occuring bits (0110) would be a proper + * conversion. However one cannot detect from a 32 bit IEE754 + * representation which bits would "repeat infinitely", since the + * missing bits would not fit into the 32 bit float, i.e. the + * information needed simply is not there! */ - final String sJONull = XML.toString(jsonObjectJONull); - assertTrue("JSONObject.NULL should emit a null value", - "null".equals(sJONull)); - final String sNull = XML.toString(jsonObjectNull); - assertTrue("null should emit an empty string", "".equals(sNull)); + assertTrue("expected 3.0999999046325684", Double.valueOf(3.0999999046325684).equals(JsonPath.read(doc, "$.keyFloat"))); + + /** + * float f = 3.1f; double df = (double) f; double d = 3.1d; + * System.out.println + * (Integer.toBinaryString(Float.floatToRawIntBits(f))); + * System.out.println + * (Long.toBinaryString(Double.doubleToRawLongBits(df))); + * System.out.println + * (Long.toBinaryString(Double.doubleToRawLongBits(d))); + * + * - Float: + * seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm + * 1000000010001100110011001100110 + * - Double + * seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + * 10000000 10001100110011001100110 + * 100000000001000110011001100110011000000000000000000000000000000 + * 100000000001000110011001100110011001100110011001100110011001101 + */ + + /** + * Examples of well documented but probably unexpected behavior in + * java / with 32-bit float to 64-bit float conversion. + */ + assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d ); + assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d ); + Double d1 = new Double( 1.1f ); + Double d2 = new Double( "1.1f" ); + assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); + + assertTrue( "Correctly converting float to double via base10 (string) representation!", new Double( 3.1d ).equals( new Double( new Float( 3.1f ).toString() ) ) ); + + // Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject + JSONObject jo = new JSONObject(); + jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double + assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); + + JSONObject inc = new JSONObject(); + inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) + assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); + inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! + // this.put(key, (Float) value + 1); + // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. + // 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects! + // 3. A float+float operation will be performed and results into a float primitive. + // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method + // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa + assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Double ); + // correct implementation (with change of behavior) would be: + // this.put(key, new Float((Float) value + 1)); + // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not + // really in the the scope of a JSON-library (IMHO.) + } /** @@ -1181,22 +1238,449 @@ public class JSONObjectTest { public void jsonObjectNumberToString() { String str; Double dVal; - final Integer iVal = 1; + Integer iVal = 1; str = JSONObject.numberToString(iVal); - assertTrue("expected " + iVal + " actual " + str, iVal.toString() - .equals(str)); + assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); dVal = 12.34; str = JSONObject.numberToString(dVal); - assertTrue("expected " + dVal + " actual " + str, dVal.toString() - .equals(str)); + assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); dVal = 12.34e27; str = JSONObject.numberToString(dVal); - assertTrue("expected " + dVal + " actual " + str, dVal.toString() - .equals(str)); + assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); // trailing .0 is truncated, so it doesn't quite match toString() dVal = 5000000.0000000; str = JSONObject.numberToString(dVal); - assertTrue("expected 5000000 actual " + str, str.equals("5000000")); + assertTrue("expected 5000000 actual "+str, str.equals("5000000")); + } + + /** + * Exercise JSONObject put() and similar() methods + */ + @Test + public void jsonObjectPut() { + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("trueKey", true); + jsonObject.put("falseKey", false); + Integer [] intArray = { 0, 1, 2 }; + jsonObject.put("arrayKey", Arrays.asList(intArray)); + Map myMap = new HashMap(); + myMap.put("myKey1", "myVal1"); + myMap.put("myKey2", "myVal2"); + myMap.put("myKey3", "myVal3"); + myMap.put("myKey4", "myVal4"); + jsonObject.put("objectKey", myMap); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); + assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); + assertTrue("expected myVal1", "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); + assertTrue("expected myVal2", "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); + assertTrue("expected myVal3", "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); + assertTrue("expected myVal4", "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); + + jsonObject.remove("trueKey"); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + assertTrue("unequal jsonObjects should not be similar", + !jsonObject.similar(expectedJsonObject)); + assertTrue("jsonObject should not be similar to jsonArray", + !jsonObject.similar(new JSONArray())); + + String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; + String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; + JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); + JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); + assertTrue("different values should not be similar", + !aCompareValueJsonObject.similar(bCompareValueJsonObject)); + + String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; + String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; + JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); + JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); + assertTrue("different nested JSONObjects should not be similar", + !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); + + String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; + String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; + JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); + JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); + assertTrue("different nested JSONArrays should not be similar", + !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); + } + + /** + * Exercise JSONObject toString() method + */ + @Test + public void jsonObjectToString() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); + assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); + assertTrue("expected myVal1", "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); + assertTrue("expected myVal2", "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); + assertTrue("expected myVal3", "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); + assertTrue("expected myVal4", "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); + } + + /** + * Explores how JSONObject handles maps. Insert a string/string map + * as a value in a JSONObject. It will remain a map. Convert the + * JSONObject to string, then create a new JSONObject from the string. + * In the new JSONObject, the value will be stored as a nested JSONObject. + * Confirm that map and nested JSONObject have the same contents. + */ + @Test + public void jsonObjectToStringSuppressWarningOnCastToMap() { + JSONObject jsonObject = new JSONObject(); + Map map = new HashMap<>(); + map.put("abc", "def"); + jsonObject.put("key", map); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 1 key item", ((Map)(JsonPath.read(doc, "$.key"))).size() == 1); + assertTrue("expected def", "def".equals(JsonPath.read(doc, "$.key.abc"))); + } + + /** + * Explores how JSONObject handles collections. Insert a string collection + * as a value in a JSONObject. It will remain a collection. Convert the + * JSONObject to string, then create a new JSONObject from the string. + * In the new JSONObject, the value will be stored as a nested JSONArray. + * Confirm that collection and nested JSONArray have the same contents. + */ + @Test + public void jsonObjectToStringSuppressWarningOnCastToCollection() { + JSONObject jsonObject = new JSONObject(); + Collection collection = new ArrayList(); + collection.add("abc"); + // ArrayList will be added as an object + jsonObject.put("key", collection); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 1 key item", ((List)(JsonPath.read(doc, "$.key"))).size() == 1); + assertTrue("expected abc", "abc".equals(JsonPath.read(doc, "$.key[0]"))); + } + + /** + * Exercises the JSONObject.valueToString() method for various types + */ + @Test + public void valueToString() { + + assertTrue("null valueToString() incorrect", + "null".equals(JSONObject.valueToString(null))); + MyJsonString jsonString = new MyJsonString(); + assertTrue("jsonstring valueToString() incorrect", + "my string".equals(JSONObject.valueToString(jsonString))); + assertTrue("boolean valueToString() incorrect", + "true".equals(JSONObject.valueToString(Boolean.TRUE))); + assertTrue("non-numeric double", + "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); + String jsonObjectStr = + "{"+ + "\"key1\":\"val1\","+ + "\"key2\":\"val2\","+ + "\"key3\":\"val3\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("jsonObject valueToString() incorrect", + JSONObject.valueToString(jsonObject).equals(jsonObject.toString())); + String jsonArrayStr = + "[1,2,3]"; + JSONArray jsonArray = new JSONArray(jsonArrayStr); + assertTrue("jsonArra valueToString() incorrect", + JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); + Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + assertTrue("map valueToString() incorrect", + jsonObject.toString().equals(JSONObject.valueToString(map))); + Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + assertTrue("collection valueToString() expected: "+ + jsonArray.toString()+ " actual: "+ + JSONObject.valueToString(collection), + jsonArray.toString().equals(JSONObject.valueToString(collection))); + Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; + assertTrue("array valueToString() incorrect", + jsonArray.toString().equals(JSONObject.valueToString(array))); + } + + /** + * Confirm that https://github.com/douglascrockford/JSON-java/issues/167 is fixed. + * The following code was throwing a ClassCastException in the + * JSONObject(Map) constructor + */ + @Test + public void valueToStringConfirmException() { + Map myMap = new HashMap(); + myMap.put(1, "myValue"); + // this is the test, it should not throw an exception + String str = JSONObject.valueToString(myMap); + // confirm result, just in case + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1"))); + } + + /** + * Exercise the JSONObject wrap() method. Sometimes wrap() will change + * the object being wrapped, other times not. The purpose of wrap() is + * to ensure the value is packaged in a way that is compatible with how + * a JSONObject value or JSONArray value is supposed to be stored. + */ + @Test + public void wrapObject() { + // wrap(null) returns NULL + assertTrue("null wrap() incorrect", + JSONObject.NULL == JSONObject.wrap(null)); + + // wrap(Integer) returns Integer + Integer in = new Integer(1); + assertTrue("Integer wrap() incorrect", + in == JSONObject.wrap(in)); + + /** + * This test is to document the preferred behavior if BigDecimal is + * supported. Previously bd returned as a string, since it + * is recognized as being a Java package class. Now with explicit + * support for big numbers, it remains a BigDecimal + */ + Object bdWrap = JSONObject.wrap(BigDecimal.ONE); + assertTrue("BigDecimal.ONE evaluates to ONE", + bdWrap.equals(BigDecimal.ONE)); + + // wrap JSONObject returns JSONObject + String jsonObjectStr = + "{"+ + "\"key1\":\"val1\","+ + "\"key2\":\"val2\","+ + "\"key3\":\"val3\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("JSONObject wrap() incorrect", + jsonObject == JSONObject.wrap(jsonObject)); + + // wrap collection returns JSONArray + Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + JSONArray jsonArray = (JSONArray) (JSONObject.wrap(collection)); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + + // wrap Array returns JSONArray + Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; + JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); + assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + + // wrap map returns JSONObject + Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + JSONObject mapJsonObject = (JSONObject) (JSONObject.wrap(map)); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString()); + assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected val1", "val1".equals(JsonPath.read(doc, "$.key1"))); + assertTrue("expected val2", "val2".equals(JsonPath.read(doc, "$.key2"))); + assertTrue("expected val3", "val3".equals(JsonPath.read(doc, "$.key3"))); + } + + /** + * Explore how JSONObject handles parsing errors. + */ + @Test + public void jsonObjectParsingErrors() { + try { + // does not start with '{' + String str = "abc"; + new JSONObject(str); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "A JSONObject text must begin with '{' at 1 [character 2 line 1]". + equals(e.getMessage())); + } + try { + // does not end with '}' + String str = "{"; + new JSONObject(str); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "A JSONObject text must end with '}' at 2 [character 3 line 1]". + equals(e.getMessage())); + } + try { + // key with no ':' + String str = "{\"myKey\" = true}"; + new JSONObject(str); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Expected a ':' after a key at 10 [character 11 line 1]". + equals(e.getMessage())); + } + try { + // entries with no ',' separator + String str = "{\"myKey\":true \"myOtherKey\":false}"; + new JSONObject(str); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Expected a ',' or '}' at 15 [character 16 line 1]". + equals(e.getMessage())); + } + try { + // append to wrong key + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.append("myKey", "hello"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[myKey] is not a JSONArray.". + equals(e.getMessage())); + } + try { + // increment wrong key + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("myKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Unable to increment [\"myKey\"].". + equals(e.getMessage())); + } + try { + // invalid key + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.get(null); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Null key.". + equals(e.getMessage())); + } + try { + // invalid numberToString() + JSONObject.numberToString((Number)null); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Null pointer". + equals(e.getMessage())); + } + try { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0); + assertTrue("Expected an exception", false); + } catch (NullPointerException ignored) { + } + try { + // multiple putOnce key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.putOnce("hello", "world"); + jsonObject.putOnce("hello", "world!"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("", true); + } + try { + // test validity of invalid double + JSONObject.testValidity(Double.NaN); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("", true); + } + try { + // test validity of invalid float + JSONObject.testValidity(Float.NEGATIVE_INFINITY); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("", true); + } + } + + /** + * Confirm behavior when putOnce() is called with null parameters + */ + @Test + public void jsonObjectPutOnceNull() { + JSONObject jsonObject = new JSONObject(); + jsonObject.putOnce(null, null); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** @@ -1205,8 +1689,8 @@ public class JSONObjectTest { @Test public void jsonObjectOptDefault() { - final String str = "{\"myKey\": \"myval\"}"; - final JSONObject jsonObject = new JSONObject(str); + String str = "{\"myKey\": \"myval\"}"; + JSONObject jsonObject = new JSONObject(str); assertTrue("optBoolean() should return default boolean", Boolean.TRUE == jsonObject.optBoolean("myKey", Boolean.TRUE)); @@ -1222,207 +1706,6 @@ public class JSONObjectTest { "hi".equals(jsonObject.optString("hiKey", "hi"))); } - /** - * Explore how JSONObject handles parsing errors. - */ - @Test - public void jsonObjectParsingErrors() { - try { - // does not start with '{' - final String str = "abc"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "A JSONObject text must begin with '{' at 1 [character 2 line 1]" - .equals(e.getMessage())); - } - try { - // does not end with '}' - final String str = "{"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "A JSONObject text must end with '}' at 2 [character 3 line 1]" - .equals(e.getMessage())); - } - try { - // key with no ':' - final String str = "{\"myKey\" = true}"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "Expected a ':' after a key at 10 [character 11 line 1]" - .equals(e.getMessage())); - } - try { - // entries with no ',' separator - final String str = "{\"myKey\":true \"myOtherKey\":false}"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "Expected a ',' or '}' at 15 [character 16 line 1]" - .equals(e.getMessage())); - } - try { - // append to wrong key - final String str = "{\"myKey\":true, \"myOtherKey\":false}"; - final JSONObject jsonObject = new JSONObject(str); - jsonObject.append("myKey", "hello"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[myKey] is not a JSONArray.".equals(e - .getMessage())); - } - try { - // increment wrong key - final String str = "{\"myKey\":true, \"myOtherKey\":false}"; - final JSONObject jsonObject = new JSONObject(str); - jsonObject.increment("myKey"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "Unable to increment [\"myKey\"].".equals(e.getMessage())); - } - try { - // invalid key - final String str = "{\"myKey\":true, \"myOtherKey\":false}"; - final JSONObject jsonObject = new JSONObject(str); - jsonObject.get(null); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "Null key.".equals(e.getMessage())); - } - try { - // invalid numberToString() - JSONObject.numberToString((Number) null); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("Expecting an exception message", - "Null pointer".equals(e.getMessage())); - } - try { - // null put key - final JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, 0); - assertTrue("Expected an exception", false); - } catch (final NullPointerException ignored) { - } - try { - // multiple putOnce key - final JSONObject jsonObject = new JSONObject("{}"); - jsonObject.putOnce("hello", "world"); - jsonObject.putOnce("hello", "world!"); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("", true); - } - try { - // test validity of invalid double - JSONObject.testValidity(Double.NaN); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("", true); - } - try { - // test validity of invalid float - JSONObject.testValidity(Float.NEGATIVE_INFINITY); - assertTrue("Expected an exception", false); - } catch (final JSONException e) { - assertTrue("", true); - } - } - - /** - * Exercise JSONObject put() and similar() methods - */ - @Test - public void jsonObjectPut() { - final String expectedStr = "{" + "\"trueKey\":true," - + "\"falseKey\":false," + "\"arrayKey\":[0,1,2]," - + "\"objectKey\":{" + "\"myKey1\":\"myVal1\"," - + "\"myKey2\":\"myVal2\"," + "\"myKey3\":\"myVal3\"," - + "\"myKey4\":\"myVal4\"" + "}" + "}"; - final JSONObject jsonObject = new JSONObject(); - jsonObject.put("trueKey", true); - jsonObject.put("falseKey", false); - final Integer[] intArray = { 0, 1, 2 }; - jsonObject.put("arrayKey", Arrays.asList(intArray)); - final Map myMap = new HashMap(); - myMap.put("myKey1", "myVal1"); - myMap.put("myKey2", "myVal2"); - myMap.put("myKey3", "myVal3"); - myMap.put("myKey4", "myVal4"); - jsonObject.put("objectKey", myMap); - - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 4 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 4); - assertTrue("expected true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected 3 arrayKey items", - ((List) JsonPath.read(doc, "$.arrayKey")).size() == 3); - assertTrue("expected 0", - Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); - assertTrue("expected 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); - assertTrue("expected 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); - assertTrue("expected 4 objectKey items", - ((Map) JsonPath.read(doc, "$.objectKey")).size() == 4); - assertTrue("expected myVal1", - "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); - assertTrue("expected myVal2", - "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); - assertTrue("expected myVal3", - "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); - assertTrue("expected myVal4", - "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); - - jsonObject.remove("trueKey"); - final JSONObject expectedJsonObject = new JSONObject(expectedStr); - assertTrue("unequal jsonObjects should not be similar", - !jsonObject.similar(expectedJsonObject)); - assertTrue("jsonObject should not be similar to jsonArray", - !jsonObject.similar(new JSONArray())); - - final String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; - final String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; - final JSONObject aCompareValueJsonObject = new JSONObject( - aCompareValueStr); - final JSONObject bCompareValueJsonObject = new JSONObject( - bCompareValueStr); - assertTrue("different values should not be similar", - !aCompareValueJsonObject.similar(bCompareValueJsonObject)); - - final String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; - final String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; - final JSONObject aCompareObjectJsonObject = new JSONObject( - aCompareObjectStr); - final JSONObject bCompareObjectJsonObject = new JSONObject( - bCompareObjectStr); - assertTrue("different nested JSONObjects should not be similar", - !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); - - final String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; - final String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; - final JSONObject aCompareArrayJsonObject = new JSONObject( - aCompareArrayStr); - final JSONObject bCompareArrayJsonObject = new JSONObject( - bCompareArrayStr); - assertTrue("different nested JSONArrays should not be similar", - !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); - } - /** * Confirm behavior when JSONObject put(key, null object) is called */ @@ -1430,11 +1713,11 @@ public class JSONObjectTest { public void jsonObjectputNull() { // put null should remove the item. - final String str = "{\"myKey\": \"myval\"}"; - final JSONObject jsonObjectRemove = new JSONObject(str); + String str = "{\"myKey\": \"myval\"}"; + JSONObject jsonObjectRemove = new JSONObject(str); jsonObjectRemove.remove("myKey"); - final JSONObject jsonObjectPutNull = new JSONObject(str); + JSONObject jsonObjectPutNull = new JSONObject(str); jsonObjectPutNull.put("myKey", (Object) null); // validate JSON @@ -1443,18 +1726,9 @@ public class JSONObjectTest { } /** - * Confirm behavior when putOnce() is called with null parameters - */ - @Test - public void jsonObjectPutOnceNull() { - final JSONObject jsonObject = new JSONObject(); - jsonObject.putOnce(null, null); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); - } - - /** - * Exercise JSONObject quote() method This purpose of quote() is to ensure - * that for strings with embedded quotes, the quotes are properly escaped. + * Exercise JSONObject quote() method + * This purpose of quote() is to ensure that for strings with embedded + * quotes, the quotes are properly escaped. */ @Test public void jsonObjectQuote() { @@ -1462,281 +1736,50 @@ public class JSONObjectTest { str = ""; String quotedStr; quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found " + quotedStr, + assertTrue("quote() expected escaped quotes, found "+quotedStr, "\"\"".equals(quotedStr)); str = "\"\""; quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found " + quotedStr, + assertTrue("quote() expected escaped quotes, found "+quotedStr, "\"\\\"\\\"\"".equals(quotedStr)); str = ") JsonPath.read(doc, "$")).size() == 4); - assertTrue("expected true", - Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected false", - Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected 3 arrayKey items", - ((List) JsonPath.read(doc, "$.arrayKey")).size() == 3); - assertTrue("expected 0", - Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); - assertTrue("expected 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); - assertTrue("expected 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); - assertTrue("expected 4 objectKey items", - ((Map) JsonPath.read(doc, "$.objectKey")).size() == 4); - assertTrue("expected myVal1", - "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); - assertTrue("expected myVal2", - "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); - assertTrue("expected myVal3", - "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); - assertTrue("expected myVal4", - "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); - } - - /** - * Explores how JSONObject handles collections. Insert a string collection - * as a value in a JSONObject. It will remain a collection. Convert the - * JSONObject to string, then create a new JSONObject from the string. In - * the new JSONObject, the value will be stored as a nested JSONArray. - * Confirm that collection and nested JSONArray have the same contents. - */ - @Test - public void jsonObjectToStringSuppressWarningOnCastToCollection() { - final JSONObject jsonObject = new JSONObject(); - final Collection collection = new ArrayList(); - collection.add("abc"); - // ArrayList will be added as an object - jsonObject.put("key", collection); - - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 1 top level item", - ((Map) JsonPath.read(doc, "$")).size() == 1); - assertTrue("expected 1 key item", - ((List) JsonPath.read(doc, "$.key")).size() == 1); - assertTrue("expected abc", "abc".equals(JsonPath.read(doc, "$.key[0]"))); - } - - /** - * Explores how JSONObject handles maps. Insert a string/string map as a - * value in a JSONObject. It will remain a map. Convert the JSONObject to - * string, then create a new JSONObject from the string. In the new - * JSONObject, the value will be stored as a nested JSONObject. Confirm that - * map and nested JSONObject have the same contents. - */ - @Test - public void jsonObjectToStringSuppressWarningOnCastToMap() { - final JSONObject jsonObject = new JSONObject(); - final Map map = new HashMap<>(); - map.put("abc", "def"); - jsonObject.put("key", map); - - // validate JSON - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonObject.toString()); - assertTrue("expected 1 top level item", - ((Map) JsonPath.read(doc, "$")).size() == 1); - assertTrue("expected 1 key item", - ((Map) JsonPath.read(doc, "$.key")).size() == 1); - assertTrue("expected def", - "def".equals(JsonPath.read(doc, "$.key.abc"))); - } - - /** - * Exercise some JSONObject get[type] and opt[type] methods - */ - @Test - public void jsonObjectValues() { - final String str = "{" + "\"trueKey\":true," + "\"falseKey\":false," - + "\"trueStrKey\":\"true\"," + "\"falseStrKey\":\"false\"," - + "\"stringKey\":\"hello world!\"," + "\"intKey\":42," - + "\"intStrKey\":\"43\"," + "\"longKey\":1234567890123456789," - + "\"longStrKey\":\"987654321098765432\"," - + "\"doubleKey\":-23.45e7," + "\"doubleStrKey\":\"00001.000\"," - + "\"arrayKey\":[0,1,2]," - + "\"objectKey\":{\"myKey\":\"myVal\"}" + "}"; - final JSONObject jsonObject = new JSONObject(str); - assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); - assertTrue("opt trueKey should be true", - jsonObject.optBoolean("trueKey")); - assertTrue("falseKey should be false", - !jsonObject.getBoolean("falseKey")); - assertTrue("trueStrKey should be true", - jsonObject.getBoolean("trueStrKey")); - assertTrue("trueStrKey should be true", - jsonObject.optBoolean("trueStrKey")); - assertTrue("falseStrKey should be false", - !jsonObject.getBoolean("falseStrKey")); - assertTrue("stringKey should be string", - jsonObject.getString("stringKey").equals("hello world!")); - assertTrue("doubleKey should be double", - jsonObject.getDouble("doubleKey") == -23.45e7); - assertTrue("doubleStrKey should be double", - jsonObject.getDouble("doubleStrKey") == 1); - assertTrue("opt doubleKey should be double", - jsonObject.optDouble("doubleKey") == -23.45e7); - assertTrue("opt doubleKey with Default should be double", - jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); - assertTrue("intKey should be int", jsonObject.optInt("intKey") == 42); - assertTrue("opt intKey should be int", - jsonObject.optInt("intKey", 0) == 42); - assertTrue("opt intKey with default should be int", - jsonObject.getInt("intKey") == 42); - assertTrue("intStrKey should be int", - jsonObject.getInt("intStrKey") == 43); - assertTrue("longKey should be long", - jsonObject.getLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey should be long", - jsonObject.optLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey with default should be long", - jsonObject.optLong("longKey", 0) == 1234567890123456789L); - assertTrue("longStrKey should be long", - jsonObject.getLong("longStrKey") == 987654321098765432L); - assertTrue("xKey should not exist", jsonObject.isNull("xKey")); - assertTrue("stringKey should exist", jsonObject.has("stringKey")); - assertTrue("opt stringKey should string", - jsonObject.optString("stringKey").equals("hello world!")); - assertTrue("opt stringKey with default should string", jsonObject - .optString("stringKey", "not found").equals("hello world!")); - JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); - assertTrue("arrayKey should be JSONArray", jsonArray.getInt(0) == 0 - && jsonArray.getInt(1) == 1 && jsonArray.getInt(2) == 2); - jsonArray = jsonObject.optJSONArray("arrayKey"); - assertTrue("opt arrayKey should be JSONArray", jsonArray.getInt(0) == 0 - && jsonArray.getInt(1) == 1 && jsonArray.getInt(2) == 2); - final JSONObject jsonObjectInner = jsonObject - .getJSONObject("objectKey"); - assertTrue("objectKey should be JSONObject", - jsonObjectInner.get("myKey").equals("myVal")); - } - - /** - * This test documents numeric values which could be numerically handled as - * BigDecimal or BigInteger. It helps determine what outputs will change if - * those types are supported. - */ - @Test - public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { - // Valid JSON Numbers, probably should return BigDecimal or BigInteger - // objects - final String str = "{" + "\"numberWithDecimals\":299792.457999999984," - + "\"largeNumber\":12345678901234567890," - + "\"preciseNumber\":0.2000000000000000111," - + "\"largeExponent\":-23.45e2327" + "}"; - final JSONObject jsonObject = new JSONObject(str); - // Comes back as a double, but loses precision - assertTrue( - "numberWithDecimals currently evaluates to double 299792.458", - jsonObject.get("numberWithDecimals").equals( - new Double("299792.458"))); - Object obj = jsonObject.get("largeNumber"); - assertTrue("largeNumber currently evaluates to string", - "12345678901234567890".equals(obj)); - // comes back as a double but loses precision - assertTrue("preciseNumber currently evaluates to double 0.2", - jsonObject.get("preciseNumber").equals(new Double(0.2))); - obj = jsonObject.get("largeExponent"); - assertTrue("largeExponent should currently evaluates as a string", - "-23.45e2327".equals(obj)); - } - - /** - * Confirm behavior when JSONObject stringToValue() is called for an empty - * string + * Confirm behavior when JSONObject stringToValue() is called for an + * empty string */ @Test public void stringToValue() { - final String str = ""; - final String valueStr = (String) JSONObject.stringToValue(str); - assertTrue("stringToValue() expected empty String, found " + valueStr, + String str = ""; + String valueStr = (String)(JSONObject.stringToValue(str)); + assertTrue("stringToValue() expected empty String, found "+valueStr, "".equals(valueStr)); } - /** - * Check whether JSONObject handles large or high precision numbers - * correctly - */ - @Test - public void stringToValueNumbersTest() { - assertTrue("-0 Should be a Double!", - JSONObject.stringToValue("-0") instanceof Double); - assertTrue("-0 Should be a Double!", - JSONObject.stringToValue("-0.0") instanceof Double); - assertTrue("'-' Should be a String!", - JSONObject.stringToValue("-") instanceof String); - assertTrue("0.2 should be a Double!", - JSONObject.stringToValue("0.2") instanceof Double); - assertTrue( - "Doubles should be Doubles, even when incorrectly converting floats!", - JSONObject.stringToValue(new Double("0.2f").toString()) instanceof Double); - /** - * This test documents a need for BigDecimal conversion. - */ - final Object obj = JSONObject.stringToValue("299792.457999999984"); - assertTrue( - "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!", - obj.equals(new Double(299792.458))); - assertTrue("1 should be an Integer!", - JSONObject.stringToValue("1") instanceof Integer); - assertTrue("Integer.MAX_VALUE should still be an Integer!", - JSONObject.stringToValue(new Integer(Integer.MAX_VALUE) - .toString()) instanceof Integer); - assertTrue("Large integers should be a Long!", - JSONObject.stringToValue(new Long(Long - .sum(Integer.MAX_VALUE, 1)).toString()) instanceof Long); - assertTrue( - "Long.MAX_VALUE should still be an Integer!", - JSONObject.stringToValue(new Long(Long.MAX_VALUE).toString()) instanceof Long); - - final String str = new BigInteger(new Long(Long.MAX_VALUE).toString()) - .add(BigInteger.ONE).toString(); - assertTrue("Really large integers currently evaluate to string", - JSONObject.stringToValue(str).equals("9223372036854775808")); - } - /** * Confirm behavior when toJSONArray is called with a null value */ @@ -1746,330 +1789,114 @@ public class JSONObjectTest { null == new JSONObject().toJSONArray(null)); } - /** - * This test documents an unexpected numeric behavior. A double that ends - * with .0 is parsed, serialized, then parsed again. On the second parse, it - * has become an int. - */ - @Test - public void unexpectedDoubleToIntConversion() { - final String key30 = "key30"; - final String key31 = "key31"; - final JSONObject jsonObject = new JSONObject(); - jsonObject.put(key30, new Double(3.0)); - jsonObject.put(key31, new Double(3.1)); - - assertTrue("3.0 should remain a double", - jsonObject.getDouble(key30) == 3); - assertTrue("3.1 should remain a double", - jsonObject.getDouble(key31) == 3.1); - - // turns 3.0 into 3. - final String serializedString = jsonObject.toString(); - final JSONObject deserialized = new JSONObject(serializedString); - assertTrue("3.0 is now an int", - deserialized.get(key30) instanceof Integer); - assertTrue("3.0 can still be interpreted as a double", - deserialized.getDouble(key30) == 3.0); - assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); - } - - /** - * Exercises the JSONObject.valueToString() method for various types - */ - @Test - public void valueToString() { - - assertTrue("null valueToString() incorrect", - "null".equals(JSONObject.valueToString(null))); - final MyJsonString jsonString = new MyJsonString(); - assertTrue("jsonstring valueToString() incorrect", - "my string".equals(JSONObject.valueToString(jsonString))); - assertTrue("boolean valueToString() incorrect", - "true".equals(JSONObject.valueToString(Boolean.TRUE))); - assertTrue("non-numeric double", "null".equals(JSONObject - .doubleToString(Double.POSITIVE_INFINITY))); - final String jsonObjectStr = "{" + "\"key1\":\"val1\"," - + "\"key2\":\"val2\"," + "\"key3\":\"val3\"" + "}"; - final JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("jsonObject valueToString() incorrect", JSONObject - .valueToString(jsonObject).equals(jsonObject.toString())); - final String jsonArrayStr = "[1,2,3]"; - final JSONArray jsonArray = new JSONArray(jsonArrayStr); - assertTrue("jsonArra valueToString() incorrect", JSONObject - .valueToString(jsonArray).equals(jsonArray.toString())); - final Map map = new HashMap(); - map.put("key1", "val1"); - map.put("key2", "val2"); - map.put("key3", "val3"); - assertTrue("map valueToString() incorrect", jsonObject.toString() - .equals(JSONObject.valueToString(map))); - final Collection collection = new ArrayList(); - collection.add(new Integer(1)); - collection.add(new Integer(2)); - collection.add(new Integer(3)); - assertTrue( - "collection valueToString() expected: " + jsonArray.toString() - + " actual: " + JSONObject.valueToString(collection), - jsonArray.toString().equals( - JSONObject.valueToString(collection))); - final Integer[] array = { new Integer(1), new Integer(2), - new Integer(3) }; - assertTrue("array valueToString() incorrect", jsonArray.toString() - .equals(JSONObject.valueToString(array))); - } - - /** - * Confirm that https://github.com/douglascrockford/JSON-java/issues/167 is - * fixed. The following code was throwing a ClassCastException in the - * JSONObject(Map) constructor - */ - @Test - public void valueToStringConfirmException() { - final Map myMap = new HashMap(); - myMap.put(1, "myValue"); - // this is the test, it should not throw an exception - final String str = JSONObject.valueToString(myMap); - // confirm result, just in case - final Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(str); - assertTrue("expected 1 top level item", - ((Map) JsonPath.read(doc, "$")).size() == 1); - assertTrue("expected myValue", - "myValue".equals(JsonPath.read(doc, "$.1"))); - } - - /** - * Verifies that the constructor has backwards compatability with RAW types - * pre-java5. - */ - @Test - public void verifyConstructor() { - - final JSONObject expected = new JSONObject("{\"myKey\":10}"); - - @SuppressWarnings("rawtypes") - final Map myRawC = Collections.singletonMap("myKey", - Integer.valueOf(10)); - final JSONObject jaRaw = new JSONObject(myRawC); - - final Map myCStrObj = Collections.singletonMap("myKey", - (Object) Integer.valueOf(10)); - final JSONObject jaStrObj = new JSONObject(myCStrObj); - - final Map myCStrInt = Collections.singletonMap( - "myKey", Integer.valueOf(10)); - final JSONObject jaStrInt = new JSONObject(myCStrInt); - - final Map myCObjObj = Collections.singletonMap((Object) "myKey", - (Object) Integer.valueOf(10)); - final JSONObject jaObjObj = new JSONObject(myCObjObj); - - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); - } - - /** - * Verifies that the put Collection has backwards compatability with RAW - * types pre-java5. - */ - @Test - public void verifyPutCollection() { - - final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); - - @SuppressWarnings("rawtypes") - final Collection myRawC = Collections.singleton(Integer.valueOf(10)); - final JSONObject jaRaw = new JSONObject(); - jaRaw.put("myCollection", myRawC); - - final Collection myCObj = Collections - .singleton((Object) Integer.valueOf(10)); - final JSONObject jaObj = new JSONObject(); - jaObj.put("myCollection", myCObj); - - final Collection myCInt = Collections.singleton(Integer - .valueOf(10)); - final JSONObject jaInt = new JSONObject(); - jaInt.put("myCollection", myCInt); - - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaInt)); - } - - /** - * Verifies that the put Map has backwards compatability with RAW types - * pre-java5. - */ - @Test - public void verifyPutMap() { - - final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); - - @SuppressWarnings("rawtypes") - final Map myRawC = Collections.singletonMap("myKey", - Integer.valueOf(10)); - final JSONObject jaRaw = new JSONObject(); - jaRaw.put("myMap", myRawC); - - final Map myCStrObj = Collections.singletonMap("myKey", - (Object) Integer.valueOf(10)); - final JSONObject jaStrObj = new JSONObject(); - jaStrObj.put("myMap", myCStrObj); - - final Map myCStrInt = Collections.singletonMap( - "myKey", Integer.valueOf(10)); - final JSONObject jaStrInt = new JSONObject(); - jaStrInt.put("myMap", myCStrInt); - - final Map myCObjObj = Collections.singletonMap((Object) "myKey", - (Object) Integer.valueOf(10)); - final JSONObject jaObjObj = new JSONObject(); - jaObjObj.put("myMap", myCObjObj); - - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); - } - - /** - * Exercise the JSONObject wrap() method. Sometimes wrap() will change the - * object being wrapped, other times not. The purpose of wrap() is to ensure - * the value is packaged in a way that is compatible with how a JSONObject - * value or JSONArray value is supposed to be stored. - */ - @Test - public void wrapObject() { - // wrap(null) returns NULL - assertTrue("null wrap() incorrect", - JSONObject.NULL == JSONObject.wrap(null)); - - // wrap(Integer) returns Integer - final Integer in = new Integer(1); - assertTrue("Integer wrap() incorrect", in == JSONObject.wrap(in)); - - /** - * This test is to document the preferred behavior if BigDecimal is - * supported. Previously bd returned as a string, since it is recognized - * as being a Java package class. Now with explicit support for big - * numbers, it remains a BigDecimal - */ - final Object bdWrap = JSONObject.wrap(BigDecimal.ONE); - assertTrue("BigDecimal.ONE evaluates to ONE", - bdWrap.equals(BigDecimal.ONE)); - - // wrap JSONObject returns JSONObject - final String jsonObjectStr = "{" + "\"key1\":\"val1\"," - + "\"key2\":\"val2\"," + "\"key3\":\"val3\"" + "}"; - final JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("JSONObject wrap() incorrect", - jsonObject == JSONObject.wrap(jsonObject)); - - // wrap collection returns JSONArray - final Collection collection = new ArrayList(); - collection.add(new Integer(1)); - collection.add(new Integer(2)); - collection.add(new Integer(3)); - final JSONArray jsonArray = (JSONArray) JSONObject.wrap(collection); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - assertTrue("expected 3 top level items", - ((List) JsonPath.read(doc, "$")).size() == 3); - assertTrue("expected 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", - Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); - - // wrap Array returns JSONArray - final Integer[] array = { new Integer(1), new Integer(2), - new Integer(3) }; - final JSONArray integerArrayJsonArray = (JSONArray) JSONObject - .wrap(array); - - // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - assertTrue("expected 3 top level items", - ((List) JsonPath.read(doc, "$")).size() == 3); - assertTrue("expected 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", - Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); - - // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider() - .parse(integerArrayJsonArray.toString()); - assertTrue("expected 3 top level items", - ((List) JsonPath.read(doc, "$")).size() == 3); - assertTrue("expected 1", - Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", - Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", - Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); - - // wrap map returns JSONObject - final Map map = new HashMap(); - map.put("key1", "val1"); - map.put("key2", "val2"); - map.put("key3", "val3"); - final JSONObject mapJsonObject = (JSONObject) JSONObject.wrap(map); - - // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider() - .parse(mapJsonObject.toString()); - assertTrue("expected 3 top level items", - ((Map) JsonPath.read(doc, "$")).size() == 3); - assertTrue("expected val1", "val1".equals(JsonPath.read(doc, "$.key1"))); - assertTrue("expected val2", "val2".equals(JsonPath.read(doc, "$.key2"))); - assertTrue("expected val3", "val3".equals(JsonPath.read(doc, "$.key3"))); - } - /** * Exercise the JSONObject write() method */ @Test public void write() { - final String str = "{\"key\":\"value\"}"; - final String expectedStr = str; - final JSONObject jsonObject = new JSONObject(str); - final StringWriter stringWriter = new StringWriter(); - final Writer writer = jsonObject.write(stringWriter); - final String actualStr = writer.toString(); - assertTrue( - "write() expected " + expectedStr + "but found " + actualStr, + String str = "{\"key\":\"value\"}"; + String expectedStr = str; + JSONObject jsonObject = new JSONObject(str); + StringWriter stringWriter = new StringWriter(); + Writer writer = jsonObject.write(stringWriter); + String actualStr = writer.toString(); + assertTrue("write() expected " +expectedStr+ + "but found " +actualStr, expectedStr.equals(actualStr)); } + + /** + * Exercise the JSONObject equals() method + */ + @Test + public void equals() { + String str = "{\"key\":\"value\"}"; + JSONObject aJsonObject = new JSONObject(str); + assertTrue("Same JSONObject should be equal to itself", + aJsonObject.equals(aJsonObject)); + } + + /** + * JSON null is not the same as Java null. This test examines the differences + * in how they are handled by JSON-java. + */ + @Test + public void jsonObjectNullOperations() { + /** + * The Javadoc for JSONObject.NULL states: + * "JSONObject.NULL is equivalent to the value that JavaScript calls null, + * whilst Java's null is equivalent to the value that JavaScript calls + * undefined." + * + * Standard ECMA-262 6th Edition / June 2015 (included to help explain the javadoc): + * undefined value: primitive value used when a variable has not been assigned a value + * Undefined type: type whose sole value is the undefined value + * null value: primitive value that represents the intentional absence of any object value + * Null type: type whose sole value is the null value + * Java SE8 language spec (included to help explain the javadoc): + * The Kinds of Types and Values ... + * There is also a special null type, the type of the expression null, which has no name. + * Because the null type has no name, it is impossible to declare a variable of the null + * type or to cast to the null type. The null reference is the only possible value of an + * expression of null type. The null reference can always be assigned or cast to any reference type. + * In practice, the programmer can ignore the null type and just pretend that null is merely + * a special literal that can be of any reference type. + * Extensible Markup Language (XML) 1.0 Fifth Edition / 26 November 2008 + * No mention of null + * ECMA-404 1st Edition / October 2013: + * JSON Text ... + * These are three literal name tokens: ... + * null + * + * There seems to be no best practice to follow, it's all about what we + * want the code to do. + */ + + // add JSONObject.NULL then convert to string in the manner of XML.toString() + JSONObject jsonObjectJONull = new JSONObject(); + Object obj = JSONObject.NULL; + jsonObjectJONull.put("key", obj); + Object value = jsonObjectJONull.opt("key"); + assertTrue("opt() JSONObject.NULL should find JSONObject.NULL", + obj.equals(value)); + value = jsonObjectJONull.get("key"); + assertTrue("get() JSONObject.NULL should find JSONObject.NULL", + obj.equals(value)); + if (value == null) { + value = ""; + } + String string = value instanceof String ? (String)value : null; + assertTrue("XML toString() should convert JSONObject.NULL to null", + string == null); + + // now try it with null + JSONObject jsonObjectNull = new JSONObject(); + obj = null; + jsonObjectNull.put("key", obj); + value = jsonObjectNull.opt("key"); + assertTrue("opt() null should find null", value == null); + if (value == null) { + value = ""; + } + string = value instanceof String ? (String)value : null; + assertTrue("should convert null to empty string", "".equals(string)); + try { + value = jsonObjectNull.get("key"); + assertTrue("get() null should throw exception", false); + } catch (Exception ignored) {} + + /** + * XML.toString() then goes on to do something with the value + * if the key val is "content", then value.toString() will be + * called. This will evaluate to "null" for JSONObject.NULL, + * and the empty string for null. + * But if the key is anything else, then JSONObject.NULL will be emitted + * as null and null will be emitted as "" + */ + String sJONull = XML.toString(jsonObjectJONull); + assertTrue("JSONObject.NULL should emit a null value", + "null".equals(sJONull)); + String sNull = XML.toString(jsonObjectNull); + assertTrue("null should emit an empty string", "".equals(sNull)); + } } From 974c09b22a762304cd2ed17a3f73d20f3a0a6c08 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 27 Jan 2016 15:02:37 -0500 Subject: [PATCH 193/451] Fixes typo in assert --- src/test/org/json/junit/JSONObjectTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/org/json/junit/JSONObjectTest.java b/src/test/org/json/junit/JSONObjectTest.java index 5eedf1a..869fe46 100644 --- a/src/test/org/json/junit/JSONObjectTest.java +++ b/src/test/org/json/junit/JSONObjectTest.java @@ -520,7 +520,7 @@ public class JSONObjectTest { @Test public void stringToValueNumbersTest() { assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0") instanceof Double); - assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double); + assertTrue("-0.0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double); assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String); assertTrue( "0.2 should be a Double!", JSONObject.stringToValue( "0.2" ) instanceof Double ); From 9c47ba299d5f20aee73721bb4d4d0a6c908cedc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Mon, 18 Apr 2016 21:49:14 +0200 Subject: [PATCH 194/451] initial test for JSONPointer class --- src/test/org/json/junit/JSONPointerTest.java | 78 ++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/test/org/json/junit/JSONPointerTest.java diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/org/json/junit/JSONPointerTest.java new file mode 100644 index 0000000..221f035 --- /dev/null +++ b/src/test/org/json/junit/JSONPointerTest.java @@ -0,0 +1,78 @@ +package org.json.junit; + +import static org.junit.Assert.assertSame; + +import org.json.JSONObject; +import org.json.JSONPointer; +import org.json.JSONPointerException; +import org.junit.Test; + +public class JSONPointerTest { + + private static final JSONObject document = new JSONObject("{" + + "\"foo\": [\"bar\", \"baz\"], " + + "\"\": 0," + + "\"a/b\": 1," + + "\"c%d\": 2," + + "\"e^f\": 3," + + "\"g|h\": 4," + "\"i\\\\j\": 5," + + "\"k\\\"l\": 6," + + "\" \": 7," + + "\"m~n\": 8" + + "}"); + + private Object query(String pointer) { + return new JSONPointer(pointer).queryFrom(document); + } + + @Test + public void emptyPointer() { + assertSame(document, query("")); + } + + @Test(expected = NullPointerException.class) + public void nullPointer() { + new JSONPointer(null); + } + + @Test + public void objectPropertyQuery() { + assertSame(document.get("foo"), query("/foo")); + } + + @Test + public void arrayIndexQuery() { + assertSame(document.getJSONArray("foo").get(0), query("/foo/0")); + } + + @Test(expected = JSONPointerException.class) + public void stringPropOfArrayFailure() { + query("/foo/bar"); + } + + @Test + public void queryByEmptyKey() { + assertSame(document.get(""), query("/")); + } + + @Test + public void slashEscaping() { + assertSame(document.get("a/b"), query("/a~1b")); + } + + @Test + public void tildeEscaping() { + assertSame(document.get("m~n"), query("/m~0n")); + } + + @Test + public void uriFragmentNotation() { + assertSame(document.get("foo"), query("#/foo")); + } + + @Test(expected = IllegalArgumentException.class) + public void syntaxError() { + new JSONPointer("key"); + } + +} From e00191798e93d8fd28201d60affe2f5a46dbe276 Mon Sep 17 00:00:00 2001 From: Brian Russell Date: Sun, 24 Apr 2016 23:04:12 -0400 Subject: [PATCH 195/451] Added unit tests for escaped quotes. --- src/test/org/json/junit/CDLTest.java | 57 +++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/src/test/org/json/junit/CDLTest.java b/src/test/org/json/junit/CDLTest.java index 340977b..a40b014 100644 --- a/src/test/org/json/junit/CDLTest.java +++ b/src/test/org/json/junit/CDLTest.java @@ -68,7 +68,7 @@ public class CDLTest { equals(e.getMessage())); } } - + /** * Attempts to create a JSONArray from a string with unbalanced quotes * in value line. Expects a JSONException. @@ -104,7 +104,62 @@ public class CDLTest { } } + + /** + * Attempt to create a JSONArray with unbalanced quotes and a properly escaped doubled quote. + * Expects a JSONException. + */ + @Test + public void unbalancedEscapedQuote(){ + String badLine = "Col1, Col2\n\"Val1, \"\"Val2\"\""; + try { + CDL.toJSONArray(badLine); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Missing close quote '\"'. at 27 [character 16 line 3]". + equals(e.getMessage())); + + } + } + /** + * Assert that there is no error for a single escaped quote within a properly embedded quote. + */ + @Test + public void singleEscapedQuote(){ + String singleEscape = "Col1, Col2\nVal1, \"\"\"Val2\""; + JSONArray jsonArray = CDL.toJSONArray(singleEscape); + + String cdlStr = CDL.toString(jsonArray); + assertTrue(cdlStr.contains("Col1")); + assertTrue(cdlStr.contains("Col2")); + assertTrue(cdlStr.contains("Val1")); + assertTrue(cdlStr.contains("\"Val2")); + + } + + /** + * Attempt to create a JSONArray with an escape quote and no enclosing quotes. + * Expects a JSONException. + */ + @Test + public void badEscapedQuote(){ + String badLine = "Col1, Col2\nVal1, \"\"Val2"; + + try { + CDL.toJSONArray(badLine); + assertTrue("Expecting an exception", false); + } catch (JSONException e) { + System.out.println("Message" + e.getMessage()); + assertTrue("Expecting an exception message", + "Bad character 'V' (86). at 20 [character 9 line 3]". + equals(e.getMessage())); + + } + + } + /** * call toString with a null array */ From 6211384f87e8aee878b2a59c9f9d1e9101d9cfd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Tue, 26 Apr 2016 23:01:18 +0200 Subject: [PATCH 196/451] tests for url fragment notation handling, moving test document to separate file --- .gitignore | 3 ++ src/test/org/json/junit/JSONPointerTest.java | 54 +++++++++++++++---- .../org/json/junit/jsonpointer-testdoc.json | 16 ++++++ 3 files changed, 62 insertions(+), 11 deletions(-) create mode 100644 src/test/org/json/junit/jsonpointer-testdoc.json diff --git a/.gitignore b/.gitignore index 9e7b59c..2ede482 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ build .classpath .project .settings/ +.gitignore +.gradle +src/main diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/org/json/junit/JSONPointerTest.java index 221f035..463b66e 100644 --- a/src/test/org/json/junit/JSONPointerTest.java +++ b/src/test/org/json/junit/JSONPointerTest.java @@ -5,21 +5,30 @@ import static org.junit.Assert.assertSame; import org.json.JSONObject; import org.json.JSONPointer; import org.json.JSONPointerException; +import org.json.JSONTokener; import org.junit.Test; public class JSONPointerTest { - private static final JSONObject document = new JSONObject("{" - + "\"foo\": [\"bar\", \"baz\"], " - + "\"\": 0," - + "\"a/b\": 1," - + "\"c%d\": 2," - + "\"e^f\": 3," - + "\"g|h\": 4," + "\"i\\\\j\": 5," - + "\"k\\\"l\": 6," - + "\" \": 7," - + "\"m~n\": 8" - + "}"); + private static final JSONObject document; + + // = new JSONObject("{" + // + "\"foo\": [\"bar\", \"baz\"], " + // + "\"\": 0," + // + "\"a/b\": 1," + // + "\"c%d\": 2," + // + "\"e^f\": 3," + // + "\"g|h\": 4," + // + "\"i\\\\j\": 5," + // + "\"k\\\\\\\"l\": 6," + // + "\" \": 7," + // + "\"m~n\": 8" + // + "}"); + + static { + document = new JSONObject(new JSONTokener( + JSONPointerTest.class.getResourceAsStream("/org/json/junit/jsonpointer-testdoc.json"))); + } private Object query(String pointer) { return new JSONPointer(pointer).queryFrom(document); @@ -65,11 +74,34 @@ public class JSONPointerTest { assertSame(document.get("m~n"), query("/m~0n")); } + @Test + public void backslashEscaping() { + assertSame(document.get("i\\j"), query("/i\\\\j")); + } + + @Test + public void quotationEscaping() { + assertSame(document.get("k\"l"), query("/k\\\\\\\"l")); + } + + @Test + public void whitespaceKey() { + assertSame(document.get(" "), query("/ ")); + } + @Test public void uriFragmentNotation() { assertSame(document.get("foo"), query("#/foo")); } + @Test + public void uriFragmentPercentHandling() { + assertSame(document.get("c%d"), query("#/c%25d")); + assertSame(document.get("e^f"), query("#/e%5Ef")); + assertSame(document.get("g|h"), query("#/g%7Ch")); + assertSame(document.get("m~n"), query("#/m~0n")); + } + @Test(expected = IllegalArgumentException.class) public void syntaxError() { new JSONPointer("key"); diff --git a/src/test/org/json/junit/jsonpointer-testdoc.json b/src/test/org/json/junit/jsonpointer-testdoc.json new file mode 100644 index 0000000..386bdb7 --- /dev/null +++ b/src/test/org/json/junit/jsonpointer-testdoc.json @@ -0,0 +1,16 @@ +{ + "foo": + [ + "bar", + "baz" + ], + "": 0, + "a/b": 1, + "c%d": 2, + "e^f": 3, + "g|h": 4, + "i\\j": 5, + "k\"l": 6, + " ": 7, + "m~n": 8 +} \ No newline at end of file From 66f740eb451066840cef1faf8e051a15c5d16dd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Tue, 26 Apr 2016 23:02:26 +0200 Subject: [PATCH 197/451] rolling back unwanted gitignore change in previous commit --- .gitignore | 3 --- 1 file changed, 3 deletions(-) diff --git a/.gitignore b/.gitignore index 2ede482..9e7b59c 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,3 @@ build .classpath .project .settings/ -.gitignore -.gradle -src/main From f857dda5d84cf1baa809fa0d52c657266989a6e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Tue, 26 Apr 2016 23:03:01 +0200 Subject: [PATCH 198/451] removing some deprecated commented code --- src/test/org/json/junit/JSONPointerTest.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/org/json/junit/JSONPointerTest.java index 463b66e..103c5a8 100644 --- a/src/test/org/json/junit/JSONPointerTest.java +++ b/src/test/org/json/junit/JSONPointerTest.java @@ -12,19 +12,6 @@ public class JSONPointerTest { private static final JSONObject document; - // = new JSONObject("{" - // + "\"foo\": [\"bar\", \"baz\"], " - // + "\"\": 0," - // + "\"a/b\": 1," - // + "\"c%d\": 2," - // + "\"e^f\": 3," - // + "\"g|h\": 4," - // + "\"i\\\\j\": 5," - // + "\"k\\\\\\\"l\": 6," - // + "\" \": 7," - // + "\"m~n\": 8" - // + "}"); - static { document = new JSONObject(new JSONTokener( JSONPointerTest.class.getResourceAsStream("/org/json/junit/jsonpointer-testdoc.json"))); From e748c60eb10ba5605ca6c00f37df0d843f9592bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Tue, 26 Apr 2016 23:31:43 +0200 Subject: [PATCH 199/451] tests for improved failure handling --- src/test/org/json/junit/JSONPointerTest.java | 10 ++++++++++ src/test/org/json/junit/jsonpointer-testdoc.json | 5 ++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/org/json/junit/JSONPointerTest.java index 103c5a8..3818e82 100644 --- a/src/test/org/json/junit/JSONPointerTest.java +++ b/src/test/org/json/junit/JSONPointerTest.java @@ -94,4 +94,14 @@ public class JSONPointerTest { new JSONPointer("key"); } + @Test(expected = JSONPointerException.class) + public void arrayIndexFailure() { + query("/foo/2"); + } + + @Test(expected = JSONPointerException.class) + public void primitiveFailure() { + query("/obj/key/failure"); + } + } diff --git a/src/test/org/json/junit/jsonpointer-testdoc.json b/src/test/org/json/junit/jsonpointer-testdoc.json index 386bdb7..621ce93 100644 --- a/src/test/org/json/junit/jsonpointer-testdoc.json +++ b/src/test/org/json/junit/jsonpointer-testdoc.json @@ -12,5 +12,8 @@ "i\\j": 5, "k\"l": 6, " ": 7, - "m~n": 8 + "m~n": 8, + "obj" : { + "key" : "value" + } } \ No newline at end of file From 4a3565afb316f426f42ea6ed6ce29f1e253d2a62 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 1 May 2016 22:47:23 -0500 Subject: [PATCH 200/451] unit test integration --- build.gradle | 46 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/build.gradle b/build.gradle index 2544a69..943080f 100644 --- a/build.gradle +++ b/build.gradle @@ -1,26 +1,44 @@ apply plugin: 'java' apply plugin: 'eclipse' - -jar.baseName = 'JSON-java' +apply plugin: 'jacoco' sourceSets { - test { - java { - srcDir 'src/test' + // Uncomment main if you have merged JSON-Java and JSON-Java-unit-test code + main { + java { + srcDir 'src' + exclude 'test/' + } + } + test { + java { + srcDir 'src/test' + } } - } } repositories { - mavenCentral() + mavenCentral() } dependencies { - testCompile group: 'junit', name: 'junit', version: '4.+' - testCompile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.1.0' - testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' - // Use this line if you are testing a JSON-Java release. - // Otherwise add an external jar from your local repository in Eclipse - // (The gradle build won't work unless you add a main sourceSets entry and a jar.baseName entry - // testCompile group: 'org.json', name: 'json', version: '20151123' + testCompile group: 'junit', name: 'junit', version: '4.+' + testCompile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.1.0' + testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' + // Uncomment if you are testing against a JSON-Java release + // testCompile 'org.json:json:20160212' + // Uncomment if you have copied a local JSON-Java jar file into this project + // testCompile files('./JSON-Java.jar') } + +test { finalizedBy jacocoTestReport } +jacocoTestReport{ + additionalSourceDirs = files(sourceSets.main.allJava.srcDirs) + reports { + xml.enabled false + csv.enabled false + html.destination "${buildDir}/reports/jacoco/html" + } + executionData = files('build/jacoco/test.exec') +} + From 052ce94a34186ebd8dffb7b35cc888d515e18786 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sun, 1 May 2016 22:53:53 -0500 Subject: [PATCH 201/451] Update README.md --- README.md | 33 ++------------------------------- 1 file changed, 2 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index d908b52..0357b4a 100644 --- a/README.md +++ b/README.md @@ -24,40 +24,11 @@ Run individual tests or JunitTestSuite using EclEmma Coverage, or * JSON-java.jar
**To build from the command line using gradle:** +Until the unit tests are merged into the JSON-Java project, the code has to be wired by hand. After cloning JSON-Java-unit-test, create a directory structure under src and copy the JSON-Java files into: src/org/json. Then execute the unit tests and code coverage with: ```` -build.gradle -# In this example, both the JSON-java jar and the test code is created -# from the same build file, in the test code directory. 3rd party jars are -# obtained from the maven repository. -apply plugin: 'java' -jar.baseName = 'JSON-java' - -sourceSets { - main { - java { - srcDir '../JSON-java/src/org/json' - } - } - test { - java { - srcDir 'src/org/json/junit' - } - } -} - -repositories { - mavenCentral() -} - -dependencies { - testCompile group: 'junit', name: 'junit', version: '4.+' - testCompile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.1.0' - testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' -} +gradle clean build test jacocoTestReport ```` -To measure coverage: http://www.eclemma.org/ (just install the latest in Eclipse)
- Conventions
Test filenames should consist of the name of the module being tested, with the suffix "Test". For example, Cookie.java is tested by CookieTest.java. From 6edc0938033d736ab03c8e23ccaccda2c32bae7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Tue, 3 May 2016 23:20:17 +0200 Subject: [PATCH 202/451] adding unittests for JSPONPointer#toString(), toURIFragment() and its builder class --- src/test/org/json/junit/JSONPointerTest.java | 37 ++++++++++++++++++- .../org/json/junit/jsonpointer-testdoc.json | 7 +++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/org/json/junit/JSONPointerTest.java index 3818e82..4299d8f 100644 --- a/src/test/org/json/junit/JSONPointerTest.java +++ b/src/test/org/json/junit/JSONPointerTest.java @@ -1,5 +1,6 @@ package org.json.junit; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.json.JSONObject; @@ -28,7 +29,7 @@ public class JSONPointerTest { @Test(expected = NullPointerException.class) public void nullPointer() { - new JSONPointer(null); + new JSONPointer((String) null); } @Test @@ -103,5 +104,39 @@ public class JSONPointerTest { public void primitiveFailure() { query("/obj/key/failure"); } + + @Test + public void builderTest() { + JSONPointer pointer = JSONPointer.builder() + .append("obj") + .append("other~key").append("another/key") + .append(0) + .build(); + assertEquals("val", pointer.queryFrom(document)); + } + + @Test + public void toStringEscaping() { + JSONPointer pointer = JSONPointer.builder() + .append("obj") + .append("other~key").append("another/key") + .append("\"") + .append(0) + .build(); + assertEquals("/obj/other~0key/another~1key/\\\"/0", pointer.toString()); + } + + @Test + public void emptyPointerToString() { + assertEquals("", new JSONPointer("").toString()); + } + + @Test + public void toURIFragment() { + assertEquals("#/c%25d", new JSONPointer("/c%d").toURIFragment()); + assertEquals("#/e%5Ef", new JSONPointer("/e^f").toURIFragment()); + assertEquals("#/g%7Ch", new JSONPointer("/g|h").toURIFragment()); + assertEquals("#/m%7En", new JSONPointer("/m~n").toURIFragment()); + } } diff --git a/src/test/org/json/junit/jsonpointer-testdoc.json b/src/test/org/json/junit/jsonpointer-testdoc.json index 621ce93..d58fe82 100644 --- a/src/test/org/json/junit/jsonpointer-testdoc.json +++ b/src/test/org/json/junit/jsonpointer-testdoc.json @@ -14,6 +14,11 @@ " ": 7, "m~n": 8, "obj" : { - "key" : "value" + "key" : "value", + "other~key" : { + "another/key" : [ + "val" + ] + } } } \ No newline at end of file From 2eed4be5fca99a8f2ced50b4827f3f1f6ab798b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Tue, 3 May 2016 23:42:26 +0200 Subject: [PATCH 203/451] one more test for null-check in Builder#append(String) --- src/test/org/json/junit/JSONPointerTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/org/json/junit/JSONPointerTest.java index 4299d8f..f17ba6e 100644 --- a/src/test/org/json/junit/JSONPointerTest.java +++ b/src/test/org/json/junit/JSONPointerTest.java @@ -115,6 +115,11 @@ public class JSONPointerTest { assertEquals("val", pointer.queryFrom(document)); } + @Test(expected = NullPointerException.class) + public void nullToken() { + JSONPointer.builder().append(null); + } + @Test public void toStringEscaping() { JSONPointer pointer = JSONPointer.builder() From adb3118d31f84cd4d1b60828a95f64c0c9e282bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Thu, 5 May 2016 16:00:15 +0200 Subject: [PATCH 204/451] added test for checking if the JSONPointer is immutable --- src/test/org/json/junit/JSONPointerTest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/org/json/junit/JSONPointerTest.java index f17ba6e..820023b 100644 --- a/src/test/org/json/junit/JSONPointerTest.java +++ b/src/test/org/json/junit/JSONPointerTest.java @@ -2,6 +2,7 @@ package org.json.junit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; import org.json.JSONObject; import org.json.JSONPointer; @@ -143,5 +144,16 @@ public class JSONPointerTest { assertEquals("#/g%7Ch", new JSONPointer("/g|h").toURIFragment()); assertEquals("#/m%7En", new JSONPointer("/m~n").toURIFragment()); } + + @Test + public void tokenListIsCopiedInConstructor() { + JSONPointer.Builder b = JSONPointer.builder().append("key1"); + JSONPointer jp1 = b.build(); + b.append("key2"); + JSONPointer jp2 = b.build(); + if(jp1.toString().equals(jp2.toString())) { + fail("Oops, my pointers are sharing a backing array"); + } + } } From ccc7a7af29bb6385180c8647d0b332a804250198 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 7 May 2016 07:02:50 -0500 Subject: [PATCH 205/451] Update README.md --- README.md | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 0357b4a..1be9c65 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,10 @@ Unit tests to validate the JSON-Java GitHub project code
https://github.com/douglascrockford/JSON-java
-*These tests are a work in progress. Help from interested developers is welcome.*
-More coverage is needed, but more importantly, improvements to test quality is needed.
- -Eclipse is the recommended development environment.
+Gradle and Eclipse is the recommended build tool and IDE.
Run individual tests or JunitTestSuite using EclEmma Coverage, or execute the **TestRunner** application directly.
-**You will need the following libraries for testing:**
+**The following libraries are required:**
* asm-1.0.2.jar
* commons-io-2.1.jar
* commons-lang-2.6.jar
@@ -24,10 +21,31 @@ Run individual tests or JunitTestSuite using EclEmma Coverage, or * JSON-java.jar
**To build from the command line using gradle:** -Until the unit tests are merged into the JSON-Java project, the code has to be wired by hand. After cloning JSON-Java-unit-test, create a directory structure under src and copy the JSON-Java files into: src/org/json. Then execute the unit tests and code coverage with: +Until the unit tests are merged into the JSON-Java project, the code has to be wired by hand. +\# In an empty directory of your choice, clone JSON-Java-unit-test: +```` +git clone https://github.com/stleary/JSON-Java-unit-test.git . +```` +\# Create a directory structure for the JSON-Java code +```` +mkdir -p src\org\json +```` +\# clone JSON-Java +```` +git clone https://github.com/stleary/JSON-Java-unit-test.git src\org\json +```` +\# Build, then execute the unit tests and code coverage ```` gradle clean build test jacocoTestReport ```` +Unit test results will be in build\reports\tests\index.html
+Code coverage will be in build\reports\jacoco\html\index.html + +To create an Eclipse project, you will need the Eclipse Gradle plug-in, available from the Eclipse Marketplace. I am currently using Gradle IDE 3.6.4.201503050952-RELEASE
+Select File > Import > Gradle > Gradle project
+Browse to the directory where you cloned JSON-Java-unit-test
+Select Build model
+Select built project
Conventions
Test filenames should consist of the name of the module being tested, with the suffix "Test". From 691734f342ece27b686046547363e14828b6272d Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 7 May 2016 07:03:30 -0500 Subject: [PATCH 206/451] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1be9c65..388122f 100644 --- a/README.md +++ b/README.md @@ -21,8 +21,8 @@ Run individual tests or JunitTestSuite using EclEmma Coverage, or * JSON-java.jar
**To build from the command line using gradle:** -Until the unit tests are merged into the JSON-Java project, the code has to be wired by hand. -\# In an empty directory of your choice, clone JSON-Java-unit-test: +Until the unit tests are merged into the JSON-Java project, the code has to be wired by hand.
+\# In an empty directory of your choice, clone JSON-Java-unit-test:
```` git clone https://github.com/stleary/JSON-Java-unit-test.git . ```` From b843d67a921690dcf6fca86a4a23762ed11dd7a4 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 7 May 2016 07:03:50 -0500 Subject: [PATCH 207/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 388122f..8cd97b8 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Run individual tests or JunitTestSuite using EclEmma Coverage, or * slf-simple-1.7.12.jar
* JSON-java.jar
-**To build from the command line using gradle:** +**To build from the command line using gradle:**
Until the unit tests are merged into the JSON-Java project, the code has to be wired by hand.
\# In an empty directory of your choice, clone JSON-Java-unit-test:
```` From a9ff159c7804746800982445237a590a6479cbbd Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 13 May 2016 15:17:22 -0500 Subject: [PATCH 208/451] Update README.md --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8cd97b8..d08751d 100644 --- a/README.md +++ b/README.md @@ -28,11 +28,12 @@ git clone https://github.com/stleary/JSON-Java-unit-test.git . ```` \# Create a directory structure for the JSON-Java code ```` -mkdir -p src\org\json +# Windows version +md /s src\org\json ```` \# clone JSON-Java ```` -git clone https://github.com/stleary/JSON-Java-unit-test.git src\org\json +git clone https://github.com/stleary/JSON-Java.git src\org\json ```` \# Build, then execute the unit tests and code coverage ```` From 0112d82755f07838de44f31725ba6a697d4355b6 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 13 May 2016 23:13:06 -0500 Subject: [PATCH 209/451] add JSONPointerTest to test suite, fix resource for gradle build --- build.gradle | 3 +++ src/test/org/json/junit/JSONPointerTest.java | 7 ++----- src/test/org/json/junit/JunitTestSuite.java | 5 +++-- .../{org/json/junit => resources}/jsonpointer-testdoc.json | 0 4 files changed, 8 insertions(+), 7 deletions(-) rename src/test/{org/json/junit => resources}/jsonpointer-testdoc.json (100%) diff --git a/build.gradle b/build.gradle index 943080f..8dbd0fe 100644 --- a/build.gradle +++ b/build.gradle @@ -14,6 +14,9 @@ sourceSets { java { srcDir 'src/test' } + resources { + srcDir 'resources' + } } } diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/org/json/junit/JSONPointerTest.java index 820023b..c100617 100644 --- a/src/test/org/json/junit/JSONPointerTest.java +++ b/src/test/org/json/junit/JSONPointerTest.java @@ -4,10 +4,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; -import org.json.JSONObject; -import org.json.JSONPointer; -import org.json.JSONPointerException; -import org.json.JSONTokener; +import org.json.*; import org.junit.Test; public class JSONPointerTest { @@ -16,7 +13,7 @@ public class JSONPointerTest { static { document = new JSONObject(new JSONTokener( - JSONPointerTest.class.getResourceAsStream("/org/json/junit/jsonpointer-testdoc.json"))); + JSONPointerTest.class.getClassLoader().getResourceAsStream("jsonpointer-testdoc.json"))); } private Object query(String pointer) { diff --git a/src/test/org/json/junit/JunitTestSuite.java b/src/test/org/json/junit/JunitTestSuite.java index ceff6f1..3863931 100644 --- a/src/test/org/json/junit/JunitTestSuite.java +++ b/src/test/org/json/junit/JunitTestSuite.java @@ -14,7 +14,8 @@ import org.junit.runners.Suite; JSONStringerTest.class, JSONObjectTest.class, JSONArrayTest.class, - EnumTest.class + EnumTest.class, + JSONPointerTest.class }) public class JunitTestSuite { -} \ No newline at end of file +} diff --git a/src/test/org/json/junit/jsonpointer-testdoc.json b/src/test/resources/jsonpointer-testdoc.json similarity index 100% rename from src/test/org/json/junit/jsonpointer-testdoc.json rename to src/test/resources/jsonpointer-testdoc.json From 06ae87c456ead203ba78746a8b6c96f2d99c7078 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 13 May 2016 23:22:54 -0500 Subject: [PATCH 210/451] exclude resources from test --- build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/build.gradle b/build.gradle index 8dbd0fe..ad186a1 100644 --- a/build.gradle +++ b/build.gradle @@ -13,6 +13,7 @@ sourceSets { test { java { srcDir 'src/test' + exclude 'resources/' } resources { srcDir 'resources' From 45cbc66f5bd92bfad97d36de6896d6acedb0a3dc Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 14 May 2016 09:26:03 -0500 Subject: [PATCH 211/451] add coverage for JSONObject, JSONArray queryFrom() --- src/test/org/json/junit/JSONPointerTest.java | 62 +++++++++++++++++++- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/org/json/junit/JSONPointerTest.java index c100617..95fa73b 100644 --- a/src/test/org/json/junit/JSONPointerTest.java +++ b/src/test/org/json/junit/JSONPointerTest.java @@ -1,8 +1,6 @@ package org.json.junit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; import org.json.*; import org.junit.Test; @@ -153,4 +151,62 @@ public class JSONPointerTest { } } + /** + * Coverage for JSONObject queryFrom() + */ + @Test + public void queryFromJSONObject() { + String str = "{"+ + "\"stringKey\":\"hello world!\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\": {"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + Object obj = jsonObject.query("/stringKey"); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonObject.query("/arrayKey/1"); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonObject.query("/objectKey/b"); + assertTrue("Expected bVal", "bVal".equals(obj)); + try { + obj = jsonObject.query("/a/b/c"); + assertTrue("Expected JSONPointerException", false); + } catch (JSONPointerException e) { + assertTrue("Expected bad key/value exception", + "value [null] is not an array or object therefore its key b cannot be resolved". + equals(e.getMessage())); + } + } + + /** + * Coverage for JSONArray queryFrom() + */ + @Test + public void queryFromJSONArray() { + String str = "["+ + "\"hello world!\","+ + "[0,1,2],"+ + "{"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "]"; + JSONArray jsonArray = new JSONArray(str); + Object obj = jsonArray.query("/0"); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonArray.query("/1/1"); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonArray.query("/2/b"); + assertTrue("Expected bVal", "bVal".equals(obj)); + try { + obj = jsonArray.query("/a/b/c"); + assertTrue("Expected JSONPointerException", false); + } catch (JSONPointerException e) { + assertTrue("Expected bad index exception", + "a is not an array index".equals(e.getMessage())); + } + } } From 15f48a05004b171fc556f613ebd3dd86688018fb Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 14 May 2016 11:59:24 -0500 Subject: [PATCH 212/451] convert tests to use JSONPointer where practical --- src/test/org/json/junit/JSONObjectTest.java | 158 ++++++++++---------- 1 file changed, 79 insertions(+), 79 deletions(-) diff --git a/src/test/org/json/junit/JSONObjectTest.java b/src/test/org/json/junit/JSONObjectTest.java index 869fe46..f015579 100644 --- a/src/test/org/json/junit/JSONObjectTest.java +++ b/src/test/org/json/junit/JSONObjectTest.java @@ -72,10 +72,10 @@ public class JSONObjectTest { JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString()); assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"nullKey\":null", null == JsonPath.read(doc, "$.nullKey")); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey"))); + assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObjectByName.query("/doubleKey"))); } /** @@ -109,13 +109,13 @@ public class JSONObjectTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); + assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); } - + /** * Verifies that the constructor has backwards compatability with RAW types pre-java5. */ @@ -249,8 +249,8 @@ public class JSONObjectTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(JsonPath.read(doc, "$.key2"))); assertTrue("expected 0 key1 items", ((Map)(JsonPath.read(doc, "$.key1"))).size() == 0); + assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2"))); } /** @@ -272,12 +272,12 @@ public class JSONObjectTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); - assertTrue("expected \"intKey\":42", Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(JsonPath.read(doc, "$.doubleKey"))); + assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); + assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); } /** @@ -306,13 +306,13 @@ public class JSONObjectTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); - assertTrue("expected hello world!","hello world!".equals(JsonPath.read(doc, "$.stringKey"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.escapeStringKey"))); - assertTrue("expected 42", Integer.valueOf("42").equals(JsonPath.read(doc, "$.intKey"))); - assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(JsonPath.read(doc, "$.doubleKey"))); assertTrue("expected 0 items in stringReaderKey", ((Map) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); + assertTrue("expected hello world!","hello world!".equals(jsonObject.query("/stringKey"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); + assertTrue("expected 42", Integer.valueOf("42").equals(jsonObject.query("/intKey"))); + assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(jsonObject.query("/doubleKey"))); // sorry, mockito artifact assertTrue("expected 2 callbacks items", ((List)(JsonPath.read(doc, "$.callbacks"))).size() == 2); assertTrue("expected 0 handler items", ((Map)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0); @@ -335,8 +335,8 @@ public class JSONObjectTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected \"publicString\":\"abc\"", "abc".equals(JsonPath.read(doc, "$.publicString"))); - assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.publicInt"))); + assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString"))); + assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt"))); } /** @@ -353,11 +353,11 @@ public class JSONObjectTest { Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected 2 greetings items", ((Map)(JsonPath.read(doc, "$.greetings"))).size() == 2); - assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(JsonPath.read(doc, "$.greetings.hello"))); - assertTrue("expected \"world\":\"World!\"", "World!".equals(JsonPath.read(doc, "$.greetings.world"))); + assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello"))); + assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world"))); assertTrue("expected 2 farewells items", ((Map)(JsonPath.read(doc, "$.farewells"))).size() == 2); - assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(JsonPath.read(doc, "$.farewells.later"))); - assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(JsonPath.read(doc, "$.farewells.gator"))); + assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later"))); + assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator"))); } /** @@ -383,12 +383,12 @@ public class JSONObjectTest { Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); - assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.myArray[3]"))); - assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); - assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(JsonPath.read(doc, "$.myArray[5]"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1"))); + assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); + assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); + assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); } /** @@ -413,12 +413,12 @@ public class JSONObjectTest { Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.myArray[0]"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.myArray[1]"))); - assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.myArray[2]"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc,"$.myArray[3]"))); - assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.myArray[4]"))); - assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(JsonPath.read(doc, "$.myArray[5]"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1/"))); + assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); + assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); + assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); } /** @@ -1146,11 +1146,11 @@ public class JSONObjectTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.keyInt"))); - assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(JsonPath.read(doc, "$.keyLong"))); - assertTrue("expected 3.1", Double.valueOf(3.1).equals(JsonPath.read(doc, "$.keyDouble"))); - assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(JsonPath.read(doc, "$.keyBigInt"))); - assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(JsonPath.read(doc, "$.keyBigDec"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/keyInt"))); + assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(jsonObject.query("/keyLong"))); + assertTrue("expected 3.1", Double.valueOf(3.1).equals(jsonObject.query("/keyDouble"))); + assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(jsonObject.query("/keyBigInt"))); + assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(jsonObject.query("/keyBigDec"))); /** * Should work the same way on any platform! @see https://docs.oracle @@ -1175,7 +1175,7 @@ public class JSONObjectTest { * missing bits would not fit into the 32 bit float, i.e. the * information needed simply is not there! */ - assertTrue("expected 3.0999999046325684", Double.valueOf(3.0999999046325684).equals(JsonPath.read(doc, "$.keyFloat"))); + assertTrue("expected 3.0999999046325684", Double.valueOf(3.0999999046325684).equals(jsonObject.query("/keyFloat"))); /** * float f = 3.1f; double df = (double) f; double d = 3.1d; @@ -1285,17 +1285,17 @@ public class JSONObjectTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); - assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); - assertTrue("expected myVal1", "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); - assertTrue("expected myVal2", "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); - assertTrue("expected myVal3", "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); - assertTrue("expected myVal4", "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); + assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); + assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); + assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); + assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); jsonObject.remove("trueKey"); JSONObject expectedJsonObject = new JSONObject(expectedStr); @@ -1348,17 +1348,17 @@ public class JSONObjectTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseKey"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); - assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$.arrayKey[0]"))); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.arrayKey[1]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.arrayKey[2]"))); + assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); - assertTrue("expected myVal1", "myVal1".equals(JsonPath.read(doc, "$.objectKey.myKey1"))); - assertTrue("expected myVal2", "myVal2".equals(JsonPath.read(doc, "$.objectKey.myKey2"))); - assertTrue("expected myVal3", "myVal3".equals(JsonPath.read(doc, "$.objectKey.myKey3"))); - assertTrue("expected myVal4", "myVal4".equals(JsonPath.read(doc, "$.objectKey.myKey4"))); + assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); + assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); + assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); + assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); } /** @@ -1379,7 +1379,7 @@ public class JSONObjectTest { Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 1 key item", ((Map)(JsonPath.read(doc, "$.key"))).size() == 1); - assertTrue("expected def", "def".equals(JsonPath.read(doc, "$.key.abc"))); + assertTrue("expected def", "def".equals(jsonObject.query("/key/abc"))); } /** @@ -1401,7 +1401,7 @@ public class JSONObjectTest { Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 1 key item", ((List)(JsonPath.read(doc, "$.key"))).size() == 1); - assertTrue("expected abc", "abc".equals(JsonPath.read(doc, "$.key[0]"))); + assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0"))); } /** @@ -1517,9 +1517,9 @@ public class JSONObjectTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); // wrap Array returns JSONArray Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; @@ -1528,16 +1528,16 @@ public class JSONObjectTest { // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString()); assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); // wrap map returns JSONObject Map map = new HashMap(); @@ -1549,9 +1549,9 @@ public class JSONObjectTest { // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString()); assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected val1", "val1".equals(JsonPath.read(doc, "$.key1"))); - assertTrue("expected val2", "val2".equals(JsonPath.read(doc, "$.key2"))); - assertTrue("expected val3", "val3".equals(JsonPath.read(doc, "$.key3"))); + assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1"))); + assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2"))); + assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3"))); } /** From 8ed0362683acd784fbd0a9d75beb86e56ed300d9 Mon Sep 17 00:00:00 2001 From: stleary Date: Sat, 14 May 2016 13:38:46 -0500 Subject: [PATCH 213/451] convert remaining JsonPath expressions to JSONPointer --- src/test/org/json/junit/CookieListTest.java | 40 +++---- src/test/org/json/junit/EnumTest.java | 64 +++++------ src/test/org/json/junit/JSONArrayTest.java | 104 +++++++++--------- src/test/org/json/junit/JSONStringerTest.java | 68 ++++++------ 4 files changed, 138 insertions(+), 138 deletions(-) diff --git a/src/test/org/json/junit/CookieListTest.java b/src/test/org/json/junit/CookieListTest.java index 815c767..7a710db 100644 --- a/src/test/org/json/junit/CookieListTest.java +++ b/src/test/org/json/junit/CookieListTest.java @@ -78,7 +78,7 @@ public class CookieListTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("Expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID"))); + assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(jsonObject.query("/SID"))); } /** @@ -91,7 +91,7 @@ public class CookieListTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("Expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(JsonPath.read(doc, "$.SID"))); + assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(jsonObject.query("/SID"))); } /** @@ -111,12 +111,12 @@ public class CookieListTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected myCookieValue1", "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); - assertTrue("expected myCookieValue2", "myCookieValue2".equals(JsonPath.read(doc, "$.name2"))); - assertTrue("expected myCookieValue3", "myCookieValue3".equals(JsonPath.read(doc, "$.name3"))); - assertTrue("expected myCookieValue4", "myCookieValue4".equals(JsonPath.read(doc, "$.name4"))); - assertTrue("expected myCookieValue5", "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); - assertTrue("expected myCookieValue6", "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); + assertTrue("expected myCookieValue1", "myCookieValue1".equals(jsonObject.query("/name1"))); + assertTrue("expected myCookieValue2", "myCookieValue2".equals(jsonObject.query("/name2"))); + assertTrue("expected myCookieValue3", "myCookieValue3".equals(jsonObject.query("/name3"))); + assertTrue("expected myCookieValue4", "myCookieValue4".equals(jsonObject.query("/name4"))); + assertTrue("expected myCookieValue5", "myCookieValue5".equals(jsonObject.query("/name5"))); + assertTrue("expected myCookieValue6", "myCookieValue6".equals(jsonObject.query("/name6"))); } /** @@ -151,12 +151,12 @@ public class CookieListTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected myCookieValue1", "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); - assertTrue("expected myCookieValue2", "myCookieValue2".equals(JsonPath.read(doc, "$.name2"))); - assertTrue("expected myCookieValue3", "myCookieValue3".equals(JsonPath.read(doc, "$.name3"))); - assertTrue("expected myCookieValue4", "myCookieValue4".equals(JsonPath.read(doc, "$.name4"))); - assertTrue("expected myCookieValue5", "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); - assertTrue("expected myCookieValue6", "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); + assertTrue("expected myCookieValue1", "myCookieValue1".equals(jsonObject.query("/name1"))); + assertTrue("expected myCookieValue2", "myCookieValue2".equals(jsonObject.query("/name2"))); + assertTrue("expected myCookieValue3", "myCookieValue3".equals(jsonObject.query("/name3"))); + assertTrue("expected myCookieValue4", "myCookieValue4".equals(jsonObject.query("/name4"))); + assertTrue("expected myCookieValue5", "myCookieValue5".equals(jsonObject.query("/name5"))); + assertTrue("expected myCookieValue6", "myCookieValue6".equals(jsonObject.query("/name6"))); } /** @@ -176,11 +176,11 @@ public class CookieListTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected myCookieValue1", "myCookieValue1".equals(JsonPath.read(doc, "$.name1"))); - assertTrue("expected my Cookie Value 2", "my Cookie Value 2".equals(JsonPath.read(doc, "$.name2"))); - assertTrue("expected my+Cookie&Value;3=", "my+Cookie&Value;3=".equals(JsonPath.read(doc, "$.name3"))); - assertTrue("expected my%CookieValue4", "my%CookieValue4".equals(JsonPath.read(doc, "$.name4"))); - assertTrue("expected my%CookieValue5", "myCookieValue5".equals(JsonPath.read(doc, "$.name5"))); - assertTrue("expected myCookieValue6", "myCookieValue6".equals(JsonPath.read(doc, "$.name6"))); + assertTrue("expected myCookieValue1", "myCookieValue1".equals(jsonObject.query("/name1"))); + assertTrue("expected my Cookie Value 2", "my Cookie Value 2".equals(jsonObject.query("/name2"))); + assertTrue("expected my+Cookie&Value;3=", "my+Cookie&Value;3=".equals(jsonObject.query("/name3"))); + assertTrue("expected my%CookieValue4", "my%CookieValue4".equals(jsonObject.query("/name4"))); + assertTrue("expected my%CookieValue5", "myCookieValue5".equals(jsonObject.query("/name5"))); + assertTrue("expected myCookieValue6", "myCookieValue6".equals(jsonObject.query("/name6"))); } } diff --git a/src/test/org/json/junit/EnumTest.java b/src/test/org/json/junit/EnumTest.java index a591dba..ff4b294 100644 --- a/src/test/org/json/junit/EnumTest.java +++ b/src/test/org/json/junit/EnumTest.java @@ -36,8 +36,8 @@ public class EnumTest { Object doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonObject.toString()); assertTrue("expecting 2 items in top level object", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expecting val 2", "val 2".equals(JsonPath.read(doc, "$.value"))); - assertTrue("expecting 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal"))); + assertTrue("expecting val 2", "val 2".equals(jsonObject.query("/value"))); + assertTrue("expecting 2", Integer.valueOf(2).equals(jsonObject.query("/intVal"))); /** * class which contains enum instances. Each enum should be stored @@ -53,8 +53,8 @@ public class EnumTest { assertTrue("expecting 2 items in top level object", ((Map)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expecting 2 items in myEnumField object", ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); assertTrue("expecting 0 items in myEnum object", ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); - assertTrue("expecting 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal"))); - assertTrue("expecting val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value"))); + assertTrue("expecting 3", Integer.valueOf(3).equals(jsonObject.query("/myEnumField/intVal"))); + assertTrue("expecting val 3", "val 3".equals(jsonObject.query("/myEnumField/value"))); } /** @@ -74,9 +74,9 @@ public class EnumTest { // validate JSON object Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1"))); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2"))); - assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3"))); + assertTrue("expected VAL1", MyEnum.VAL1.equals(jsonObject.query("/VAL1"))); + assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonObject.query("/VAL2"))); + assertTrue("expected VAL3", MyEnum.VAL3.equals(jsonObject.query("/VAL3"))); MyEnumField myEnumField = MyEnumField.VAL3; names = JSONObject.getNames(myEnumField); @@ -84,9 +84,9 @@ public class EnumTest { jsonObject = new JSONObject(myEnumField, names); doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1"))); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2"))); - assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3"))); + assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/VAL1"))); + assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/VAL2"))); + assertTrue("expected VAL3", myEnumField.VAL3.equals(jsonObject.query("/VAL3"))); } @@ -105,8 +105,8 @@ public class EnumTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level objects", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnum"))); - assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.myEnumField"))); + assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonObject.query("/myEnum"))); + assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/myEnumField"))); JSONArray jsonArray = new JSONArray(); jsonArray.put(myEnum); @@ -115,8 +115,8 @@ public class EnumTest { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 2 top level objects", ((List)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonArray.query("/0"))); + assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonArray.query("/1"))); /** * Leaving these tests because they exercise get, opt, and remove @@ -174,8 +174,8 @@ public class EnumTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected val 2", "val 2".equals(JsonPath.read(doc, "$.value"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal"))); + assertTrue("expected val 2", "val 2".equals(jsonObject.query("/value"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/intVal"))); MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); @@ -187,8 +187,8 @@ public class EnumTest { assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected 2 myEnumField items", ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); assertTrue("expected 0 myEnum items", ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal"))); - assertTrue("expected val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/myEnumField/intVal"))); + assertTrue("expected val 3", "val 3".equals(jsonObject.query("/myEnumField/value"))); String [] names = JSONObject.getNames(myEnum); jsonObject = new JSONObject(myEnum, names); @@ -196,9 +196,9 @@ public class EnumTest { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1"))); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2"))); - assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3"))); + assertTrue("expected VAL1", MyEnum.VAL1.equals(jsonObject.query("/VAL1"))); + assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonObject.query("/VAL2"))); + assertTrue("expected VAL3", MyEnum.VAL3.equals(jsonObject.query("/VAL3"))); names = JSONObject.getNames(myEnumField); jsonObject = new JSONObject(myEnumField, names); @@ -206,9 +206,9 @@ public class EnumTest { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected VAL1", "VAL1".equals(JsonPath.read(doc, "$.VAL1"))); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.VAL2"))); - assertTrue("expected VAL3", "VAL3".equals(JsonPath.read(doc, "$.VAL3"))); + assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/VAL1"))); + assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/VAL2"))); + assertTrue("expected VAL3", MyEnumField.VAL3.equals(jsonObject.query("/VAL3"))); expectedStr = "{\"myEnum\":\"VAL2\", \"myEnumField\":\"VAL2\"}"; jsonObject = new JSONObject(); @@ -218,8 +218,8 @@ public class EnumTest { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnum"))); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$.myEnumField"))); + assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonObject.query("/myEnum"))); + assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/myEnumField"))); JSONArray jsonArray = new JSONArray(); jsonArray.put(myEnum); @@ -228,8 +228,8 @@ public class EnumTest { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 2 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected VAL2", "VAL2".equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonArray.query("/0"))); + assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonArray.query("/1"))); } /** @@ -248,8 +248,8 @@ public class EnumTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected val 2", "val 2".equals(JsonPath.read(doc, "$.value"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.intVal"))); + assertTrue("expected val 2", "val 2".equals(jsonObject.query("/value"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/intVal"))); MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); @@ -261,8 +261,8 @@ public class EnumTest { assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); assertTrue("expected 2 myEnumField items", ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); assertTrue("expected 0 myEnum items", ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.myEnumField.intVal"))); - assertTrue("expected val 3", "val 3".equals(JsonPath.read(doc, "$.myEnumField.value"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/myEnumField/intVal"))); + assertTrue("expected val 3", "val 3".equals(jsonObject.query("/myEnumField/value"))); } diff --git a/src/test/org/json/junit/JSONArrayTest.java b/src/test/org/json/junit/JSONArrayTest.java index 455d680..4bc95ef 100644 --- a/src/test/org/json/junit/JSONArrayTest.java +++ b/src/test/org/json/junit/JSONArrayTest.java @@ -316,24 +316,24 @@ public class JSONArrayTest { */ Object doc = Configuration.defaultConfiguration().jsonProvider().parse("["+joinStr+"]"); assertTrue("expected 13 items in top level object", ((List)(JsonPath.read(doc, "$"))).size() == 13); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected \"true\"", "true".equals(JsonPath.read(doc, "$[2]"))); - assertTrue("expected \"false\"", "false".equals(JsonPath.read(doc, "$[3]"))); - assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[4]"))); - assertTrue("expected 0.002345", Double.valueOf(0.002345).equals(JsonPath.read(doc, "$[5]"))); - assertTrue("expected \"23.45\"", "23.45".equals(JsonPath.read(doc, "$[6]"))); - assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$[7]"))); - assertTrue("expected \"43\"", "43".equals(JsonPath.read(doc, "$[8]"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonArray.query("/0"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonArray.query("/1"))); + assertTrue("expected \"true\"", "true".equals(jsonArray.query("/2"))); + assertTrue("expected \"false\"", "false".equals(jsonArray.query("/3"))); + assertTrue("expected hello", "hello".equals(jsonArray.query("/4"))); + assertTrue("expected 0.002345", Double.valueOf(0.002345).equals(jsonArray.query("/5"))); + assertTrue("expected \"23.45\"", "23.45".equals(jsonArray.query("/6"))); + assertTrue("expected 42", Integer.valueOf(42).equals(jsonArray.query("/7"))); + assertTrue("expected \"43\"", "43".equals(jsonArray.query("/8"))); assertTrue("expected 1 item in [9]", ((List)(JsonPath.read(doc, "$[9]"))).size() == 1); - assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[9][0]"))); + assertTrue("expected world", "world".equals(jsonArray.query("/9/0"))); assertTrue("expected 4 items in [10]", ((Map)(JsonPath.read(doc, "$[10]"))).size() == 4); - assertTrue("expected value1", "value1".equals(JsonPath.read(doc, "$[10].key1"))); - assertTrue("expected value2", "value2".equals(JsonPath.read(doc, "$[10].key2"))); - assertTrue("expected value3", "value3".equals(JsonPath.read(doc, "$[10].key3"))); - assertTrue("expected value4", "value4".equals(JsonPath.read(doc, "$[10].key4"))); - assertTrue("expected 0", Integer.valueOf(0).equals(JsonPath.read(doc, "$[11]"))); - assertTrue("expected \"-1\"", "-1".equals(JsonPath.read(doc, "$[12]"))); + assertTrue("expected value1", "value1".equals(jsonArray.query("/10/key1"))); + assertTrue("expected value2", "value2".equals(jsonArray.query("/10/key2"))); + assertTrue("expected value3", "value3".equals(jsonArray.query("/10/key3"))); + assertTrue("expected value4", "value4".equals(jsonArray.query("/10/key4"))); + assertTrue("expected 0", Integer.valueOf(0).equals(jsonArray.query("/11"))); + assertTrue("expected \"-1\"", "-1".equals(jsonArray.query("/12"))); } /** @@ -461,24 +461,24 @@ public class JSONArrayTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 10 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 10); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonArray.query("/0"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonArray.query("/1"))); assertTrue("expected 2 items in [2]", ((List)(JsonPath.read(doc, "$[2]"))).size() == 2); - assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[2][0]"))); - assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[2][1]"))); - assertTrue("expected 2.5", Double.valueOf(2.5).equals(JsonPath.read(doc, "$[3]"))); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[4]"))); - assertTrue("expected 45", Integer.valueOf(45).equals(JsonPath.read(doc, "$[5]"))); - assertTrue("expected objectPut", "objectPut".equals(JsonPath.read(doc, "$[6]"))); + assertTrue("expected hello", "hello".equals(jsonArray.query("/2/0"))); + assertTrue("expected world", "world".equals(jsonArray.query("/2/1"))); + assertTrue("expected 2.5", Double.valueOf(2.5).equals(jsonArray.query("/3"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/4"))); + assertTrue("expected 45", Long.valueOf(45).equals(jsonArray.query("/5"))); + assertTrue("expected objectPut", "objectPut".equals(jsonArray.query("/6"))); assertTrue("expected 3 items in [7]", ((Map)(JsonPath.read(doc, "$[7]"))).size() == 3); - assertTrue("expected val10", "val10".equals(JsonPath.read(doc, "$[7].key10"))); - assertTrue("expected val20", "val20".equals(JsonPath.read(doc, "$[7].key20"))); - assertTrue("expected val30", "val30".equals(JsonPath.read(doc, "$[7].key30"))); + assertTrue("expected val10", "val10".equals(jsonArray.query("/7/key10"))); + assertTrue("expected val20", "val20".equals(jsonArray.query("/7/key20"))); + assertTrue("expected val30", "val30".equals(jsonArray.query("/7/key30"))); assertTrue("expected 1 item in [8]", ((Map)(JsonPath.read(doc, "$[8]"))).size() == 1); - assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$[8].k1"))); + assertTrue("expected v1", "v1".equals(jsonArray.query("/8/k1"))); assertTrue("expected 2 items in [9]", ((List)(JsonPath.read(doc, "$[9]"))).size() == 2); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[9][0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[9][1]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/9/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/9/1"))); } /** @@ -538,25 +538,25 @@ public class JSONArrayTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 11 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 11); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonArray.query("/0"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonArray.query("/1"))); assertTrue("expected 2 items in [2]", ((List)(JsonPath.read(doc, "$[2]"))).size() == 2); - assertTrue("expected hello", "hello".equals(JsonPath.read(doc, "$[2][0]"))); - assertTrue("expected world", "world".equals(JsonPath.read(doc, "$[2][1]"))); - assertTrue("expected 2.5", Double.valueOf(2.5).equals(JsonPath.read(doc, "$[3]"))); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[4]"))); - assertTrue("expected 45", Integer.valueOf(45).equals(JsonPath.read(doc, "$[5]"))); - assertTrue("expected objectPut", "objectPut".equals(JsonPath.read(doc, "$[6]"))); - assertTrue("expected null", null == JsonPath.read(doc, "$[7]")); + assertTrue("expected hello", "hello".equals(jsonArray.query("/2/0"))); + assertTrue("expected world", "world".equals(jsonArray.query("/2/1"))); + assertTrue("expected 2.5", Double.valueOf(2.5).equals(jsonArray.query("/3"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/4"))); + assertTrue("expected 45", Long.valueOf(45).equals(jsonArray.query("/5"))); + assertTrue("expected objectPut", "objectPut".equals(jsonArray.query("/6"))); + assertTrue("expected null", JSONObject.NULL.equals(jsonArray.query("/7"))); assertTrue("expected 3 items in [8]", ((Map)(JsonPath.read(doc, "$[8]"))).size() == 3); - assertTrue("expected val10", "val10".equals(JsonPath.read(doc, "$[8].key10"))); - assertTrue("expected val20", "val20".equals(JsonPath.read(doc, "$[8].key20"))); - assertTrue("expected val30", "val30".equals(JsonPath.read(doc, "$[8].key30"))); + assertTrue("expected val10", "val10".equals(jsonArray.query("/8/key10"))); + assertTrue("expected val20", "val20".equals(jsonArray.query("/8/key20"))); + assertTrue("expected val30", "val30".equals(jsonArray.query("/8/key30"))); assertTrue("expected 2 items in [9]", ((List)(JsonPath.read(doc, "$[9]"))).size() == 2); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[9][0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[9][1]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/9/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/9/1"))); assertTrue("expected 1 item in [10]", ((Map)(JsonPath.read(doc, "$[10]"))).size() == 1); - assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$[10].k1"))); + assertTrue("expected v1", "v1".equals(jsonArray.query("/10/k1"))); } /** @@ -637,13 +637,13 @@ public class JSONArrayTest { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 7 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 7); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$[2]"))); - assertTrue("expected 4", Integer.valueOf(4).equals(JsonPath.read(doc, "$[3]"))); - assertTrue("expected 5", Integer.valueOf(5).equals(JsonPath.read(doc, "$[4]"))); - assertTrue("expected 6", Integer.valueOf(6).equals(JsonPath.read(doc, "$[5]"))); - assertTrue("expected 7", Integer.valueOf(7).equals(JsonPath.read(doc, "$[6]"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); + assertTrue("expected 4", Integer.valueOf(4).equals(jsonArray.query("/3"))); + assertTrue("expected 5", Integer.valueOf(5).equals(jsonArray.query("/4"))); + assertTrue("expected 6", Integer.valueOf(6).equals(jsonArray.query("/5"))); + assertTrue("expected 7", Integer.valueOf(7).equals(jsonArray.query("/6"))); } /** diff --git a/src/test/org/json/junit/JSONStringerTest.java b/src/test/org/json/junit/JSONStringerTest.java index 631d792..19b46de 100644 --- a/src/test/org/json/junit/JSONStringerTest.java +++ b/src/test/org/json/junit/JSONStringerTest.java @@ -194,13 +194,13 @@ public class JSONStringerTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 7 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 7); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueValue"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseValue"))); - assertTrue("expected null", null == JsonPath.read(doc, "$.nullValue")); - assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.stringValue"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, "$.complexStringValue"))); - assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.intValue"))); - assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(JsonPath.read(doc, "$.doubleValue"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueValue"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseValue"))); + assertTrue("expected null", JSONObject.NULL.equals(jsonObject.query("/nullValue"))); + assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/stringValue"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/complexStringValue"))); + assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/intValue"))); + assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(jsonObject.query("/doubleValue"))); } /** @@ -224,12 +224,12 @@ public class JSONStringerTest { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); assertTrue("expected 6 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$[0]"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$[1]"))); - assertTrue("expected null", null == JsonPath.read(doc, "$[2]")); - assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$[3]"))); - assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$[4]"))); - assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(JsonPath.read(doc, "$[5]"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonArray.query("/0"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonArray.query("/1"))); + assertTrue("expected null", JSONObject.NULL.equals(jsonArray.query("/2"))); + assertTrue("expected hello world!", "hello world!".equals(jsonArray.query("/3"))); + assertTrue("expected 42", Integer.valueOf(42).equals(jsonArray.query("/4"))); + assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(jsonArray.query("/5"))); } /** @@ -281,27 +281,27 @@ public class JSONStringerTest { assertTrue("expected 5 array1 items", ((List)(JsonPath.read(doc, "$.object2.array1"))).size() == 5); assertTrue("expected 4 array[2] items", ((Map)(JsonPath.read(doc, "$.object2.array1[2]"))).size() == 4); assertTrue("expected 4 array1[2].array2 items", ((List)(JsonPath.read(doc, "$.object2.array1[2].array2"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(JsonPath.read(doc, "$.trueValue"))); - assertTrue("expected false", Boolean.FALSE.equals(JsonPath.read(doc, "$.falseValue"))); - assertTrue("expected null", null == JsonPath.read(doc, "$.nullValue")); - assertTrue("expected hello world!", "hello world!".equals(JsonPath.read(doc, "$.stringValue"))); - assertTrue("expected 42", Integer.valueOf(42).equals(JsonPath.read(doc, "$.intValue"))); - assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(JsonPath.read(doc, "$.doubleValue"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(JsonPath.read(doc, "$.complexStringValue"))); - assertTrue("expected v1", "v1".equals(JsonPath.read(doc, "$.object2.k1"))); - assertTrue("expected v2", "v2".equals(JsonPath.read(doc, "$.object2.k2"))); - assertTrue("expected v3", "v3".equals(JsonPath.read(doc, "$.object2.k3"))); - assertTrue("expected 1", Integer.valueOf(1).equals(JsonPath.read(doc, "$.object2.array1[0]"))); - assertTrue("expected 2", Integer.valueOf(2).equals(JsonPath.read(doc, "$.object2.array1[1]"))); - assertTrue("expected v4", "v4".equals(JsonPath.read(doc, "$.object2.array1[2].k4"))); - assertTrue("expected v5", "v5".equals(JsonPath.read(doc, "$.object2.array1[2].k5"))); - assertTrue("expected v6", "v6".equals(JsonPath.read(doc, "$.object2.array1[2].k6"))); - assertTrue("expected 5", Integer.valueOf(5).equals(JsonPath.read(doc, "$.object2.array1[2].array2[0]"))); - assertTrue("expected 6", Integer.valueOf(6).equals(JsonPath.read(doc, "$.object2.array1[2].array2[1]"))); - assertTrue("expected 7", Integer.valueOf(7).equals(JsonPath.read(doc, "$.object2.array1[2].array2[2]"))); - assertTrue("expected 8", Integer.valueOf(8).equals(JsonPath.read(doc, "$.object2.array1[2].array2[3]"))); - assertTrue("expected 3", Integer.valueOf(3).equals(JsonPath.read(doc, "$.object2.array1[3]"))); - assertTrue("expected 4", Integer.valueOf(4).equals(JsonPath.read(doc, "$.object2.array1[4]"))); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueValue"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseValue"))); + assertTrue("expected null", JSONObject.NULL.equals(jsonObject.query("/nullValue"))); + assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/stringValue"))); + assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/intValue"))); + assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(jsonObject.query("/doubleValue"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/complexStringValue"))); + assertTrue("expected v1", "v1".equals(jsonObject.query("/object2/k1"))); + assertTrue("expected v2", "v2".equals(jsonObject.query("/object2/k2"))); + assertTrue("expected v3", "v3".equals(jsonObject.query("/object2/k3"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/object2/array1/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/object2/array1/1"))); + assertTrue("expected v4", "v4".equals(jsonObject.query("/object2/array1/2/k4"))); + assertTrue("expected v5", "v5".equals(jsonObject.query("/object2/array1/2/k5"))); + assertTrue("expected v6", "v6".equals(jsonObject.query("/object2/array1/2/k6"))); + assertTrue("expected 5", Integer.valueOf(5).equals(jsonObject.query("/object2/array1/2/array2/0"))); + assertTrue("expected 6", Integer.valueOf(6).equals(jsonObject.query("/object2/array1/2/array2/1"))); + assertTrue("expected 7", Integer.valueOf(7).equals(jsonObject.query("/object2/array1/2/array2/2"))); + assertTrue("expected 8", Integer.valueOf(8).equals(jsonObject.query("/object2/array1/2/array2/3"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/object2/array1/3"))); + assertTrue("expected 4", Integer.valueOf(4).equals(jsonObject.query("/object2/array1/4"))); } } From a1893ebc02fc11b0fa895ee8591ff40e1d24abd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Mon, 16 May 2016 14:54:01 +0200 Subject: [PATCH 214/451] unittests for stlear/JSON-Java#233 --- src/test/org/json/junit/JSONArrayTest.java | 28 ++++++++++++++++++-- src/test/org/json/junit/JSONObjectTest.java | 29 +++++++++++++++++++-- 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/src/test/org/json/junit/JSONArrayTest.java b/src/test/org/json/junit/JSONArrayTest.java index 455d680..ffc9c26 100644 --- a/src/test/org/json/junit/JSONArrayTest.java +++ b/src/test/org/json/junit/JSONArrayTest.java @@ -1,15 +1,24 @@ package org.json.junit; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import org.json.JSONPointerException; import org.junit.Test; -import com.jayway.jsonpath.*; +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.JsonPath; /** @@ -686,4 +695,19 @@ public class JSONArrayTest { new Long(-1).equals(Long.parseLong((String) it.next()))); assertTrue("should be at end of array", !it.hasNext()); } + + @Test(expected = JSONPointerException.class) + public void queryWithNoResult() { + new JSONArray().query("/a/b"); + } + + @Test + public void optQueryWithNoResult() { + assertNull(new JSONArray().optQuery("/a/b")); + } + + @Test(expected = IllegalArgumentException.class) + public void optQueryWithSyntaxError() { + new JSONArray().optQuery("invalid"); + } } diff --git a/src/test/org/json/junit/JSONObjectTest.java b/src/test/org/json/junit/JSONObjectTest.java index 869fe46..7624ffb 100644 --- a/src/test/org/json/junit/JSONObjectTest.java +++ b/src/test/org/json/junit/JSONObjectTest.java @@ -1,6 +1,7 @@ package org.json.junit; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -10,16 +11,25 @@ import java.io.StringWriter; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import org.json.CDL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; +import org.json.JSONPointerException; import org.json.XML; import org.junit.Test; -import com.jayway.jsonpath.*; +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.JsonPath; /** * JSONObject, along with JSONArray, are the central classes of the reference app. @@ -1899,4 +1909,19 @@ public class JSONObjectTest { String sNull = XML.toString(jsonObjectNull); assertTrue("null should emit an empty string", "".equals(sNull)); } + + @Test(expected = JSONPointerException.class) + public void queryWithNoResult() { + new JSONObject().query("/a/b"); + } + + @Test + public void optQueryWithNoResult() { + assertNull(new JSONObject().optQuery("/a/b")); + } + + @Test(expected = IllegalArgumentException.class) + public void optQueryWithSyntaxError() { + new JSONObject().optQuery("invalid"); + } } From c7fdada0fd4b65ce3beb04e67c8dc64e7e11189a Mon Sep 17 00:00:00 2001 From: Mads Ager Date: Thu, 2 Jun 2016 16:41:43 +0200 Subject: [PATCH 215/451] Add test that an invalid escape sequence results in a JSONException and not a NumberFormatException. --- src/test/org/json/junit/JSONObjectTest.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/test/org/json/junit/JSONObjectTest.java b/src/test/org/json/junit/JSONObjectTest.java index 1c8beb2..6ef3615 100644 --- a/src/test/org/json/junit/JSONObjectTest.java +++ b/src/test/org/json/junit/JSONObjectTest.java @@ -1924,4 +1924,10 @@ public class JSONObjectTest { public void optQueryWithSyntaxError() { new JSONObject().optQuery("invalid"); } + + @Test(expected = JSONException.class) + public void invalidEscapeSequence() { + String json = "{ \"\\url\": \"value\" }"; + new JSONObject(json); + } } From 80f9e48e64e89ca7710257939076c3e9a8000b21 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 16 Jun 2016 12:20:54 -0400 Subject: [PATCH 216/451] Moves src folder to simplify build.gradle configuration. If JSON-Java source is merged, it's src fold would now be src/main/java/org.json/ instead of src/main/org.json as well. --- .gitignore | 6 ++++++ build.gradle | 17 ++--------------- src/test/{ => java}/org/json/junit/CDLTest.java | 0 .../org/json/junit/CookieListTest.java | 0 .../{ => java}/org/json/junit/CookieTest.java | 0 .../{ => java}/org/json/junit/EnumTest.java | 0 .../{ => java}/org/json/junit/HTTPTest.java | 0 .../org/json/junit/JSONArrayTest.java | 0 .../{ => java}/org/json/junit/JSONMLTest.java | 0 .../org/json/junit/JSONObjectTest.java | 0 .../org/json/junit/JSONPointerTest.java | 0 .../org/json/junit/JSONStringerTest.java | 0 .../org/json/junit/JunitTestSuite.java | 0 src/test/{ => java}/org/json/junit/MyBean.java | 0 .../org/json/junit/MyBigNumberBean.java | 0 src/test/{ => java}/org/json/junit/MyEnum.java | 0 .../{ => java}/org/json/junit/MyEnumClass.java | 0 .../{ => java}/org/json/junit/MyEnumField.java | 0 .../{ => java}/org/json/junit/MyJsonString.java | 0 .../org/json/junit/MyPublicClass.java | 0 .../{ => java}/org/json/junit/PropertyTest.java | 0 .../org/json/junit/StringsResourceBundle.java | 0 .../{ => java}/org/json/junit/TestRunner.java | 0 src/test/{ => java}/org/json/junit/Util.java | 0 src/test/{ => java}/org/json/junit/XMLTest.java | 0 25 files changed, 8 insertions(+), 15 deletions(-) rename src/test/{ => java}/org/json/junit/CDLTest.java (100%) rename src/test/{ => java}/org/json/junit/CookieListTest.java (100%) rename src/test/{ => java}/org/json/junit/CookieTest.java (100%) rename src/test/{ => java}/org/json/junit/EnumTest.java (100%) rename src/test/{ => java}/org/json/junit/HTTPTest.java (100%) rename src/test/{ => java}/org/json/junit/JSONArrayTest.java (100%) rename src/test/{ => java}/org/json/junit/JSONMLTest.java (100%) rename src/test/{ => java}/org/json/junit/JSONObjectTest.java (100%) rename src/test/{ => java}/org/json/junit/JSONPointerTest.java (100%) rename src/test/{ => java}/org/json/junit/JSONStringerTest.java (100%) rename src/test/{ => java}/org/json/junit/JunitTestSuite.java (100%) rename src/test/{ => java}/org/json/junit/MyBean.java (100%) rename src/test/{ => java}/org/json/junit/MyBigNumberBean.java (100%) rename src/test/{ => java}/org/json/junit/MyEnum.java (100%) rename src/test/{ => java}/org/json/junit/MyEnumClass.java (100%) rename src/test/{ => java}/org/json/junit/MyEnumField.java (100%) rename src/test/{ => java}/org/json/junit/MyJsonString.java (100%) rename src/test/{ => java}/org/json/junit/MyPublicClass.java (100%) rename src/test/{ => java}/org/json/junit/PropertyTest.java (100%) rename src/test/{ => java}/org/json/junit/StringsResourceBundle.java (100%) rename src/test/{ => java}/org/json/junit/TestRunner.java (100%) rename src/test/{ => java}/org/json/junit/Util.java (100%) rename src/test/{ => java}/org/json/junit/XMLTest.java (100%) diff --git a/.gitignore b/.gitignore index 9e7b59c..7afd420 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,9 @@ build .classpath .project .settings/ +/.gradle/ +/gradle/ +/gradlew +/gradlew.bat +.gitmodules +src/main/ diff --git a/build.gradle b/build.gradle index ad186a1..d2969d4 100644 --- a/build.gradle +++ b/build.gradle @@ -4,21 +4,8 @@ apply plugin: 'jacoco' sourceSets { // Uncomment main if you have merged JSON-Java and JSON-Java-unit-test code - main { - java { - srcDir 'src' - exclude 'test/' - } - } - test { - java { - srcDir 'src/test' - exclude 'resources/' - } - resources { - srcDir 'resources' - } - } + main + test } repositories { diff --git a/src/test/org/json/junit/CDLTest.java b/src/test/java/org/json/junit/CDLTest.java similarity index 100% rename from src/test/org/json/junit/CDLTest.java rename to src/test/java/org/json/junit/CDLTest.java diff --git a/src/test/org/json/junit/CookieListTest.java b/src/test/java/org/json/junit/CookieListTest.java similarity index 100% rename from src/test/org/json/junit/CookieListTest.java rename to src/test/java/org/json/junit/CookieListTest.java diff --git a/src/test/org/json/junit/CookieTest.java b/src/test/java/org/json/junit/CookieTest.java similarity index 100% rename from src/test/org/json/junit/CookieTest.java rename to src/test/java/org/json/junit/CookieTest.java diff --git a/src/test/org/json/junit/EnumTest.java b/src/test/java/org/json/junit/EnumTest.java similarity index 100% rename from src/test/org/json/junit/EnumTest.java rename to src/test/java/org/json/junit/EnumTest.java diff --git a/src/test/org/json/junit/HTTPTest.java b/src/test/java/org/json/junit/HTTPTest.java similarity index 100% rename from src/test/org/json/junit/HTTPTest.java rename to src/test/java/org/json/junit/HTTPTest.java diff --git a/src/test/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java similarity index 100% rename from src/test/org/json/junit/JSONArrayTest.java rename to src/test/java/org/json/junit/JSONArrayTest.java diff --git a/src/test/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java similarity index 100% rename from src/test/org/json/junit/JSONMLTest.java rename to src/test/java/org/json/junit/JSONMLTest.java diff --git a/src/test/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java similarity index 100% rename from src/test/org/json/junit/JSONObjectTest.java rename to src/test/java/org/json/junit/JSONObjectTest.java diff --git a/src/test/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java similarity index 100% rename from src/test/org/json/junit/JSONPointerTest.java rename to src/test/java/org/json/junit/JSONPointerTest.java diff --git a/src/test/org/json/junit/JSONStringerTest.java b/src/test/java/org/json/junit/JSONStringerTest.java similarity index 100% rename from src/test/org/json/junit/JSONStringerTest.java rename to src/test/java/org/json/junit/JSONStringerTest.java diff --git a/src/test/org/json/junit/JunitTestSuite.java b/src/test/java/org/json/junit/JunitTestSuite.java similarity index 100% rename from src/test/org/json/junit/JunitTestSuite.java rename to src/test/java/org/json/junit/JunitTestSuite.java diff --git a/src/test/org/json/junit/MyBean.java b/src/test/java/org/json/junit/MyBean.java similarity index 100% rename from src/test/org/json/junit/MyBean.java rename to src/test/java/org/json/junit/MyBean.java diff --git a/src/test/org/json/junit/MyBigNumberBean.java b/src/test/java/org/json/junit/MyBigNumberBean.java similarity index 100% rename from src/test/org/json/junit/MyBigNumberBean.java rename to src/test/java/org/json/junit/MyBigNumberBean.java diff --git a/src/test/org/json/junit/MyEnum.java b/src/test/java/org/json/junit/MyEnum.java similarity index 100% rename from src/test/org/json/junit/MyEnum.java rename to src/test/java/org/json/junit/MyEnum.java diff --git a/src/test/org/json/junit/MyEnumClass.java b/src/test/java/org/json/junit/MyEnumClass.java similarity index 100% rename from src/test/org/json/junit/MyEnumClass.java rename to src/test/java/org/json/junit/MyEnumClass.java diff --git a/src/test/org/json/junit/MyEnumField.java b/src/test/java/org/json/junit/MyEnumField.java similarity index 100% rename from src/test/org/json/junit/MyEnumField.java rename to src/test/java/org/json/junit/MyEnumField.java diff --git a/src/test/org/json/junit/MyJsonString.java b/src/test/java/org/json/junit/MyJsonString.java similarity index 100% rename from src/test/org/json/junit/MyJsonString.java rename to src/test/java/org/json/junit/MyJsonString.java diff --git a/src/test/org/json/junit/MyPublicClass.java b/src/test/java/org/json/junit/MyPublicClass.java similarity index 100% rename from src/test/org/json/junit/MyPublicClass.java rename to src/test/java/org/json/junit/MyPublicClass.java diff --git a/src/test/org/json/junit/PropertyTest.java b/src/test/java/org/json/junit/PropertyTest.java similarity index 100% rename from src/test/org/json/junit/PropertyTest.java rename to src/test/java/org/json/junit/PropertyTest.java diff --git a/src/test/org/json/junit/StringsResourceBundle.java b/src/test/java/org/json/junit/StringsResourceBundle.java similarity index 100% rename from src/test/org/json/junit/StringsResourceBundle.java rename to src/test/java/org/json/junit/StringsResourceBundle.java diff --git a/src/test/org/json/junit/TestRunner.java b/src/test/java/org/json/junit/TestRunner.java similarity index 100% rename from src/test/org/json/junit/TestRunner.java rename to src/test/java/org/json/junit/TestRunner.java diff --git a/src/test/org/json/junit/Util.java b/src/test/java/org/json/junit/Util.java similarity index 100% rename from src/test/org/json/junit/Util.java rename to src/test/java/org/json/junit/Util.java diff --git a/src/test/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java similarity index 100% rename from src/test/org/json/junit/XMLTest.java rename to src/test/java/org/json/junit/XMLTest.java From 46a1c9acf9573d20648f101058f2e4ac51a1163a Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 16 Jun 2016 13:02:08 -0400 Subject: [PATCH 217/451] Adds test case to confirm the parsing of control characters --- .../java/org/json/junit/JSONObjectTest.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 6ef3615..d550139 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1564,6 +1564,26 @@ public class JSONObjectTest { assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3"))); } + + /** + * RFC 7159 defines control characters to be U+0000 through U+001F. This test verifies that the parser is checking for these in expected ways. + */ + @Test + public void jsonObjectParseControlCharacters(){ + for(int i = 0;i<=0x001f;i++){ + final String charString = String.valueOf((char)i); + final String source = "{\"key\":\""+charString+"\"}"; + try { + JSONObject jo = new JSONObject(source); + assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key"))); + } catch (JSONException ex) { + assertTrue("Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error", + i=='\0' || i=='\n' || i=='\r' + ); + } + } + } + /** * Explore how JSONObject handles parsing errors. */ From c5deff636bd1413fab65ee0e64484c5422fd9a6e Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 16 Jun 2016 23:59:34 -0400 Subject: [PATCH 218/451] updates README for new project layout --- README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d08751d..40a4ebf 100644 --- a/README.md +++ b/README.md @@ -29,15 +29,22 @@ git clone https://github.com/stleary/JSON-Java-unit-test.git . \# Create a directory structure for the JSON-Java code ```` # Windows version -md /s src\org\json +md /s src\main\java\org\json +# *nix version +mkdir -p src/main/java/org/json ```` \# clone JSON-Java ```` -git clone https://github.com/stleary/JSON-Java.git src\org\json +#Windows version +git clone https://github.com/stleary/JSON-Java.git src\main\java\org\json + +#*Nix version +git clone https://github.com/stleary/JSON-Java.git src/main/java/org/json ```` \# Build, then execute the unit tests and code coverage ```` gradle clean build test jacocoTestReport + ```` Unit test results will be in build\reports\tests\index.html
Code coverage will be in build\reports\jacoco\html\index.html From 1204ea9dcf611b874d7b0feadad86f84da4c2a63 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 17 Jun 2016 00:04:27 -0400 Subject: [PATCH 219/451] fixes a typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 40a4ebf..385c222 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ When adding a new unit test, don't forget to update JunitTestSuite.java. The fundamental issues with JSON-Java testing are:
* JSONObjects are unordered, making simple string comparison ineffective. -* Comparisons via **equals()** is not currently supported. Neither JSONArray nor JSONObject overrride hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. +* Comparisons via **equals()** is not currently supported. Neither JSONArray nor JSONObject override hashCode() or equals(), so comparison defaults to the Object equals(), which is not useful. * Access to the JSONArray and JSONObject internal containers for comparison is not currently available. General issues with unit testing are:
From c2de22471172bcc1e3c328c0a171c0155fc98e06 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 8 Jul 2016 16:58:58 -0400 Subject: [PATCH 220/451] Verify opt method conversions for JSONArray and JSONObject --- src/test/java/org/json/junit/JSONArrayTest.java | 16 ++++++++++++++++ src/test/java/org/json/junit/JSONObjectTest.java | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 7643ee0..ef3a608 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -3,6 +3,8 @@ package org.json.junit; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import java.math.BigDecimal; +import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -414,6 +416,20 @@ public class JSONArrayTest { assertTrue("Array opt string default implicit", "".equals(jsonArray.optString(-1))); } + + /** + * Verifies that the opt methods properly convert string values. + */ + @Test + public void optStringConversion(){ + JSONArray ja = new JSONArray("[\"123\",\"true\",\"false\"]"); + assertTrue("unexpected optBoolean value",ja.optBoolean(1,false)==true); + assertTrue("unexpected optBoolean value",ja.optBoolean(2,true)==false); + assertTrue("unexpected optInt value",ja.optInt(0,0)==123); + assertTrue("unexpected optLong value",ja.optLong(0,0)==123); + assertTrue("unexpected optDouble value",ja.optDouble(0,0.0)==123.0); + assertTrue("unexpected optBigInteger value",ja.optBigInteger(0,BigInteger.ZERO).compareTo(new BigInteger("123"))==0); + assertTrue("unexpected optBigDecimal value",ja.optBigDecimal(0,BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); } /** * Exercise the JSONArray.put(value) method with various parameters diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index d550139..08ec964 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1735,6 +1735,22 @@ public class JSONObjectTest { assertTrue("optString() should return default string", "hi".equals(jsonObject.optString("hiKey", "hi"))); } + + /** + * Verifies that the opt methods properly convert string values. + */ + @Test + public void jsonObjectOptStringConversion() { + JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\"}"); + assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true); + assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false); + assertTrue("unexpected optInt value",jo.optInt("int",0)==123); + assertTrue("unexpected optLong value",jo.optLong("int",0)==123); + assertTrue("unexpected optDouble value",jo.optDouble("int",0.0)==123.0); + assertTrue("unexpected optBigInteger value",jo.optBigInteger("int",BigInteger.ZERO).compareTo(new BigInteger("123"))==0); + assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); + + } /** * Confirm behavior when JSONObject put(key, null object) is called From 215321cd28008cfd5b2192efa16cf10f737206c3 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 18 Jul 2016 15:01:36 -0400 Subject: [PATCH 221/451] updates Test cases to support new JSONML and XML conversion options --- src/test/java/org/json/junit/JSONMLTest.java | 37 ++++++++++++++++ src/test/java/org/json/junit/XMLTest.java | 44 ++++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 953a39d..1298591 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -698,4 +698,41 @@ public class JSONMLTest { Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } + /** + * JSON string with lost leading zero and converted "True" to true. See test + * result in comment below. + */ + @Test + public void testToJSONArray_jsonOutput() { + final String originalXml = "011000True"; + final String expectedJsonString = "[\"root\",[\"id\",\"01\"],[\"id\",1],[\"id\",\"00\"],[\"id\",0],[\"item\",{\"id\":\"01\"}],[\"title\",true]]"; + final JSONArray actualJsonOutput = JSONML.toJSONArray(originalXml, false); + assertEquals(expectedJsonString, actualJsonOutput.toString()); + } + + /** + * JSON string cannot be reverted to original xml. See test result in + * comment below. + */ + @Test + public void testToJSONArray_reversibility() { + final String originalXml = "011000True"; + final String revertedXml = JSONML.toString(JSONML.toJSONArray(originalXml, false)); + assertNotEquals(revertedXml, originalXml); + } + + /** + * test passes when using the new method toJsonML. + */ + @Test + public void testToJsonML() { + final String originalXml = "011000True"; + final String expectedJsonString = "[\"root\",[\"id\",\"01\"],[\"id\",\"1\"],[\"id\",\"00\"],[\"id\",\"0\"],[\"item\",{\"id\":\"01\"}],[\"title\",\"True\"]]"; + final JSONArray json = JSONML.toJSONArray(originalXml,true); + assertEquals(expectedJsonString, json.toString()); + + final String reverseXml = JSONML.toString(json); + assertEquals(originalXml, reverseXml); + } + } diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index d35c8ac..2f3fea7 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -1,12 +1,14 @@ package org.json.junit; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.json.JSONArray; import org.json.JSONException; +import org.json.JSONML; import org.json.JSONObject; import org.json.XML; import org.junit.Rule; @@ -723,4 +725,46 @@ public class XMLTest { } */ } + + /** + * JSON string lost leading zero and converted "True" to true. + */ + @Test + public void testToJSONArray_jsonOutput() { + final String originalXml = "011000True"; + final String expectedJsonString = "{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",1,\"00\",0],\"title\":true}}"; + final JSONObject actualJsonOutput = XML.toJSONObject(originalXml, false); + + assertEquals(expectedJsonString, actualJsonOutput.toString()); + } + + /** + * JSON string cannot be reverted to original xml. + */ + @Test + public void testToJSONArray_reversibility() { + final String originalXml = "011000True"; + final String revertedXml = XML.toString(XML.toJSONObject(originalXml, false)); + + assertNotEquals(revertedXml, originalXml); + } + + /** + * test passes when using the new method toJsonArray. + */ + @Test + public void testToJsonXML() { + final String originalXml = "011000True"; + final String expectedJsonString = "{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"True\"}}"; + + final JSONObject json = XML.toJSONObject(originalXml,true); + assertEquals(expectedJsonString, json.toString()); + + final String reverseXml = XML.toString(json); + // this reversal isn't exactly the same. use JSONML for an exact reversal + final String expectedReverseXml = "01011000True"; + + assertEquals(expectedReverseXml, reverseXml); + } + } \ No newline at end of file From c3ba4bdbe5321c0cf2eeae9829e8a6508cd4665b Mon Sep 17 00:00:00 2001 From: Nicholas Cull Date: Sat, 23 Jul 2016 19:12:51 +1000 Subject: [PATCH 222/451] Nesting depth test works as expected. --- .../java/org/json/junit/JSONStringerTest.java | 59 ++++++++++++++++--- 1 file changed, 50 insertions(+), 9 deletions(-) diff --git a/src/test/java/org/json/junit/JSONStringerTest.java b/src/test/java/org/json/junit/JSONStringerTest.java index 19b46de..d4376df 100644 --- a/src/test/java/org/json/junit/JSONStringerTest.java +++ b/src/test/java/org/json/junit/JSONStringerTest.java @@ -27,7 +27,7 @@ public class JSONStringerTest { jsonStringer.key(null); assertTrue("Expected an exception", false); } catch (JSONException e) { - assertTrue("Expected an exception message", + assertTrue("Expected an exception message", "Null key.". equals(e.getMessage())); } @@ -44,7 +44,7 @@ public class JSONStringerTest { jsonStringer.key("hi"); assertTrue("Expected an exception", false); } catch (JSONException e) { - assertTrue("Expected an exception message", + assertTrue("Expected an exception message", "Misplaced key.". equals(e.getMessage())); } @@ -61,7 +61,7 @@ public class JSONStringerTest { try { jsonStringer.array(); } catch (JSONException e) { - assertTrue("Expected an exception message", + assertTrue("Expected an exception message", "Misplaced array.". equals(e.getMessage())); } @@ -78,7 +78,7 @@ public class JSONStringerTest { try { jsonStringer.endArray(); } catch (JSONException e) { - assertTrue("Expected an exception message", + assertTrue("Expected an exception message", "Misplaced endArray.". equals(e.getMessage())); } @@ -95,7 +95,7 @@ public class JSONStringerTest { try { jsonStringer.endObject(); } catch (JSONException e) { - assertTrue("Expected an exception message", + assertTrue("Expected an exception message", "Misplaced endObject.". equals(e.getMessage())); } @@ -112,7 +112,7 @@ public class JSONStringerTest { try { jsonStringer.object(); } catch (JSONException e) { - assertTrue("Expected an exception message", + assertTrue("Expected an exception message", "Misplaced object.". equals(e.getMessage())); } @@ -125,7 +125,47 @@ public class JSONStringerTest { @Test public void exceedNestDepthException() { try { - new JSONStringer().object(). + JSONStringer s = new JSONStringer(); + s.object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). + key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(); + s.key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). @@ -165,9 +205,10 @@ public class JSONStringerTest { key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(). key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(); + fail("Expected an exception message"); } catch (JSONException e) { - assertTrue("Expected an exception message", - "". + assertTrue("Expected an exception message", + "Nesting too deep.". equals(e.getMessage())); } } From 72c2b911bfba67472c6d03bdb4ffa12c47b56b70 Mon Sep 17 00:00:00 2001 From: Nicholas Cull Date: Sat, 23 Jul 2016 22:33:19 +1000 Subject: [PATCH 223/451] Tests for toString(), write(), toList(), and toMap(). Explicitly test variations of toString() and write() for different indent levels, and different method overloads. Also create some tests for the new toList() and toMap() methods for coverage improvements to JSONArray and JSONObject. --- .../java/org/json/junit/JSONArrayTest.java | 195 ++++++++++++++++++ .../java/org/json/junit/JSONObjectTest.java | 180 +++++++++++++++- 2 files changed, 373 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index ef3a608..c818e8b 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -2,7 +2,10 @@ package org.json.junit; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import java.io.StringWriter; +import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; @@ -639,6 +642,71 @@ public class JSONArrayTest { !jsonArray.similar(otherJsonArray)); } + /** + * Exercise JSONArray toString() method with various indent levels. + */ + @Test + public void jsonArrayToStringIndent() { + String jsonArray0Str = + "[" + + "[1,2," + + "{\"key3\":true}" + + "]," + + "{\"key1\":\"val1\",\"key2\":" + + "{\"key2\":\"val2\"}" + + "}," + + "[" + + "[1,2.1]" + + "," + + "[null]" + + "]" + + "]"; + + String jsonArray1Str = + "[\n" + + " [\n" + + " 1,\n" + + " 2,\n" + + " {\"key3\": true}\n" + + " ],\n" + + " {\n" + + " \"key1\": \"val1\",\n" + + " \"key2\": {\"key2\": \"val2\"}\n" + + " },\n" + + " [\n" + + " [\n" + + " 1,\n" + + " 2.1\n" + + " ],\n" + + " [null]\n" + + " ]\n" + + "]"; + String jsonArray4Str = + "[\n" + + " [\n" + + " 1,\n" + + " 2,\n" + + " {\"key3\": true}\n" + + " ],\n" + + " {\n" + + " \"key1\": \"val1\",\n" + + " \"key2\": {\"key2\": \"val2\"}\n" + + " },\n" + + " [\n" + + " [\n" + + " 1,\n" + + " 2.1\n" + + " ],\n" + + " [null]\n" + + " ]\n" + + "]"; + JSONArray jsonArray = new JSONArray(jsonArray0Str); + assertEquals(jsonArray0Str, jsonArray.toString()); + assertEquals(jsonArray0Str, jsonArray.toString(0)); + assertEquals(jsonArray1Str, jsonArray.toString(1)); + assertEquals(jsonArray4Str, jsonArray.toString(4)); + } + /** * Convert an empty JSONArray to JSONObject */ @@ -726,4 +794,131 @@ public class JSONArrayTest { public void optQueryWithSyntaxError() { new JSONArray().optQuery("invalid"); } + + + /** + * Exercise the JSONArray write() method + */ + @Test + public void write() { + String str = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":2,\"key3\":3}]"; + String expectedStr = str; + JSONArray jsonArray = new JSONArray(str); + StringWriter stringWriter = new StringWriter(); + Writer writer = jsonArray.write(stringWriter); + String actualStr = writer.toString(); + assertTrue("write() expected " + expectedStr + + "but found " + actualStr, + expectedStr.equals(actualStr)); + StringBuilder stringBuilder = new StringBuilder(); + Appendable appendable = jsonArray.write(stringBuilder); + actualStr = appendable.toString(); + assertTrue("write() expected " + expectedStr + + "but found " + actualStr, + expectedStr.equals(actualStr)); + } + + /** + * Exercise the JSONArray write(Appendable, int, int) method + */ + @Test + public void write3Param() { + String str0 = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":false,\"key3\":3.14}]"; + String str2 = + "[\n" + + " \"value1\",\n" + + " \"value2\",\n" + + " {\n" + + " \"key1\": 1,\n" + + " \"key2\": false,\n" + + " \"key3\": 3.14\n" + + " }\n" + + " ]"; + String expectedStr = str0; + JSONArray jsonArray = new JSONArray(str0); + StringWriter stringWriter = new StringWriter(); + Writer writer = jsonArray.write(stringWriter, 0, 0); + String actualStr = writer.toString(); + assertEquals(expectedStr, actualStr); + expectedStr = str0; + StringBuilder stringBuilder = new StringBuilder(); + Appendable appendable = jsonArray.write(stringBuilder, 0, 0); + actualStr = appendable.toString(); + assertEquals(expectedStr, actualStr); + expectedStr = str2; + stringBuilder = new StringBuilder(); + appendable = jsonArray.write(stringBuilder, 2, 1); + actualStr = appendable.toString(); + assertEquals(expectedStr, actualStr); + } + + /** + * Exercise JSONArray toString() method with various indent levels. + */ + @Test + public void toList() { + String jsonArrayStr = + "[" + + "[1,2," + + "{\"key3\":true}" + + "]," + + "{\"key1\":\"val1\",\"key2\":" + + "{\"key2\":null}," + + "\"key3\":42,\"key4\":[]" + + "}," + + "[" + + "[\"value1\",2.1]" + + "," + + "[null]" + + "]" + + "]"; + + JSONArray jsonArray = new JSONArray(jsonArrayStr); + List list = jsonArray.toList(); + + assertTrue("List should not be null", list != null); + assertTrue("List should have 3 elements", list.size() == 3); + + List val1List = (List) list.get(0); + assertTrue("val1 should not be null", val1List != null); + assertTrue("val1 should have 3 elements", val1List.size() == 3); + + assertTrue("val1 value 1 should be 1", val1List.get(0).equals(Integer.valueOf(1))); + assertTrue("val1 value 2 should be 2", val1List.get(1).equals(Integer.valueOf(2))); + + Map key1Value3Map = (Map)val1List.get(2); + assertTrue("Map should not be null", key1Value3Map != null); + assertTrue("Map should have 1 element", key1Value3Map.size() == 1); + assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); + + Map val2Map = (Map) list.get(1); + assertTrue("val2 should not be null", val2Map != null); + assertTrue("val2 should have 4 elements", val2Map.size() == 4); + assertTrue("val2 map key 1 should be val1", val2Map.get("key1").equals("val1")); + assertTrue("val2 map key 3 should be 42", val2Map.get("key3").equals(Integer.valueOf(42))); + + Map val2Key2Map = (Map)val2Map.get("key2"); + assertTrue("val2 map key 2 should not be null", val2Key2Map != null); + assertTrue("val2 map key 2 should have an entry", val2Key2Map.containsKey("key2")); + assertTrue("val2 map key 2 value should be null", val2Key2Map.get("key2") == null); + + List val2Key4List = (List)val2Map.get("key4"); + assertTrue("val2 map key 4 should not be null", val2Key4List != null); + assertTrue("val2 map key 4 should be empty", val2Key4List.isEmpty()); + + List val3List = (List) list.get(2); + assertTrue("val3 should not be null", val3List != null); + assertTrue("val3 should have 2 elements", val3List.size() == 2); + + List val3Val1List = (List)val3List.get(0); + assertTrue("val3 list val 1 should not be null", val3Val1List != null); + assertTrue("val3 list val 1 should have 2 elements", val3Val1List.size() == 2); + assertTrue("val3 list val 1 list element 1 should be value1", val3Val1List.get(0).equals("value1")); + assertTrue("val3 list val 1 list element 2 should be 2.1", val3Val1List.get(1).equals(Double.valueOf("2.1"))); + + List val3Val2List = (List)val3List.get(1); + assertTrue("val3 list val 2 should not be null", val3Val2List != null); + assertTrue("val3 list val 2 should have 1 element", val3Val2List.size() == 1); + assertTrue("val3 list val 2 list element 1 should be null", val3Val2List.get(0) == null); + } } diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 08ec964..73029e7 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -3,6 +3,7 @@ package org.json.junit; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -1371,6 +1372,74 @@ public class JSONObjectTest { assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); } + /** + * Exercise JSONObject toString() method with various indent levels. + */ + @Test + public void jsonObjectToStringIndent() { + String jsonObject0Str = + "{"+ + "\"key1\":" + + "[1,2," + + "{\"key3\":true}" + + "],"+ + "\"key2\":" + + "{\"key1\":\"val1\",\"key2\":" + + "{\"key2\":\"val2\"}" + + "},"+ + "\"key3\":" + + "[" + + "[1,2.1]" + + "," + + "[null]" + + "]"+ + "}"; + + String jsonObject1Str = + "{\n" + + " \"key1\": [\n" + + " 1,\n" + + " 2,\n" + + " {\"key3\": true}\n" + + " ],\n" + + " \"key2\": {\n" + + " \"key1\": \"val1\",\n" + + " \"key2\": {\"key2\": \"val2\"}\n" + + " },\n" + + " \"key3\": [\n" + + " [\n" + + " 1,\n" + + " 2.1\n" + + " ],\n" + + " [null]\n" + + " ]\n" + + "}"; + String jsonObject4Str = + "{\n" + + " \"key1\": [\n" + + " 1,\n" + + " 2,\n" + + " {\"key3\": true}\n" + + " ],\n" + + " \"key2\": {\n" + + " \"key1\": \"val1\",\n" + + " \"key2\": {\"key2\": \"val2\"}\n" + + " },\n" + + " \"key3\": [\n" + + " [\n" + + " 1,\n" + + " 2.1\n" + + " ],\n" + + " [null]\n" + + " ]\n" + + "}"; + JSONObject jsonObject = new JSONObject(jsonObject0Str); + assertEquals(jsonObject0Str, jsonObject.toString()); + assertEquals(jsonObject0Str, jsonObject.toString(0)); + assertEquals(jsonObject1Str, jsonObject.toString(1)); + assertEquals(jsonObject4Str, jsonObject.toString(4)); + } + /** * Explores how JSONObject handles maps. Insert a string/string map * as a value in a JSONObject. It will remain a map. Convert the @@ -1441,7 +1510,7 @@ public class JSONObjectTest { String jsonArrayStr = "[1,2,3]"; JSONArray jsonArray = new JSONArray(jsonArrayStr); - assertTrue("jsonArra valueToString() incorrect", + assertTrue("jsonArray valueToString() incorrect", JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); Map map = new HashMap(); map.put("key1", "val1"); @@ -1840,7 +1909,7 @@ public class JSONObjectTest { */ @Test public void write() { - String str = "{\"key\":\"value\"}"; + String str = "{\"key1\":\"value1\",\"key2\":[1,2,3]}"; String expectedStr = str; JSONObject jsonObject = new JSONObject(str); StringWriter stringWriter = new StringWriter(); @@ -1849,6 +1918,45 @@ public class JSONObjectTest { assertTrue("write() expected " +expectedStr+ "but found " +actualStr, expectedStr.equals(actualStr)); + StringBuilder stringBuilder = new StringBuilder(); + Appendable appendable = jsonObject.write(stringBuilder); + actualStr = appendable.toString(); + assertTrue("write() expected " +expectedStr+ + "but found " +actualStr, + expectedStr.equals(actualStr)); + } + + /** + * Exercise the JSONObject write(Appendable, int, int) method + */ + @Test + public void write3Param() { + String str0 = "{\"key1\":\"value1\",\"key2\":[1,false,3.14]}"; + String str2 = + "{\n" + + " \"key1\": \"value1\",\n" + + " \"key2\": [\n" + + " 1,\n" + + " false,\n" + + " 3.14\n" + + " ]\n" + + " }"; + String expectedStr = str0; + JSONObject jsonObject = new JSONObject(str0); + StringWriter stringWriter = new StringWriter(); + Writer writer = jsonObject.write(stringWriter,0,0); + String actualStr = writer.toString(); + assertEquals(expectedStr, actualStr); + expectedStr = str0; + StringBuilder stringBuilder = new StringBuilder(); + Appendable appendable = jsonObject.write(stringBuilder,0,0); + actualStr = appendable.toString(); + assertEquals(expectedStr, actualStr); + expectedStr = str2; + stringBuilder = new StringBuilder(); + appendable = jsonObject.write(stringBuilder,2,1); + actualStr = appendable.toString(); + assertEquals(expectedStr, actualStr); } /** @@ -1966,4 +2074,72 @@ public class JSONObjectTest { String json = "{ \"\\url\": \"value\" }"; new JSONObject(json); } + + /** + * Exercise JSONObject toMap() method. + */ + @Test + public void toMap() { + String jsonObjectStr = + "{" + + "\"key1\":" + + "[1,2," + + "{\"key3\":true}" + + "]," + + "\"key2\":" + + "{\"key1\":\"val1\",\"key2\":" + + "{\"key2\":null}," + + "\"key3\":42" + + "}," + + "\"key3\":" + + "[" + + "[\"value1\",2.1]" + + "," + + "[null]" + + "]" + + "}"; + + JSONObject jsonObject = new JSONObject(jsonObjectStr); + Map map = jsonObject.toMap(); + + assertTrue("Map should not be null", map != null); + assertTrue("Map should have 3 elements", map.size() == 3); + + List key1List = (List)map.get("key1"); + assertTrue("key1 should not be null", key1List != null); + assertTrue("key1 list should have 3 elements", key1List.size() == 3); + assertTrue("key1 value 1 should be 1", key1List.get(0).equals(Integer.valueOf(1))); + assertTrue("key1 value 2 should be 2", key1List.get(1).equals(Integer.valueOf(2))); + + Map key1Value3Map = (Map)key1List.get(2); + assertTrue("Map should not be null", key1Value3Map != null); + assertTrue("Map should have 1 element", key1Value3Map.size() == 1); + assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); + + Map key2Map = (Map)map.get("key2"); + assertTrue("key2 should not be null", key2Map != null); + assertTrue("key2 map should have 3 elements", key2Map.size() == 3); + assertTrue("key2 map key 1 should be val1", key2Map.get("key1").equals("val1")); + assertTrue("key2 map key 3 should be 42", key2Map.get("key3").equals(Integer.valueOf(42))); + + Map key2Val2Map = (Map)key2Map.get("key2"); + assertTrue("key2 map key 2 should not be null", key2Val2Map != null); + assertTrue("key2 map key 2 should have an entry", key2Val2Map.containsKey("key2")); + assertTrue("key2 map key 2 value should be null", key2Val2Map.get("key2") == null); + + List key3List = (List)map.get("key3"); + assertTrue("key3 should not be null", key3List != null); + assertTrue("key3 list should have 3 elements", key3List.size() == 2); + + List key3Val1List = (List)key3List.get(0); + assertTrue("key3 list val 1 should not be null", key3Val1List != null); + assertTrue("key3 list val 1 should have 2 elements", key3Val1List.size() == 2); + assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); + assertTrue("key3 list val 1 list element 2 should be 2.1", key3Val1List.get(1).equals(Double.valueOf("2.1"))); + + List key3Val2List = (List)key3List.get(1); + assertTrue("key3 list val 2 should not be null", key3Val2List != null); + assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1); + assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null); + } } From ae77b5cd83121555152a13407fce230992afc0c0 Mon Sep 17 00:00:00 2001 From: Nicholas Cull Date: Sat, 23 Jul 2016 22:51:50 +1000 Subject: [PATCH 224/451] Tests for deep copy and mutability of toList() and toMap(). Both toMap() and toList() return deep copies, which are also mutable. That is, any changes to the JSONObject or JSONArray do not affect the newly create Map or List, and vice-versa. The resulting objects can be altered. --- src/test/java/org/json/junit/JSONArrayTest.java | 8 ++++++++ src/test/java/org/json/junit/JSONObjectTest.java | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index c818e8b..9f0e773 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -920,5 +920,13 @@ public class JSONArrayTest { assertTrue("val3 list val 2 should not be null", val3Val2List != null); assertTrue("val3 list val 2 should have 1 element", val3Val2List.size() == 1); assertTrue("val3 list val 2 list element 1 should be null", val3Val2List.get(0) == null); + + // assert that toList() is a deep copy + jsonArray.getJSONObject(1).put("key1", "still val1"); + assertTrue("val2 map key 1 should be val1", val2Map.get("key1").equals("val1")); + + // assert that the new list is mutable + assertTrue("Removing an entry should succeed", list.remove(2) != null); + assertTrue("List should have 2 elements", list.size() == 2); } } diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 73029e7..10405b0 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -2141,5 +2141,14 @@ public class JSONObjectTest { assertTrue("key3 list val 2 should not be null", key3Val2List != null); assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1); assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null); + + // Assert that toMap() is a deep copy + jsonObject.getJSONArray("key3").getJSONArray(0).put(0, "still value 1"); + assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); + + // assert that the new map is mutable + assertTrue("Removing a key should succeed", map.remove("key3") != null); + assertTrue("Map should have 2 elements", map.size() == 2); + } } From 6b4edbd40c115e2895af9e3c68908e5ede7ac03e Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 23 Jul 2016 10:02:19 -0500 Subject: [PATCH 225/451] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 385c222..2e2fcc8 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ git clone https://github.com/stleary/JSON-Java-unit-test.git . ```` \# Create a directory structure for the JSON-Java code ```` -# Windows version -md /s src\main\java\org\json +# Windows 10 version +mkdir src\main\java\org\json # *nix version mkdir -p src/main/java/org/json ```` From 2307f6f85e535df6b925056667a7b8f4671e1a99 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 23 Jul 2016 10:12:04 -0500 Subject: [PATCH 226/451] Update README.md --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 2e2fcc8..e45f7bf 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,13 @@ git clone https://github.com/stleary/JSON-Java.git src/main/java/org/json gradle clean build test jacocoTestReport ```` +\# Eclipse setup requires the Gradle IDE plug-in +\# I use Gradle IDE 3.6.4.201503050952-RELEASE org.springsource.ide.eclipse.gradle.feature.feature.group Pivotal Software, Inc. +```` +File > Import > Gradle project > (navigate to your directory) > Build Model > (Select your directory) > Finish +(It is not necessary to run "gradle eclipse" on the project, from the command line) +```` + Unit test results will be in build\reports\tests\index.html
Code coverage will be in build\reports\jacoco\html\index.html From cdfdaba95bb489475ea0aacdbb2f940e1a3dafe0 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 23 Jul 2016 10:12:33 -0500 Subject: [PATCH 227/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e45f7bf..54e085d 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ git clone https://github.com/stleary/JSON-Java.git src/main/java/org/json gradle clean build test jacocoTestReport ```` -\# Eclipse setup requires the Gradle IDE plug-in +\# Eclipse setup requires the Gradle IDE plug-in
\# I use Gradle IDE 3.6.4.201503050952-RELEASE org.springsource.ide.eclipse.gradle.feature.feature.group Pivotal Software, Inc. ```` File > Import > Gradle project > (navigate to your directory) > Build Model > (Select your directory) > Finish From 5d8ea6fa4e91467adce884666b0a26c694701800 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 23 Jul 2016 10:13:21 -0500 Subject: [PATCH 228/451] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 54e085d..faf400a 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,8 @@ gradle clean build test jacocoTestReport ```` \# Eclipse setup requires the Gradle IDE plug-in
-\# I use Gradle IDE 3.6.4.201503050952-RELEASE org.springsource.ide.eclipse.gradle.feature.feature.group Pivotal Software, Inc. +\# I use Gradle IDE 3.6.4.201503050952-RELEASE org.springsource.ide.eclipse.gradle.feature.feature.group Pivotal Software, Inc.
+\# From the Eclipse IDE: ```` File > Import > Gradle project > (navigate to your directory) > Build Model > (Select your directory) > Finish (It is not necessary to run "gradle eclipse" on the project, from the command line) From ffcfa66d7798061df9a5450ce9579d6ee6bbce9f Mon Sep 17 00:00:00 2001 From: Nicholas Cull Date: Sun, 24 Jul 2016 18:56:08 +1000 Subject: [PATCH 229/451] Add JSONString test class. This set of tests demonstrates what happens when JSONString returns various results from its toJSONString() method. Tests for null returns and exceptions thrown. Also tests what happens for non-JSONString objects. The intent is to cover JSONObject's valueToString() and writeValue() methods. --- .../java/org/json/junit/JSONStringTest.java | 310 ++++++++++++++++++ .../java/org/json/junit/JunitTestSuite.java | 7 +- 2 files changed, 314 insertions(+), 3 deletions(-) create mode 100644 src/test/java/org/json/junit/JSONStringTest.java diff --git a/src/test/java/org/json/junit/JSONStringTest.java b/src/test/java/org/json/junit/JSONStringTest.java new file mode 100644 index 0000000..c7d9d3e --- /dev/null +++ b/src/test/java/org/json/junit/JSONStringTest.java @@ -0,0 +1,310 @@ +package org.json.junit; + +import static org.junit.Assert.*; + +import java.io.StringWriter; +import java.util.*; + +import org.json.*; +import org.junit.Test; + +/** + * Tests for JSONString implementations, and the difference between + * {@link JSONObject#valueToString} and {@link JSONObject#writeValue}. + */ +public class JSONStringTest { + + /** + * This tests the JSONObject.writeValue() method. We can't test directly + * due to it being a package-protected method. Instead, we can call + * JSONArray.write(), which delegates the writing of each entry to + * writeValue(). + */ + @Test + public void writeValues() throws Exception { + JSONArray jsonArray = new JSONArray(); + jsonArray.put((Object)null); + + StringWriter writer = new StringWriter(); + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[null]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(JSONObject.NULL); + writer = new StringWriter(); + output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[null]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(new JSONObject()); + writer = new StringWriter(); + output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[{}]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(new JSONArray()); + writer = new StringWriter(); + output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[[]]".equals(output)); + + jsonArray = new JSONArray(); + Map singleMap = Collections.singletonMap("key1", "value1"); + jsonArray.put((Object)singleMap); + writer = new StringWriter(); + output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[{\"key1\":\"value1\"}]".equals(output)); + + jsonArray = new JSONArray(); + List singleList = Collections.singletonList("entry1"); + jsonArray.put((Object)singleList); + writer = new StringWriter(); + output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[[\"entry1\"]]".equals(output)); + + jsonArray = new JSONArray(); + int[] intArray = new int[] { 1, 2, 3 }; + jsonArray.put(intArray); + writer = new StringWriter(); + output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[[1,2,3]]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(24); + writer = new StringWriter(); + output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[24]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put("string value"); + writer = new StringWriter(); + output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"string value\"]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(true); + writer = new StringWriter(); + output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[true]".equals(output)); + + } + + /** + * This tests the JSONObject.valueToString() method. These should be + * identical to the values above, except for the enclosing [ and ]. + */ + @Test + public void valuesToString() throws Exception { + + String output = JSONObject.valueToString(null); + assertTrue("String values should be equal", "null".equals(output)); + + output = JSONObject.valueToString(JSONObject.NULL); + assertTrue("String values should be equal", "null".equals(output)); + + output = JSONObject.valueToString(new JSONObject()); + assertTrue("String values should be equal", "{}".equals(output)); + + output = JSONObject.valueToString(new JSONArray()); + assertTrue("String values should be equal", "[]".equals(output)); + + Map singleMap = Collections.singletonMap("key1", "value1"); + output = JSONObject.valueToString(singleMap); + assertTrue("String values should be equal", "{\"key1\":\"value1\"}".equals(output)); + + List singleList = Collections.singletonList("entry1"); + output = JSONObject.valueToString(singleList); + assertTrue("String values should be equal", "[\"entry1\"]".equals(output)); + + int[] intArray = new int[] { 1, 2, 3 }; + output = JSONObject.valueToString(intArray); + assertTrue("String values should be equal", "[1,2,3]".equals(output)); + + output = JSONObject.valueToString(24); + assertTrue("String values should be equal", "24".equals(output)); + + output = JSONObject.valueToString("string value"); + assertTrue("String values should be equal", "\"string value\"".equals(output)); + + output = JSONObject.valueToString(true); + assertTrue("String values should be equal", "true".equals(output)); + + } + + /** + * Test what happens when toJSONString() returns a well-formed JSON value. + * This is the usual case. + */ + @Test + public void testJSONStringValue() throws Exception { + JSONStringValue jsonString = new JSONStringValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(jsonString); + + StringWriter writer = new StringWriter(); + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"the JSON string value\"]".equals(output)); + + output = JSONObject.valueToString(jsonString); + assertTrue("String values should be equal", "\"the JSON string value\"".equals(output)); + } + + /** + * Test what happens when toJSONString() returns null. In one case, + * use the object's toString() method. In the other, throw a JSONException. + */ + @Test + public void testJSONNullStringValue() throws Exception { + JSONNullStringValue jsonString = new JSONNullStringValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(jsonString); + + StringWriter writer = new StringWriter(); + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"the toString value\"]".equals(output)); + + // The first different between writeValue() and valueToString(): + // in this case, valueToString throws a JSONException + try { + output = JSONObject.valueToString(jsonString); + fail("Expected an exception, got a String value"); + } catch (Exception e) { + assertTrue("Expected JSONException", e instanceof JSONException); + assertTrue("Exception message does not match", "Bad value from toJSONString: null".equals(e.getMessage())); + } + } + + /** + * Test what happens when toJSONString() returns an exception. In both + * cases, a JSONException is thrown, with the cause and message set from + * the original exception. + */ + @Test + public void testJSONStringExceptionValue() throws Exception { + JSONStringExceptionValue jsonString = new JSONStringExceptionValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(jsonString); + + StringWriter writer = new StringWriter(); + String output = null; + try { + output = jsonArray.write(writer).toString(); + fail("Expected an exception, got a String value"); + } catch (Exception e) { + assertTrue("Expected JSONException", e instanceof JSONException); + assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); + } + + try { + output = JSONObject.valueToString(jsonString); + fail("Expected an exception, got a String value"); + } catch (Exception e) { + assertTrue("Expected JSONException", e instanceof JSONException); + assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); + } + } + + /** + * Test what happens when a Java object's toString() returns a String value. + * This is the usual case. + */ + @Test + public void testStringValue() throws Exception { + StringValue nonJsonString = new StringValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(nonJsonString); + + StringWriter writer = new StringWriter(); + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"the toString value for StringValue\"]".equals(output)); + + output = JSONObject.valueToString(nonJsonString); + assertTrue("String values should be equal", "\"the toString value for StringValue\"".equals(output)); + } + + /** + * Test what happens when a Java object's toString() returns null. + * Defaults to empty string. + */ + @Test + public void testNullStringValue() throws Exception { + NullStringValue nonJsonString = new NullStringValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(nonJsonString); + + StringWriter writer = new StringWriter(); + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"\"]".equals(output)); + + output = JSONObject.valueToString(nonJsonString); + assertTrue("String values should be equal", "\"\"".equals(output)); + } + + /** + * A JSONString that returns a valid JSON string value. + */ + private static final class JSONStringValue implements JSONString { + + @Override + public String toJSONString() { + return "\"the JSON string value\""; + } + + @Override + public String toString() { + return "the toString value for JSONStringValue"; + } + } + + /** + * A JSONString that returns null when calling toJSONString(). + */ + private static final class JSONNullStringValue implements JSONString { + + @Override + public String toJSONString() { + return null; + } + + @Override + public String toString() { + return "the toString value"; + } + } + + /** + * A JSONString that throw an exception when calling toJSONString(). + */ + private static final class JSONStringExceptionValue implements JSONString { + + @Override + public String toJSONString() { + throw new IllegalStateException("the exception value"); + } + + @Override + public String toString() { + return "the toString value for JSONStringExceptionValue"; + } + } + + public static final class StringValue { + + @Override + public String toString() { + return "the toString value for StringValue"; + } + } + + public static final class NullStringValue { + + @Override + public String toString() { + return null; + } + } +} diff --git a/src/test/java/org/json/junit/JunitTestSuite.java b/src/test/java/org/json/junit/JunitTestSuite.java index 3863931..3a7223e 100644 --- a/src/test/java/org/json/junit/JunitTestSuite.java +++ b/src/test/java/org/json/junit/JunitTestSuite.java @@ -15,7 +15,8 @@ import org.junit.runners.Suite; JSONObjectTest.class, JSONArrayTest.class, EnumTest.class, - JSONPointerTest.class + JSONPointerTest.class, + JSONStringTest.class }) -public class JunitTestSuite { -} +public class JunitTestSuite { +} From 1246e12827fce05f70ce6758df647ea436d6578b Mon Sep 17 00:00:00 2001 From: Nicholas Cull Date: Sun, 24 Jul 2016 19:39:52 +1000 Subject: [PATCH 230/451] Factor out Writer from Appendable tests. --- .../java/org/json/junit/JSONArrayTest.java | 64 +++++++++++++++---- .../java/org/json/junit/JSONObjectTest.java | 61 ++++++++++++++---- 2 files changed, 102 insertions(+), 23 deletions(-) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 9f0e773..13dbb39 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -802,24 +802,36 @@ public class JSONArrayTest { @Test public void write() { String str = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":2,\"key3\":3}]"; - String expectedStr = str; JSONArray jsonArray = new JSONArray(str); + String expectedStr = str; StringWriter stringWriter = new StringWriter(); Writer writer = jsonArray.write(stringWriter); String actualStr = writer.toString(); assertTrue("write() expected " + expectedStr + - "but found " + actualStr, - expectedStr.equals(actualStr)); - StringBuilder stringBuilder = new StringBuilder(); - Appendable appendable = jsonArray.write(stringBuilder); - actualStr = appendable.toString(); - assertTrue("write() expected " + expectedStr + - "but found " + actualStr, + " but found " + actualStr, expectedStr.equals(actualStr)); } /** - * Exercise the JSONArray write(Appendable, int, int) method + * Exercise the JSONArray write() method using Appendable. + */ +/* + @Test + public void writeAppendable() { + String str = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":2,\"key3\":3}]"; + JSONArray jsonArray = new JSONArray(str); + String expectedStr = str; + StringBuilder stringBuilder = new StringBuilder(); + Appendable appendable = jsonArray.write(stringBuilder); + String actualStr = appendable.toString(); + assertTrue("write() expected " + expectedStr + + " but found " + actualStr, + expectedStr.equals(actualStr)); + } +*/ + + /** + * Exercise the JSONArray write(Writer, int, int) method */ @Test public void write3Param() { @@ -834,23 +846,51 @@ public class JSONArrayTest { " \"key3\": 3.14\n" + " }\n" + " ]"; - String expectedStr = str0; JSONArray jsonArray = new JSONArray(str0); + String expectedStr = str0; StringWriter stringWriter = new StringWriter(); Writer writer = jsonArray.write(stringWriter, 0, 0); String actualStr = writer.toString(); assertEquals(expectedStr, actualStr); - expectedStr = str0; + + expectedStr = str2; + stringWriter = new StringWriter(); + writer = jsonArray.write(stringWriter, 2, 1); + actualStr = writer.toString(); + assertEquals(expectedStr, actualStr); + } + + /** + * Exercise the JSONArray write(Appendable, int, int) method + */ +/* + @Test + public void write3ParamAppendable() { + String str0 = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":false,\"key3\":3.14}]"; + String str2 = + "[\n" + + " \"value1\",\n" + + " \"value2\",\n" + + " {\n" + + " \"key1\": 1,\n" + + " \"key2\": false,\n" + + " \"key3\": 3.14\n" + + " }\n" + + " ]"; + JSONArray jsonArray = new JSONArray(str0); + String expectedStr = str0; StringBuilder stringBuilder = new StringBuilder(); Appendable appendable = jsonArray.write(stringBuilder, 0, 0); - actualStr = appendable.toString(); + String actualStr = appendable.toString(); assertEquals(expectedStr, actualStr); + expectedStr = str2; stringBuilder = new StringBuilder(); appendable = jsonArray.write(stringBuilder, 2, 1); actualStr = appendable.toString(); assertEquals(expectedStr, actualStr); } +*/ /** * Exercise JSONArray toString() method with various indent levels. diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 10405b0..df1b141 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1916,18 +1916,30 @@ public class JSONObjectTest { Writer writer = jsonObject.write(stringWriter); String actualStr = writer.toString(); assertTrue("write() expected " +expectedStr+ - "but found " +actualStr, - expectedStr.equals(actualStr)); - StringBuilder stringBuilder = new StringBuilder(); - Appendable appendable = jsonObject.write(stringBuilder); - actualStr = appendable.toString(); - assertTrue("write() expected " +expectedStr+ - "but found " +actualStr, + " but found " +actualStr, expectedStr.equals(actualStr)); } /** - * Exercise the JSONObject write(Appendable, int, int) method + * Exercise the JSONObject write() method + */ +/* + @Test + public void writeAppendable() { + String str = "{\"key1\":\"value1\",\"key2\":[1,2,3]}"; + String expectedStr = str; + JSONObject jsonObject = new JSONObject(str); + StringBuilder stringBuilder = new StringBuilder(); + Appendable appendable = jsonObject.write(stringBuilder); + String actualStr = appendable.toString(); + assertTrue("write() expected " +expectedStr+ + " but found " +actualStr, + expectedStr.equals(actualStr)); + } +*/ + + /** + * Exercise the JSONObject write(Writer, int, int) method */ @Test public void write3Param() { @@ -1941,23 +1953,50 @@ public class JSONObjectTest { " 3.14\n" + " ]\n" + " }"; - String expectedStr = str0; JSONObject jsonObject = new JSONObject(str0); + String expectedStr = str0; StringWriter stringWriter = new StringWriter(); Writer writer = jsonObject.write(stringWriter,0,0); String actualStr = writer.toString(); assertEquals(expectedStr, actualStr); - expectedStr = str0; + + expectedStr = str2; + stringWriter = new StringWriter(); + writer = jsonObject.write(stringWriter,2,1); + actualStr = writer.toString(); + assertEquals(expectedStr, actualStr); + } + + /** + * Exercise the JSONObject write(Appendable, int, int) method + */ +/* + @Test + public void write3ParamAppendable() { + String str0 = "{\"key1\":\"value1\",\"key2\":[1,false,3.14]}"; + String str2 = + "{\n" + + " \"key1\": \"value1\",\n" + + " \"key2\": [\n" + + " 1,\n" + + " false,\n" + + " 3.14\n" + + " ]\n" + + " }"; + JSONObject jsonObject = new JSONObject(str0); + String expectedStr = str0; StringBuilder stringBuilder = new StringBuilder(); Appendable appendable = jsonObject.write(stringBuilder,0,0); - actualStr = appendable.toString(); + String actualStr = appendable.toString(); assertEquals(expectedStr, actualStr); + expectedStr = str2; stringBuilder = new StringBuilder(); appendable = jsonObject.write(stringBuilder,2,1); actualStr = appendable.toString(); assertEquals(expectedStr, actualStr); } +*/ /** * Exercise the JSONObject equals() method From efe33a1e370917ca571db5b95a0372b44a052afb Mon Sep 17 00:00:00 2001 From: Nicholas Cull Date: Sun, 24 Jul 2016 19:57:01 +1000 Subject: [PATCH 231/451] Fix comment. --- src/test/java/org/json/junit/JSONStringTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONStringTest.java b/src/test/java/org/json/junit/JSONStringTest.java index c7d9d3e..cba5d09 100644 --- a/src/test/java/org/json/junit/JSONStringTest.java +++ b/src/test/java/org/json/junit/JSONStringTest.java @@ -164,7 +164,7 @@ public class JSONStringTest { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[\"the toString value\"]".equals(output)); - // The first different between writeValue() and valueToString(): + // The only different between writeValue() and valueToString(): // in this case, valueToString throws a JSONException try { output = JSONObject.valueToString(jsonString); From e57881f8fa9d81ccda83e17d2379f3597b0af213 Mon Sep 17 00:00:00 2001 From: run2000 Date: Mon, 25 Jul 2016 09:44:43 +1000 Subject: [PATCH 232/451] Fail when exceptions are not thrown as expected The idiom was started in the first few methods, but not continued further down where JSONException was expected. False success may have resulted. --- src/test/java/org/json/junit/JSONStringerTest.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/test/java/org/json/junit/JSONStringerTest.java b/src/test/java/org/json/junit/JSONStringerTest.java index d4376df..99cdd6f 100644 --- a/src/test/java/org/json/junit/JSONStringerTest.java +++ b/src/test/java/org/json/junit/JSONStringerTest.java @@ -60,6 +60,7 @@ public class JSONStringerTest { jsonStringer.object().endObject(); try { jsonStringer.array(); + assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expected an exception message", "Misplaced array.". @@ -77,6 +78,7 @@ public class JSONStringerTest { jsonStringer.object(); try { jsonStringer.endArray(); + assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expected an exception message", "Misplaced endArray.". @@ -94,6 +96,7 @@ public class JSONStringerTest { jsonStringer.array(); try { jsonStringer.endObject(); + assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expected an exception message", "Misplaced endObject.". @@ -111,6 +114,7 @@ public class JSONStringerTest { jsonStringer.object().endObject(); try { jsonStringer.object(); + assertTrue("Expected an exception", false); } catch (JSONException e) { assertTrue("Expected an exception message", "Misplaced object.". From 0c157cae75fdd89914c53b56a8bb385144931452 Mon Sep 17 00:00:00 2001 From: Nicholas Cull Date: Mon, 8 Aug 2016 19:40:10 +1000 Subject: [PATCH 233/451] JSONWriter uses Appendable. --- JSONWriter.java | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/JSONWriter.java b/JSONWriter.java index 09d1130..696ee23 100644 --- a/JSONWriter.java +++ b/JSONWriter.java @@ -1,7 +1,6 @@ package org.json; import java.io.IOException; -import java.io.Writer; /* Copyright (c) 2006 JSON.org @@ -50,11 +49,11 @@ SOFTWARE. *

* The first method called must be array or object. * There are no methods for adding commas or colons. JSONWriter adds them for - * you. Objects and arrays can be nested up to 20 levels deep. + * you. Objects and arrays can be nested up to 200 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org - * @version 2015-12-09 + * @version 2016-08-08 */ public class JSONWriter { private static final int maxdepth = 200; @@ -88,12 +87,12 @@ public class JSONWriter { /** * The writer that will receive the output. */ - protected Writer writer; + protected Appendable writer; /** * Make a fresh JSONWriter. It can be used to build one JSON text. */ - public JSONWriter(Writer w) { + public JSONWriter(Appendable w) { this.comma = false; this.mode = 'i'; this.stack = new JSONObject[maxdepth]; @@ -114,9 +113,9 @@ public class JSONWriter { if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { - this.writer.write(','); + this.writer.append(','); } - this.writer.write(string); + this.writer.append(string); } catch (IOException e) { throw new JSONException(e); } @@ -163,7 +162,7 @@ public class JSONWriter { } this.pop(mode); try { - this.writer.write(c); + this.writer.append(c); } catch (IOException e) { throw new JSONException(e); } @@ -207,10 +206,10 @@ public class JSONWriter { try { this.stack[this.top - 1].putOnce(string, Boolean.TRUE); if (this.comma) { - this.writer.write(','); + this.writer.append(','); } - this.writer.write(JSONObject.quote(string)); - this.writer.write(':'); + this.writer.append(JSONObject.quote(string)); + this.writer.append(':'); this.comma = false; this.mode = 'o'; return this; From a2c311527b1961ec8cefc20d8219bc72728bb7ec Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 9 Aug 2016 15:54:06 -0400 Subject: [PATCH 234/451] Updates tests to include all opt methods and verify for missing keys. --- .../java/org/json/junit/JSONArrayTest.java | 5 +- .../java/org/json/junit/JSONObjectTest.java | 48 +++++++++++++++++-- 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index ef3a608..6e9fd6a 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -373,7 +373,10 @@ public class JSONArrayTest { assertTrue("Array opt value out of range", null == jsonArray.opt(-1)); - assertTrue("Array opt boolean", + assertTrue("Array opt value out of range", + null == jsonArray.opt(jsonArray.length())); + + assertTrue("Array opt boolean", Boolean.TRUE == jsonArray.optBoolean(0)); assertTrue("Array opt boolean default", Boolean.FALSE == jsonArray.optBoolean(-1, Boolean.FALSE)); diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 08ec964..61043ae 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1714,20 +1714,28 @@ public class JSONObjectTest { } /** - * Exercise JSONObject opt(key, default) method + * Exercise JSONObject opt(key, default) method. */ @Test public void jsonObjectOptDefault() { - String str = "{\"myKey\": \"myval\"}"; + String str = "{\"myKey\": \"myval\", \"hiKey\": null}"; JSONObject jsonObject = new JSONObject(str); + assertTrue("optBigDecimal() should return default ", + BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); + assertTrue(" should return default ", + BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); assertTrue("optBoolean() should return default boolean", - Boolean.TRUE == jsonObject.optBoolean("myKey", Boolean.TRUE)); - assertTrue("optInt() should return default int", - 42 == jsonObject.optInt("myKey", 42)); + true == jsonObject.optBoolean("myKey", true)); assertTrue("optInt() should return default int", 42 == jsonObject.optInt("myKey", 42)); + assertTrue("optEnum() should return default ", + MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); + assertTrue("optJSONArray() should return null ", + null==jsonObject.optJSONArray("myKey")); + assertTrue("optJSONObject() should return null ", + null==jsonObject.optJSONObject("myKey")); assertTrue("optLong() should return default long", 42 == jsonObject.optLong("myKey", 42)); assertTrue("optDouble() should return default double", @@ -1736,6 +1744,36 @@ public class JSONObjectTest { "hi".equals(jsonObject.optString("hiKey", "hi"))); } + /** + * Exercise JSONObject opt(key, default) method when the key doesn't exist. + */ + @Test + public void jsonObjectOptNoKey() { + + JSONObject jsonObject = new JSONObject(); + + assertTrue("optBigDecimal() should return default ", + BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); + assertTrue(" should return default ", + BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); + assertTrue("optBoolean() should return default boolean", + true == jsonObject.optBoolean("myKey", true)); + assertTrue("optInt() should return default int", + 42 == jsonObject.optInt("myKey", 42)); + assertTrue("optEnum() should return default ", + MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); + assertTrue("optJSONArray() should return null ", + null==jsonObject.optJSONArray("myKey")); + assertTrue("optJSONObject() should return null ", + null==jsonObject.optJSONObject("myKey")); + assertTrue("optLong() should return default long", + 42 == jsonObject.optLong("myKey", 42)); + assertTrue("optDouble() should return default double", + 42.3 == jsonObject.optDouble("myKey", 42.3)); + assertTrue("optString() should return default string", + "hi".equals(jsonObject.optString("hiKey", "hi"))); + } + /** * Verifies that the opt methods properly convert string values. */ From 80e36eb63c976079eda49cfc070fef5bdde89f0c Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 9 Aug 2016 15:59:27 -0400 Subject: [PATCH 235/451] Fixes error messages --- src/test/java/org/json/junit/JSONObjectTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 61043ae..935b687 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1722,15 +1722,15 @@ public class JSONObjectTest { String str = "{\"myKey\": \"myval\", \"hiKey\": null}"; JSONObject jsonObject = new JSONObject(str); - assertTrue("optBigDecimal() should return default ", + assertTrue("optBigDecimal() should return default BigDecimal", BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); - assertTrue(" should return default ", + assertTrue("optBigInteger() should return default BigInteger", BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); assertTrue("optBoolean() should return default boolean", true == jsonObject.optBoolean("myKey", true)); assertTrue("optInt() should return default int", 42 == jsonObject.optInt("myKey", 42)); - assertTrue("optEnum() should return default ", + assertTrue("optEnum() should return default Enum", MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); assertTrue("optJSONArray() should return null ", null==jsonObject.optJSONArray("myKey")); @@ -1752,15 +1752,15 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(); - assertTrue("optBigDecimal() should return default ", + assertTrue("optBigDecimal() should return default BigDecimal", BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); - assertTrue(" should return default ", + assertTrue("optBigInteger() should return default BigInteger", BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); assertTrue("optBoolean() should return default boolean", true == jsonObject.optBoolean("myKey", true)); assertTrue("optInt() should return default int", 42 == jsonObject.optInt("myKey", 42)); - assertTrue("optEnum() should return default ", + assertTrue("optEnum() should return default Enum", MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); assertTrue("optJSONArray() should return null ", null==jsonObject.optJSONArray("myKey")); From 8bae09f81bda5d12f1ea2d625097cdf1a113d84a Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 9 Aug 2016 16:11:46 -0400 Subject: [PATCH 236/451] removes unnecessary comparison to true --- src/test/java/org/json/junit/JSONObjectTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 935b687..d55f5df 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1727,7 +1727,7 @@ public class JSONObjectTest { assertTrue("optBigInteger() should return default BigInteger", BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); assertTrue("optBoolean() should return default boolean", - true == jsonObject.optBoolean("myKey", true)); + jsonObject.optBoolean("myKey", true)); assertTrue("optInt() should return default int", 42 == jsonObject.optInt("myKey", 42)); assertTrue("optEnum() should return default Enum", @@ -1757,7 +1757,7 @@ public class JSONObjectTest { assertTrue("optBigInteger() should return default BigInteger", BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); assertTrue("optBoolean() should return default boolean", - true == jsonObject.optBoolean("myKey", true)); + jsonObject.optBoolean("myKey", true)); assertTrue("optInt() should return default int", 42 == jsonObject.optInt("myKey", 42)); assertTrue("optEnum() should return default Enum", From f881b61c815aa22c5683a389a6da81b7277e9a6e Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Wed, 10 Aug 2016 15:35:26 -0500 Subject: [PATCH 237/451] Update XML.java Removed a problematic JavaDoc in the header comment to a deprecated method --- XML.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/XML.java b/XML.java index b76969a..0f0bee9 100644 --- a/XML.java +++ b/XML.java @@ -31,7 +31,7 @@ import java.util.Iterator; * covert a JSONObject into an XML text. * * @author JSON.org - * @version 2016-01-30 + * @version 2016-08-10 */ @SuppressWarnings("boxing") public class XML { @@ -300,7 +300,7 @@ public class XML { * This method has been deprecated in favor of the * {@link JSONObject.stringToValue(String)} method. Use it instead. * - * @deprecated Use {@link JSONObject#stringToValue(String)} instead. + * @deprecated Use JSONObject#stringToValue(String) instead. * @param string String to convert * @return JSON value of this string or the string */ From 5779400f26716c6c8dfc5b39fc9d4f9406f8da22 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 11 Aug 2016 12:21:49 -0400 Subject: [PATCH 238/451] test updates to make sure Enums are handled consistently. --- src/test/java/org/json/junit/EnumTest.java | 94 +++++++++++++------ src/test/java/org/json/junit/MyEnumField.java | 3 + 2 files changed, 70 insertions(+), 27 deletions(-) diff --git a/src/test/java/org/json/junit/EnumTest.java b/src/test/java/org/json/junit/EnumTest.java index ff4b294..ab4a1e5 100644 --- a/src/test/java/org/json/junit/EnumTest.java +++ b/src/test/java/org/json/junit/EnumTest.java @@ -1,13 +1,18 @@ package org.json.junit; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; -import java.util.*; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; -import org.json.*; -import org.junit.*; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Test; -import com.jayway.jsonpath.*; +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.JsonPath; /** * Enums are not explicitly supported in JSON-Java. But because enums act like @@ -50,11 +55,12 @@ public class EnumTest { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expecting 2 items in top level object", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expecting 2 items in myEnumField object", ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); - assertTrue("expecting 0 items in myEnum object", ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); - assertTrue("expecting 3", Integer.valueOf(3).equals(jsonObject.query("/myEnumField/intVal"))); - assertTrue("expecting val 3", "val 3".equals(jsonObject.query("/myEnumField/value"))); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected 2 myEnumField items", "VAL3".equals((JsonPath.read(doc, "$.myEnumField")))); + assertTrue("expected 0 myEnum items", "VAL1".equals((JsonPath.read(doc, "$.myEnum")))); + + assertTrue("expecting MyEnumField.VAL3", MyEnumField.VAL3.equals(jsonObject.query("/myEnumField"))); + assertTrue("expecting MyEnum.VAL1", MyEnum.VAL1.equals(jsonObject.query("/myEnum"))); } /** @@ -87,6 +93,45 @@ public class EnumTest { assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/VAL1"))); assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/VAL2"))); assertTrue("expected VAL3", myEnumField.VAL3.equals(jsonObject.query("/VAL3"))); + } + + /** + * Verify that enums are handled consistently between JSONArray and JSONObject + */ + @Test + public void verifyEnumConsistency(){ + JSONObject jo = new JSONObject(); + + jo.put("value", MyEnumField.VAL2); + String expected="{\"value\":\"VAL2\"}"; + String actual = jo.toString(); + assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + + jo.accumulate("value", MyEnumField.VAL1); + expected="{\"value\":[\"VAL2\",\"VAL1\"]}"; + actual = jo.toString(); + assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + + jo.remove("value"); + jo.append("value", MyEnumField.VAL1); + expected="{\"value\":[\"VAL1\"]}"; + actual = jo.toString(); + assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + + jo.put("value", EnumSet.of(MyEnumField.VAL2)); + expected="{\"value\":[\"VAL2\"]}"; + actual = jo.toString(); + assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + + JSONArray ja = new JSONArray(); + ja.put(MyEnumField.VAL2); + jo.put("value", ja); + actual = jo.toString(); + assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + + jo.put("value", new MyEnumField[]{MyEnumField.VAL2}); + actual = jo.toString(); + assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); } @@ -185,10 +230,8 @@ public class EnumTest { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected 2 myEnumField items", ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); - assertTrue("expected 0 myEnum items", ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/myEnumField/intVal"))); - assertTrue("expected val 3", "val 3".equals(jsonObject.query("/myEnumField/value"))); + assertTrue("expected VAL3", "VAL3".equals((JsonPath.read(doc, "$.myEnumField")))); + assertTrue("expected VAL1", "VAL1".equals((JsonPath.read(doc, "$.myEnum")))); String [] names = JSONObject.getNames(myEnum); jsonObject = new JSONObject(myEnum, names); @@ -233,23 +276,20 @@ public class EnumTest { } /** - * Wrap should handle enums exactly the same way as the JSONObject(Object) - * constructor. + * Wrap should handle enums exactly as a value type like Integer, Boolean, or String. */ @Test public void wrap() { - MyEnum myEnum = MyEnum.VAL2; - JSONObject jsonObject = (JSONObject)JSONObject.wrap(myEnum); - assertTrue("simple enum has no getters", jsonObject.length() == 0); + assertTrue("simple enum has no getters", JSONObject.wrap(MyEnum.VAL2) instanceof MyEnum); MyEnumField myEnumField = MyEnumField.VAL2; - jsonObject = (JSONObject)JSONObject.wrap(myEnumField); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("enum",myEnumField); // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected val 2", "val 2".equals(jsonObject.query("/value"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/intVal"))); + assertTrue("expected 1 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/enum"))); MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); @@ -259,11 +299,11 @@ public class EnumTest { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected 2 myEnumField items", ((Map)(JsonPath.read(doc, "$.myEnumField"))).size() == 2); - assertTrue("expected 0 myEnum items", ((Map)(JsonPath.read(doc, "$.myEnum"))).size() == 0); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/myEnumField/intVal"))); - assertTrue("expected val 3", "val 3".equals(jsonObject.query("/myEnumField/value"))); + assertTrue("expected VAL3", "VAL3".equals((JsonPath.read(doc, "$.myEnumField")))); + assertTrue("expected VAL1", "VAL1".equals((JsonPath.read(doc, "$.myEnum")))); + assertTrue("expecting MyEnumField.VAL3", MyEnumField.VAL3.equals(jsonObject.query("/myEnumField"))); + assertTrue("expecting MyEnum.VAL1", MyEnum.VAL1.equals(jsonObject.query("/myEnum"))); } /** diff --git a/src/test/java/org/json/junit/MyEnumField.java b/src/test/java/org/json/junit/MyEnumField.java index cff565a..8f2c633 100644 --- a/src/test/java/org/json/junit/MyEnumField.java +++ b/src/test/java/org/json/junit/MyEnumField.java @@ -20,4 +20,7 @@ public enum MyEnumField { public Integer getIntVal() { return intVal; } + public String toString(){ + return value; + } } From 91107e3e823c0e8ac5ae9ea8a018b3eb421792f0 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 11 Aug 2016 12:22:31 -0400 Subject: [PATCH 239/451] Adds support to JSONObject wrap and write methods to explicitly handle Enums. The new way enums are handled is to always place the actual enum in the JSONObject/JSONArray. When writing, we always write the actual "name" of the enum, so even with a toString override on the enum class, the value remains consistant and compatible with the optEnum/getEnum methods. The constructor JSONObject(Object) functions the same way as before when passing an enum and is consistent with other "value" types. For example, when creating a JSONObject with Long, Boolean, BigDecimal as the constructor parameter, the value will be treated as a "bean". --- JSONObject.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index aa227ff..de42faa 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1708,6 +1708,9 @@ public class JSONObject { if (value.getClass().isArray()) { return new JSONArray(value).toString(); } + if(value instanceof Enum){ + return quote(((Enum)value).name()); + } return quote(value.toString()); } @@ -1730,12 +1733,9 @@ public class JSONObject { } if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString - || object instanceof Byte || object instanceof Character - || object instanceof Short || object instanceof Integer - || object instanceof Long || object instanceof Boolean - || object instanceof Float || object instanceof Double - || object instanceof String || object instanceof BigInteger - || object instanceof BigDecimal) { + || object instanceof Number || object instanceof Character + || object instanceof Boolean || object instanceof String + || object instanceof Enum) { return object; } @@ -1797,6 +1797,8 @@ public class JSONObject { writer.write(numberToString((Number) value)); } else if (value instanceof Boolean) { writer.write(value.toString()); + } else if (value instanceof Enum) { + writer.write(quote(((Enum)value).name())); } else if (value instanceof JSONString) { Object o; try { From f96f505188e0161c4df78bc827bc05702f08024b Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 15 Aug 2016 01:53:08 -0500 Subject: [PATCH 240/451] Update JSONArray.java Fixed a Javadoc typo, originally fixed in #249, since reverted. This is to address issue #263 --- JSONArray.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 776a2bd..2446fd6 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -78,7 +78,7 @@ import java.util.Map; * * * @author JSON.org - * @version 2016-05-20 + * @version 2016-08/15 */ public class JSONArray implements Iterable { @@ -961,7 +961,7 @@ public class JSONArray implements Iterable { } /** - * Creates a JSONPointer using an intialization string and tries to + * Creates a JSONPointer using an initialization string and tries to * match it to an item within this JSONArray. For example, given a * JSONArray initialized with this document: *

From 7232a95c0bb3319edb20787430afe0fcd70d7c22 Mon Sep 17 00:00:00 2001
From: Sean Leary 
Date: Mon, 15 Aug 2016 01:58:54 -0500
Subject: [PATCH 241/451] Update JSONObject.java

Fixed some typos committed in #249, since reverted, tracking issue is #263
---
 JSONObject.java | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/JSONObject.java b/JSONObject.java
index aa227ff..ed86fab 100644
--- a/JSONObject.java
+++ b/JSONObject.java
@@ -93,7 +93,7 @@ import java.util.Set;
  * 
  *
  * @author JSON.org
- * @version 2016-05-20
+ * @version 2016-08-15
  */
 public class JSONObject {
     /**
@@ -132,6 +132,7 @@ public class JSONObject {
          *
          * @return The string "null".
          */
+        @Override
         public String toString() {
             return "null";
         }
@@ -1621,6 +1622,7 @@ public class JSONObject {
      *         brace) and ending with } (right
      *         brace).
      */
+    @Override
     public String toString() {
         try {
             return this.toString(0);
@@ -1880,13 +1882,13 @@ public class JSONObject {
     }
 
     /**
-     * Returns a java.util.Map containing all of the entrys in this object.
+     * Returns a java.util.Map containing all of the entries in this object.
      * If an entry in the object is a JSONArray or JSONObject it will also
      * be converted.
      * 

* Warning: This method assumes that the data structure is acyclical. * - * @return a java.util.Map containing the entrys of this object + * @return a java.util.Map containing the entries of this object */ public Map toMap() { Map results = new HashMap(); From 7851e9b2e8cd934e8b6071532664fb096ec65e20 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 15 Aug 2016 10:24:38 -0400 Subject: [PATCH 242/451] revert back changes to Number support --- JSONObject.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index de42faa..c722ea6 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1733,9 +1733,12 @@ public class JSONObject { } if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString - || object instanceof Number || object instanceof Character - || object instanceof Boolean || object instanceof String - || object instanceof Enum) { + || object instanceof Byte || object instanceof Character + || object instanceof Short || object instanceof Integer + || object instanceof Long || object instanceof Boolean + || object instanceof Float || object instanceof Double + || object instanceof String || object instanceof BigInteger + || object instanceof BigDecimal || object instanceof Enum) { return object; } From bbd3fd5571344d0330827e3f19ffdb3a17aed37d Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 16 Aug 2016 19:45:26 -0400 Subject: [PATCH 243/451] Adds tests for numbers --- src/test/java/org/json/junit/Fraction.java | 180 ++++++++++++++++++ .../java/org/json/junit/JSONObjectTest.java | 53 +++++- src/test/java/org/json/junit/MyNumber.java | 97 ++++++++++ .../org/json/junit/MyNumberContainer.java | 13 ++ 4 files changed, 341 insertions(+), 2 deletions(-) create mode 100644 src/test/java/org/json/junit/Fraction.java create mode 100644 src/test/java/org/json/junit/MyNumber.java create mode 100644 src/test/java/org/json/junit/MyNumberContainer.java diff --git a/src/test/java/org/json/junit/Fraction.java b/src/test/java/org/json/junit/Fraction.java new file mode 100644 index 0000000..d5d9eb6 --- /dev/null +++ b/src/test/java/org/json/junit/Fraction.java @@ -0,0 +1,180 @@ +package org.json.junit; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; + +/** + * basic fraction class, no frills. + * @author John Aylward + * + */ +public class Fraction extends Number implements Comparable { + /** + * serial id. + */ + private static final long serialVersionUID = 1L; + + /** + * value as a big decimal. + */ + private final BigDecimal bigDecimal; + + /** + * value of the denominator. + */ + private final BigInteger denominator; + /** + * value of the numerator. + */ + private final BigInteger numerator; + + /** + * @param numerator + * numerator + * @param denominator + * denominator + */ + public Fraction(final BigInteger numerator, final BigInteger denominator) { + super(); + if (numerator == null || denominator == null) { + throw new IllegalArgumentException("All values must be non-null"); + } + if (denominator.compareTo(BigInteger.ZERO)==0) { + throw new IllegalArgumentException("Divide by zero"); + } + + final BigInteger n; + final BigInteger d; + // normalize fraction + if (denominator.signum()<0) { + n = numerator.negate(); + d = denominator.negate(); + } else { + n = numerator; + d = denominator; + } + this.numerator = n; + this.denominator = d; + if (n.compareTo(BigInteger.ZERO)==0) { + this.bigDecimal = BigDecimal.ZERO; + } else if (n.compareTo(d)==0) {// i.e. 4/4, 10/10 + this.bigDecimal = BigDecimal.ONE; + } else { + this.bigDecimal = new BigDecimal(this.numerator).divide(new BigDecimal(this.denominator), + RoundingMode.HALF_EVEN); + } + } + + /** + * @param numerator + * numerator + * @param denominator + * denominator + */ + public Fraction(final long numerator, final long denominator) { + this(BigInteger.valueOf(numerator),BigInteger.valueOf(denominator)); + } + + /** + * @return the decimal + */ + public BigDecimal bigDecimalValue() { + return this.bigDecimal; + } + + @Override + public int compareTo(final Fraction o) { + // .equals call this, so no .equals compare allowed + + // if they are the same reference, just return equals + if (this == o) { + return 0; + } + + // if my denominators are already equal, just compare the numerators + if (this.denominator.compareTo(o.denominator)==0) { + return this.numerator.compareTo(o.numerator); + } + + // get numerators of common denominators + // a x ay xb + // --- --- = ---- ---- + // b y by yb + final BigInteger thisN = this.numerator.multiply(o.denominator); + final BigInteger otherN = o.numerator.multiply(this.denominator); + + return thisN.compareTo(otherN); + } + + @Override + public double doubleValue() { + return this.bigDecimal.doubleValue(); + } + + /** + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final Fraction other = (Fraction) obj; + return this.compareTo(other) == 0; + } + + @Override + public float floatValue() { + return this.bigDecimal.floatValue(); + } + + /** + * @return the denominator + */ + public BigInteger getDenominator() { + return this.denominator; + } + + /** + * @return the numerator + */ + public BigInteger getNumerator() { + return this.numerator; + } + + /** + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (this.bigDecimal == null ? 0 : this.bigDecimal.hashCode()); + return result; + } + + @Override + public int intValue() { + return this.bigDecimal.intValue(); + } + + @Override + public long longValue() { + return this.bigDecimal.longValue(); + } + + /** + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return this.numerator + "/" + this.denominator; + } +} diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index e353ae5..8c91b53 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1,9 +1,9 @@ package org.json.junit; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -20,6 +20,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; import org.json.CDL; import org.json.JSONArray; @@ -49,7 +50,7 @@ public class JSONObjectTest { MyBean myBean = null; new JSONObject(myBean); } - + /** * A JSONObject can be created with no content */ @@ -165,6 +166,54 @@ public class JSONObjectTest { expected.similar(jaObjObj)); } + /** + * Tests Number serialization. + */ + @Test + public void verifyNumberOutput(){ + JSONObject jsonObject = new JSONObject(new MyNumberContainer()); + String actual = jsonObject.toString(); + + // before wrapping of Number is allowed the number was converted as a bean + String expected = "{\"myNumber\":{\"number\":42}}"; + //String expected = "{\"myNumber\":42}"; + assertEquals("Not Equal", expected , actual); + + // put handles objects differently than the constructor. + jsonObject = new JSONObject(); + jsonObject.put("myNumber", new MyNumberContainer()); + actual = jsonObject.toString(); + // the output is the toString of the container. i.e org.json.junit.MyNumberContainer@4f063c0a + // the hex is the memory address which will change each run. + expected = "{\"myNumber\":\""+jsonObject.get("myNumber")+"\"}"; + assertEquals("Not Equal", expected , actual); + + jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); + actual = jsonObject.toString(); + // before wrapping of Number is allowed the number was converted to a string + expected = "{\"myNumber\":\"42\"}"; + assertEquals("Not Equal", expected , actual); + + // put handles objects differently than the constructor. + jsonObject = new JSONObject(); + jsonObject.put("myNumber", new AtomicInteger(42)); + actual = jsonObject.toString(); + expected = "{\"myNumber\":42}"; + assertEquals("Not Equal", expected , actual); + + // verify Fraction output + jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2))); + actual = jsonObject.toString(); + expected = "{\"myNumber\":{\"denominator\":2,\"numerator\":4}}"; + assertEquals("Not Equal", expected , actual); + + jsonObject = new JSONObject(); + jsonObject.put("myNumber", new Fraction(4,2)); + actual = jsonObject.toString(); + expected = "{\"myNumber\":4/2}"; // this is NOT valid JSON!!!!!!!!!!! BUG! + assertEquals("Not Equal", expected , actual); + } + /** * Verifies that the put Collection has backwards compatability with RAW types pre-java5. */ diff --git a/src/test/java/org/json/junit/MyNumber.java b/src/test/java/org/json/junit/MyNumber.java new file mode 100644 index 0000000..243a967 --- /dev/null +++ b/src/test/java/org/json/junit/MyNumber.java @@ -0,0 +1,97 @@ +package org.json.junit; + +import java.math.BigDecimal; + +/** + * Number override for testing. Number overrides should always override + * toString, hashCode, and Equals. + * + * @see The + * Numbers Classes + * @see Formatting + * Numeric Print Output + * + * @author John Aylward + */ +public class MyNumber extends Number { + private Number number = BigDecimal.valueOf(42); + /** + */ + private static final long serialVersionUID = 1L; + + /** + * @return number! + */ + public Number getNumber() { + return this.number; + } + + @Override + public int intValue() { + return getNumber().intValue(); + } + + @Override + public long longValue() { + return getNumber().longValue(); + } + + @Override + public float floatValue() { + return getNumber().floatValue(); + } + + @Override + public double doubleValue() { + return getNumber().doubleValue(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + * + * Number overrides should in general always override the toString method. + */ + @Override + public String toString() { + return getNumber().toString(); + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.number == null) ? 0 : this.number.hashCode()); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof MyNumber)) { + return false; + } + MyNumber other = (MyNumber) obj; + if (this.number == null) { + if (other.number != null) { + return false; + } + } else if (!this.number.equals(other.number)) { + return false; + } + return true; + } + +} diff --git a/src/test/java/org/json/junit/MyNumberContainer.java b/src/test/java/org/json/junit/MyNumberContainer.java new file mode 100644 index 0000000..524f318 --- /dev/null +++ b/src/test/java/org/json/junit/MyNumberContainer.java @@ -0,0 +1,13 @@ +package org.json.junit; + +/** + * Class that holds our MyNumber override as a property. + * @author John Aylward + */ +public class MyNumberContainer { + private MyNumber myNumber = new MyNumber(); + /** + * @return a MyNumber. + */ + public Number getMyNumber() {return this.myNumber;} +} From cbd041870432b74c3deb9b4af90c02d6b6358105 Mon Sep 17 00:00:00 2001 From: johnjaylward Date: Tue, 16 Aug 2016 21:33:54 -0400 Subject: [PATCH 244/451] Update JSONObjectTest.java fixes test to be applicable --- src/test/java/org/json/junit/JSONObjectTest.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 8c91b53..39e6ae5 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -181,11 +181,10 @@ public class JSONObjectTest { // put handles objects differently than the constructor. jsonObject = new JSONObject(); - jsonObject.put("myNumber", new MyNumberContainer()); + jsonObject.put("myNumber", new MyNumber()); actual = jsonObject.toString(); - // the output is the toString of the container. i.e org.json.junit.MyNumberContainer@4f063c0a - // the hex is the memory address which will change each run. - expected = "{\"myNumber\":\""+jsonObject.get("myNumber")+"\"}"; + // the output is the toString of the number as a string. + expected = "{\"myNumber\":\"42\"}"; assertEquals("Not Equal", expected , actual); jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); From a66b97f60bbae42133f472d77840e55f76ef3722 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 17 Aug 2016 11:31:12 -0400 Subject: [PATCH 245/451] fix test --- src/test/java/org/json/junit/JSONObjectTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 39e6ae5..55f7446 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -183,8 +183,8 @@ public class JSONObjectTest { jsonObject = new JSONObject(); jsonObject.put("myNumber", new MyNumber()); actual = jsonObject.toString(); - // the output is the toString of the number as a string. - expected = "{\"myNumber\":\"42\"}"; + // the output is the toString of the number as a number. + expected = "{\"myNumber\":42}"; assertEquals("Not Equal", expected , actual); jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); From 0b1dbe9369f22737cd91bec7f8905f909f71f1a3 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 17 Aug 2016 12:13:54 -0400 Subject: [PATCH 246/451] fixes test to not depend on key order --- src/test/java/org/json/junit/JSONObjectTest.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 55f7446..9a1d7b7 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -202,10 +202,9 @@ public class JSONObjectTest { // verify Fraction output jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2))); - actual = jsonObject.toString(); - expected = "{\"myNumber\":{\"denominator\":2,\"numerator\":4}}"; - assertEquals("Not Equal", expected , actual); - + assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject.query("/myNumber/numerator")); + assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject.query("/myNumber/denominator")); + jsonObject = new JSONObject(); jsonObject.put("myNumber", new Fraction(4,2)); actual = jsonObject.toString(); From 2f2cd4dfc5f3dfcee30e5d8fae54ff2954e7b107 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 17 Aug 2016 12:52:04 -0400 Subject: [PATCH 247/451] Fix for number output bug. java.lang.Number is currently output without any validation. For all java.* Numbers, this is fine, but for custom Number implementations like Complex or Fraction, the resulting JSON output may be invalid. For example: If a Fraction implementation defines its' toString method as `return numerator + "/" + denominator`, then the resulting JSON output would be something like this: ```json { "fraction" : 1/2 } ``` This is not valid JSON. This commit verifies that the string representation of the number is close to a JSON formatted number by use of the BigDecimal constructor. If the constructor throws a NumberFormatException, then the string value is instead quoted as a string. The example above would instead output like the following: ```json { "fraction" : "1/2" } ``` --- JSONObject.java | 51 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index ed86fab..15e74b8 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -838,7 +838,7 @@ public class JSONObject { } testValidity(number); -// Shave off trailing zeros and decimal point, if possible. + // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 @@ -1693,7 +1693,18 @@ public class JSONObject { throw new JSONException("Bad value from toJSONString: " + object); } if (value instanceof Number) { - return numberToString((Number) value); + // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex + final String numberAsString = numberToString((Number) value); + try { + // Use the BigDecimal constructor for it's parser to validate the format. + new BigDecimal(numberAsString); + // Close enough to a JSON number that we will return it unquoted + return numberAsString; + } catch (NumberFormatException ex){ + // The Number value is not a valid JSON number. + // Instead we will quote it as a string + return quote(numberAsString); + } } if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { @@ -1783,6 +1794,30 @@ public class JSONObject { int indentFactor, int indent) throws JSONException, IOException { if (value == null || value.equals(null)) { writer.write("null"); + } else if (value instanceof JSONString) { + Object o; + try { + o = ((JSONString) value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + writer.write(o != null ? o.toString() : quote(value.toString())); + } else if (value instanceof Number) { + // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary + final String numberAsString = numberToString((Number) value); + try { + // Use the BigDecimal constructor for it's parser to validate the format. + @SuppressWarnings("unused") + BigDecimal testNum = new BigDecimal(numberAsString); + // Close enough to a JSON number that we will use it unquoted + writer.write(numberAsString); + } catch (NumberFormatException ex){ + // The Number value is not a valid JSON number. + // Instead we will quote it as a string + quote(numberAsString, writer); + } + } else if (value instanceof Boolean) { + writer.write(value.toString()); } else if (value instanceof JSONObject) { ((JSONObject) value).write(writer, indentFactor, indent); } else if (value instanceof JSONArray) { @@ -1795,18 +1830,6 @@ public class JSONObject { new JSONArray(coll).write(writer, indentFactor, indent); } else if (value.getClass().isArray()) { new JSONArray(value).write(writer, indentFactor, indent); - } else if (value instanceof Number) { - writer.write(numberToString((Number) value)); - } else if (value instanceof Boolean) { - writer.write(value.toString()); - } else if (value instanceof JSONString) { - Object o; - try { - o = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - writer.write(o != null ? o.toString() : quote(value.toString())); } else { quote(value.toString(), writer); } From 58aebaa14fa58c920576db0560dce1c7a880f5dc Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 15 Sep 2016 21:31:28 -0500 Subject: [PATCH 248/451] fixed merge issues --- .../java/org/json/junit/JSONObjectTest.java | 81 ++++++++++++++----- 1 file changed, 61 insertions(+), 20 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 9a1d7b7..1b50e7a 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -171,44 +171,85 @@ public class JSONObjectTest { */ @Test public void verifyNumberOutput(){ + /** + * MyNumberContainer is a POJO, so call JSONObject(bean), + * which builds a map of getter names/values + * The only getter is getMyNumber (key=myNumber), + * whose return value is MyNumber. MyNumber extends Number, + * but is not recognized as such by wrap() per current + * implementation, so wrap() returns the default new JSONObject(bean). + * The only getter is getNumber (key=number), whose return value is + * BigDecimal(42). + */ JSONObject jsonObject = new JSONObject(new MyNumberContainer()); String actual = jsonObject.toString(); - - // before wrapping of Number is allowed the number was converted as a bean String expected = "{\"myNumber\":{\"number\":42}}"; - //String expected = "{\"myNumber\":42}"; assertEquals("Not Equal", expected , actual); - // put handles objects differently than the constructor. + /** + * JSONObject.put() handles objects differently than the + * bean constructor. Where the bean ctor wraps objects before + * placing them in the map, put() inserts the object without wrapping. + * In this case, a MyNumber instance is the value. + * The MyNumber.toString() method is responsible for + * returning a reasonable value: the string '42'. + */ jsonObject = new JSONObject(); jsonObject.put("myNumber", new MyNumber()); actual = jsonObject.toString(); - // the output is the toString of the number as a number. expected = "{\"myNumber\":42}"; assertEquals("Not Equal", expected , actual); - + + /** + * Calls the JSONObject(Map) ctor, which calls wrap() for values. + * AtomicInteger is a Number, but is not recognized by wrap(), per + * current implementation. However, the type is + * 'java.util.concurrent.atomic', so due to the 'java' prefix, + * wrap() inserts the value as a string. That is why 42 comes back + * wrapped in quotes. + */ jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); actual = jsonObject.toString(); - // before wrapping of Number is allowed the number was converted to a string expected = "{\"myNumber\":\"42\"}"; assertEquals("Not Equal", expected , actual); - - // put handles objects differently than the constructor. + + /** + * JSONObject.put() inserts the AtomicInteger directly into the + * map not calling wrap(). In toString()->write()->writeValue(), + * AtomicInteger is recognized as a Number, and converted via + * numberToString() into the unquoted string '42'. + */ jsonObject = new JSONObject(); jsonObject.put("myNumber", new AtomicInteger(42)); actual = jsonObject.toString(); expected = "{\"myNumber\":42}"; assertEquals("Not Equal", expected , actual); - - // verify Fraction output + + /** + * Calls the JSONObject(Map) ctor, which calls wrap() for values. + * Fraction is a Number, but is not recognized by wrap(), per + * current implementation. As a POJO, Franction is handled as a + * bean and inserted into a contained JSONObject. It has 2 getters, + * for numerator and denominator. + */ jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2))); + assertEquals(1, jsonObject.length()); + assertEquals(2, ((JSONObject)(jsonObject.get("myNumber"))).length()); assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject.query("/myNumber/numerator")); assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject.query("/myNumber/denominator")); + /** + * JSONObject.put() inserts the Fraction directly into the + * map not calling wrap(). In toString()->write()->writeValue(), + * Fraction is recognized as a Number, and converted via + * numberToString() into the unquoted string '4/2'. But the + * BigDecimal sanity check fails, so writeValue() defaults + * to returning a safe JSON quoted string. Pretty slick! + */ jsonObject = new JSONObject(); jsonObject.put("myNumber", new Fraction(4,2)); actual = jsonObject.toString(); - expected = "{\"myNumber\":4/2}"; // this is NOT valid JSON!!!!!!!!!!! BUG! + expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed assertEquals("Not Equal", expected , actual); } @@ -2224,44 +2265,44 @@ public class JSONObjectTest { "}"; JSONObject jsonObject = new JSONObject(jsonObjectStr); - Map map = jsonObject.toMap(); + Map map = jsonObject.toMap(); assertTrue("Map should not be null", map != null); assertTrue("Map should have 3 elements", map.size() == 3); - List key1List = (List)map.get("key1"); + List key1List = (List)map.get("key1"); assertTrue("key1 should not be null", key1List != null); assertTrue("key1 list should have 3 elements", key1List.size() == 3); assertTrue("key1 value 1 should be 1", key1List.get(0).equals(Integer.valueOf(1))); assertTrue("key1 value 2 should be 2", key1List.get(1).equals(Integer.valueOf(2))); - Map key1Value3Map = (Map)key1List.get(2); + Map key1Value3Map = (Map)key1List.get(2); assertTrue("Map should not be null", key1Value3Map != null); assertTrue("Map should have 1 element", key1Value3Map.size() == 1); assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); - Map key2Map = (Map)map.get("key2"); + Map key2Map = (Map)map.get("key2"); assertTrue("key2 should not be null", key2Map != null); assertTrue("key2 map should have 3 elements", key2Map.size() == 3); assertTrue("key2 map key 1 should be val1", key2Map.get("key1").equals("val1")); assertTrue("key2 map key 3 should be 42", key2Map.get("key3").equals(Integer.valueOf(42))); - Map key2Val2Map = (Map)key2Map.get("key2"); + Map key2Val2Map = (Map)key2Map.get("key2"); assertTrue("key2 map key 2 should not be null", key2Val2Map != null); assertTrue("key2 map key 2 should have an entry", key2Val2Map.containsKey("key2")); assertTrue("key2 map key 2 value should be null", key2Val2Map.get("key2") == null); - List key3List = (List)map.get("key3"); + List key3List = (List)map.get("key3"); assertTrue("key3 should not be null", key3List != null); assertTrue("key3 list should have 3 elements", key3List.size() == 2); - List key3Val1List = (List)key3List.get(0); + List key3Val1List = (List)key3List.get(0); assertTrue("key3 list val 1 should not be null", key3Val1List != null); assertTrue("key3 list val 1 should have 2 elements", key3Val1List.size() == 2); assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); assertTrue("key3 list val 1 list element 2 should be 2.1", key3Val1List.get(1).equals(Double.valueOf("2.1"))); - List key3Val2List = (List)key3List.get(1); + List key3Val2List = (List)key3List.get(1); assertTrue("key3 list val 2 should not be null", key3Val2List != null); assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1); assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null); From a2d3b59394d62074debc4903e46c3aa97179172e Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 12:38:06 -0400 Subject: [PATCH 249/451] Implements unicode escaping similar to JSONObject. * Removes deprecation on XML.stringToValue(). It now provides unescaping for strings to convert XML entities back into values. * New unescape function to handle XML entities -> value conversion. --- JSONML.java | 4 +-- XML.java | 80 +++++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 73 insertions(+), 11 deletions(-) diff --git a/JSONML.java b/JSONML.java index 7e99aab..9f861eb 100644 --- a/JSONML.java +++ b/JSONML.java @@ -175,7 +175,7 @@ public class JSONML { if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } - newjo.accumulate(attribute, keepStrings ? token :JSONObject.stringToValue((String)token)); + newjo.accumulate(attribute, keepStrings ? token :XML.stringToValue((String)token)); token = null; } else { newjo.accumulate(attribute, ""); @@ -226,7 +226,7 @@ public class JSONML { } else { if (ja != null) { ja.put(token instanceof String - ? keepStrings ? token :JSONObject.stringToValue((String)token) + ? keepStrings ? token :XML.stringToValue((String)token) : token); } } diff --git a/XML.java b/XML.java index 0f0bee9..833488a 100644 --- a/XML.java +++ b/XML.java @@ -35,7 +35,6 @@ import java.util.Iterator; */ @SuppressWarnings("boxing") public class XML { - /** The Character '&'. */ public static final Character AMP = '&'; @@ -71,6 +70,7 @@ public class XML { * < (less than) is replaced by &lt; * > (greater than) is replaced by &gt; * " (double quote) is replaced by &quot; + * ' (single quote / apostrophe) is replaced by &apos; *

* * @param string @@ -98,6 +98,67 @@ public class XML { sb.append("'"); break; default: + if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { + sb.append("&#x"); + sb.append(Integer.toHexString(c)); + sb.append(";"); + } else { + sb.append(c); + } + } + } + return sb.toString(); + } + + /** + * Removes XML escapes from the string. + * + * @param string + * string to remove escapes from + * @return string with converted entities + */ + public static String unescape(String string) { + StringBuilder sb = new StringBuilder(string.length()); + for (int i = 0, length = string.length(); i < length; i++) { + char c = string.charAt(i); + if (c == AMP) { + final int semic = string.indexOf(';', i); + if (semic > i) { + final String entity = string.substring(i + 1, semic); + if (entity.charAt(0) == '#') { + char cc; + if (entity.charAt(1) == 'x') { + // hex encoded unicode + cc = (char) Integer.parseInt(entity.substring(2), 16); + } else { + // decimal encoded unicode + cc = (char) Integer.parseInt(entity.substring(1)); + } + sb.append(cc); + } else { + if ("quot".equalsIgnoreCase(entity)) { + sb.append('"'); + } else if ("amp".equalsIgnoreCase(entity)) { + sb.append(AMP); + } else if ("apos".equalsIgnoreCase(entity)) { + sb.append('\''); + } else if ("lt".equalsIgnoreCase(entity)) { + sb.append('<'); + } else if ("gt".equalsIgnoreCase(entity)) { + sb.append('>'); + } else { + sb.append(AMP).append(entity).append(';'); + } + } + // skip past the entity we just parsed. + i += entity.length() + 1; + } else { + // this shouldn't happen in most cases since the parser + // errors on unclosed enties. + sb.append(c); + } + } else { + // not part of an entity sb.append(c); } } @@ -227,7 +288,6 @@ public class XML { if (token == null) { token = x.nextToken(); } - // attribute = value if (token instanceof String) { string = (String) token; @@ -238,7 +298,7 @@ public class XML { throw x.syntaxError("Missing value"); } jsonobject.accumulate(string, - keepStrings ? token : JSONObject.stringToValue((String) token)); + keepStrings ? unescape((String)token) : stringToValue((String) token)); token = null; } else { jsonobject.accumulate(string, ""); @@ -270,7 +330,7 @@ public class XML { string = (String) token; if (string.length() > 0) { jsonobject.accumulate("content", - keepStrings ? token : JSONObject.stringToValue(string)); + keepStrings ? unescape(string) : stringToValue(string)); } } else if (token == LT) { @@ -297,16 +357,18 @@ public class XML { } /** - * This method has been deprecated in favor of the - * {@link JSONObject.stringToValue(String)} method. Use it instead. + * This method is the same as {@link JSONObject.stringToValue(String)} + * except that this also tries to unescape String values. * - * @deprecated Use JSONObject#stringToValue(String) instead. * @param string String to convert * @return JSON value of this string or the string */ - @Deprecated public static Object stringToValue(String string) { - return JSONObject.stringToValue(string); + Object ret = JSONObject.stringToValue(string); + if(ret instanceof String){ + return unescape((String)ret); + } + return ret; } /** From c8563ff93daee506201b075faf203f726319afd7 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 12:38:30 -0400 Subject: [PATCH 250/451] new test case for XML changes --- src/test/java/org/json/junit/XMLTest.java | 31 ++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 2f3fea7..11c05d4 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -267,6 +267,35 @@ public class XMLTest { compareFileToJSONObject(xmlStr, expectedStr); } + /** + * Tests to verify that supported escapes in XML are converted to actual values. + */ + @Test + public void testXmlEscapeToJson(){ + String xmlStr = + "\n"+ + ""+ + "\""+ + "A €33"+ + "A €22€"+ + "some text ©"+ + "" " & ' < >"+ + ""; + String expectedStr = + "{\"root\":{" + + "\"rawQuote\":\"\\\"\"," + + "\"euro\":\"A €33\"," + + "\"euroX\":\"A €22€\"," + + "\"unknown\":\"some text ©\"," + + "\"known\":\"\\\" \\\" & ' < >\"" + + "}}"; + + compareStringToJSONObject(xmlStr, expectedStr); + compareReaderToJSONObject(xmlStr, expectedStr); + compareFileToJSONObject(xmlStr, expectedStr); + + } + /** * Valid XML with comments to JSONObject */ @@ -675,8 +704,8 @@ public class XMLTest { * @param expectedStr the expected JSON string */ private void compareStringToJSONObject(String xmlStr, String expectedStr) { - JSONObject expectedJsonObject = new JSONObject(expectedStr); JSONObject jsonObject = XML.toJSONObject(xmlStr); + JSONObject expectedJsonObject = new JSONObject(expectedStr); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } From 5027a283c1b9c1bc81663441f0a0b23de48115cc Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 13:09:32 -0400 Subject: [PATCH 251/451] Adds test for escaping from a JSONObject to XML --- src/test/java/org/json/junit/XMLTest.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 11c05d4..800dc93 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -1,6 +1,7 @@ package org.json.junit; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; @@ -293,7 +294,19 @@ public class XMLTest { compareStringToJSONObject(xmlStr, expectedStr); compareReaderToJSONObject(xmlStr, expectedStr); compareFileToJSONObject(xmlStr, expectedStr); - + } + + /** + * Tests that certain unicode characters are escaped. + */ + @Test + public void testJsonToXmlEscape(){ + JSONObject json = new JSONObject("{ \"amount\": \"10,00 €\", \"description\": \"Ação Válida\" }"); + String xml = XML.toString(json); + assertFalse("Escaping € failed. Found in XML output.", xml.contains("€")); + assertTrue("Escaping ç failed. Not found in XML output.", xml.contains("ç")); + assertTrue("Escaping ã failed. Not found in XML output.", xml.contains("ã")); + assertTrue("Escaping á failed. Not found in XML output.", xml.contains("á")); } /** From 34652a87061f2e71321d1175724c162a62b00239 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 14:13:14 -0400 Subject: [PATCH 252/451] Updates to iterate on code points instead of characters and changes the encoding to only encode control characters as defined by ISO standard. --- XML.java | 45 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/XML.java b/XML.java index 833488a..025c3be 100644 --- a/XML.java +++ b/XML.java @@ -61,6 +61,42 @@ public class XML { /** The Character '/'. */ public static final Character SLASH = '/'; + + /** + * Creates an iterator for navigating Code Points in a string instead of + * characters. + * + * @see http://stackoverflow.com/a/21791059/6030888 + */ + private static Iterable codePointIterator(final String string) { + return new Iterable() { + @Override + public Iterator iterator() { + return new Iterator() { + private int nextIndex = 0; + private int length = string.length(); + + @Override + public boolean hasNext() { + return this.nextIndex < this.length; + } + + @Override + public Integer next() { + int result = string.codePointAt(this.nextIndex); + this.nextIndex += Character.charCount(result); + return result; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + }; + } /** * Replace special characters with XML escapes: @@ -79,8 +115,7 @@ public class XML { */ public static String escape(String string) { StringBuilder sb = new StringBuilder(string.length()); - for (int i = 0, length = string.length(); i < length; i++) { - char c = string.charAt(i); + for (final int c : codePointIterator(string)) { switch (c) { case '&': sb.append("&"); @@ -98,18 +133,18 @@ public class XML { sb.append("'"); break; default: - if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { + if (Character.isISOControl(c)) { sb.append("&#x"); sb.append(Integer.toHexString(c)); sb.append(";"); } else { - sb.append(c); + sb.append(new String(Character.toChars(c))); } } } return sb.toString(); } - + /** * Removes XML escapes from the string. * From 2b87f334d0343774a77b1779011eaba250a2a0c9 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 14:13:48 -0400 Subject: [PATCH 253/451] Update test cases to support ISO Control encoding changes. --- src/test/java/org/json/junit/XMLTest.java | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 800dc93..91ee420 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -297,16 +297,30 @@ public class XMLTest { } /** - * Tests that certain unicode characters are escaped. + * Tests that control characters are escaped. */ @Test public void testJsonToXmlEscape(){ - JSONObject json = new JSONObject("{ \"amount\": \"10,00 €\", \"description\": \"Ação Válida\" }"); + final String jsonSrc = "{\"amount\":\"10,00 €\"," + + "\"description\":\"Ação Válida\u0085\"," + + "\"xmlEntities\":\"\\\" ' & < >\"" + + "}"; + JSONObject json = new JSONObject(jsonSrc); String xml = XML.toString(json); - assertFalse("Escaping € failed. Found in XML output.", xml.contains("€")); + //test control character not existing + assertFalse("Escaping \u0085 failed. Found in XML output.", xml.contains("\u0085")); + assertTrue("Escaping \u0085 failed. Entity not found in XML output.", xml.contains("…")); + // test normal unicode existing + assertTrue("Escaping € failed. Not found in XML output.", xml.contains("€")); assertTrue("Escaping ç failed. Not found in XML output.", xml.contains("ç")); assertTrue("Escaping ã failed. Not found in XML output.", xml.contains("ã")); assertTrue("Escaping á failed. Not found in XML output.", xml.contains("á")); + // test XML Entities converted + assertTrue("Escaping \" failed. Not found in XML output.", xml.contains(""")); + assertTrue("Escaping ' failed. Not found in XML output.", xml.contains("'")); + assertTrue("Escaping & failed. Not found in XML output.", xml.contains("&")); + assertTrue("Escaping < failed. Not found in XML output.", xml.contains("<")); + assertTrue("Escaping > failed. Not found in XML output.", xml.contains(">")); } /** From 68f92eb39568b0d1f736dfa878a36e32137a8a69 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 14:40:39 -0400 Subject: [PATCH 254/451] Adds more javadoc. --- XML.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/XML.java b/XML.java index 025c3be..8e63c74 100644 --- a/XML.java +++ b/XML.java @@ -64,7 +64,11 @@ public class XML { /** * Creates an iterator for navigating Code Points in a string instead of - * characters. + * characters. Once Java7 support is dropped, this can be replaced with + * + * string.codePoints() + * + * which is available in Java8 and above. * * @see http://stackoverflow.com/a/21791059/6030888 From c11e09959c546740963c0b8627f815b9f29c941e Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 15:40:26 -0400 Subject: [PATCH 255/451] Fixes code point output when unescaping code points. XML escapes are an entire code point, not surrogate pairs like in JSON. --- XML.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/XML.java b/XML.java index 8e63c74..890b2de 100644 --- a/XML.java +++ b/XML.java @@ -165,15 +165,15 @@ public class XML { if (semic > i) { final String entity = string.substring(i + 1, semic); if (entity.charAt(0) == '#') { - char cc; + int cp; if (entity.charAt(1) == 'x') { // hex encoded unicode - cc = (char) Integer.parseInt(entity.substring(2), 16); + cp = Integer.parseInt(entity.substring(2), 16); } else { // decimal encoded unicode - cc = (char) Integer.parseInt(entity.substring(1)); + cp = Integer.parseInt(entity.substring(1)); } - sb.append(cc); + sb.append(new String(Character.toChars(cp))); } else { if ("quot".equalsIgnoreCase(entity)) { sb.append('"'); From f58a0f468475b0277a123dbe44fedbefbdb993c9 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 16:10:49 -0400 Subject: [PATCH 256/451] fixes code point appends to string builder --- XML.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/XML.java b/XML.java index 890b2de..a740b0e 100644 --- a/XML.java +++ b/XML.java @@ -119,8 +119,8 @@ public class XML { */ public static String escape(String string) { StringBuilder sb = new StringBuilder(string.length()); - for (final int c : codePointIterator(string)) { - switch (c) { + for (final int cp : codePointIterator(string)) { + switch (cp) { case '&': sb.append("&"); break; @@ -137,12 +137,12 @@ public class XML { sb.append("'"); break; default: - if (Character.isISOControl(c)) { + if (Character.isISOControl(cp)) { sb.append("&#x"); - sb.append(Integer.toHexString(c)); + sb.append(Integer.toHexString(cp)); sb.append(";"); } else { - sb.append(new String(Character.toChars(c))); + sb.appendCodePoint(cp); } } } @@ -173,7 +173,7 @@ public class XML { // decimal encoded unicode cp = Integer.parseInt(entity.substring(1)); } - sb.append(new String(Character.toChars(cp))); + sb.appendCodePoint(cp); } else { if ("quot".equalsIgnoreCase(entity)) { sb.append('"'); From f6a00e94c77e3b1ca6c74308696600502751efa4 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 16:12:00 -0400 Subject: [PATCH 257/451] adds test for unicode that has surrogate pairs --- src/test/java/org/json/junit/XMLTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 91ee420..264fa44 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -281,6 +281,7 @@ public class XMLTest { "A €22€"+ "some text ©"+ "" " & ' < >"+ + "𝄢 𐅥" + ""; String expectedStr = "{\"root\":{" + @@ -288,7 +289,8 @@ public class XMLTest { "\"euro\":\"A €33\"," + "\"euroX\":\"A €22€\"," + "\"unknown\":\"some text ©\"," + - "\"known\":\"\\\" \\\" & ' < >\"" + + "\"known\":\"\\\" \\\" & ' < >\"," + + "\"high\":\"𝄢 𐅥\""+ "}}"; compareStringToJSONObject(xmlStr, expectedStr); From adb0478f66042bb35fcaad020fc76f7e1a5b6acd Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 22 Sep 2016 16:23:09 -0400 Subject: [PATCH 258/451] properly unescape tokens in JSONML for reversability. --- JSONML.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JSONML.java b/JSONML.java index 9f861eb..82853a9 100644 --- a/JSONML.java +++ b/JSONML.java @@ -175,7 +175,7 @@ public class JSONML { if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } - newjo.accumulate(attribute, keepStrings ? token :XML.stringToValue((String)token)); + newjo.accumulate(attribute, keepStrings ? XML.unescape((String)token) :XML.stringToValue((String)token)); token = null; } else { newjo.accumulate(attribute, ""); @@ -226,7 +226,7 @@ public class JSONML { } else { if (ja != null) { ja.put(token instanceof String - ? keepStrings ? token :XML.stringToValue((String)token) + ? keepStrings ? XML.unescape((String)token) :XML.stringToValue((String)token) : token); } } From fb1db9341ecd4173503f65e0d6309c1e1aca0a5e Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 28 Sep 2016 20:15:58 -0400 Subject: [PATCH 259/451] Changes encoding to better match the XML spec section 2.2 --- XML.java | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/XML.java b/XML.java index a740b0e..4ceec5e 100644 --- a/XML.java +++ b/XML.java @@ -137,7 +137,7 @@ public class XML { sb.append("'"); break; default: - if (Character.isISOControl(cp)) { + if (mustEscape(cp)) { sb.append("&#x"); sb.append(Integer.toHexString(cp)); sb.append(";"); @@ -149,6 +149,32 @@ public class XML { return sb.toString(); } + /** + * @param cp code point to test + * @return true if the code point is not valid for an XML + */ + private static boolean mustEscape(int cp) { + /* Valid range from https://www.w3.org/TR/REC-xml/#charsets + * + * #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] + * + * any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. + */ + // isISOControl is true when (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F) + // all ISO control characters are out of range except tabs and new lines + return (Character.isISOControl(cp) + && cp != 0x9 + && cp != 0xA + && cp != 0xD + ) || !( + // valid the range of acceptable characters that aren't control + (cp >= 0x20 && cp <= 0xD7FF) + || (cp >= 0xE000 && cp <= 0xFFFD) + || (cp >= 0x10000 && cp <= 0x10FFFF) + ) + ; + } + /** * Removes XML escapes from the string. * From e477d7002b71afdf997a2d4e19a0814ca75cb0c0 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 28 Sep 2016 20:22:12 -0400 Subject: [PATCH 260/451] fixes object comparison --- XML.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/XML.java b/XML.java index 4ceec5e..047c701 100644 --- a/XML.java +++ b/XML.java @@ -186,7 +186,7 @@ public class XML { StringBuilder sb = new StringBuilder(string.length()); for (int i = 0, length = string.length(); i < length; i++) { char c = string.charAt(i); - if (c == AMP) { + if (c == '&') { final int semic = string.indexOf(';', i); if (semic > i) { final String entity = string.substring(i + 1, semic); @@ -204,7 +204,7 @@ public class XML { if ("quot".equalsIgnoreCase(entity)) { sb.append('"'); } else if ("amp".equalsIgnoreCase(entity)) { - sb.append(AMP); + sb.append('&'); } else if ("apos".equalsIgnoreCase(entity)) { sb.append('\''); } else if ("lt".equalsIgnoreCase(entity)) { @@ -212,7 +212,7 @@ public class XML { } else if ("gt".equalsIgnoreCase(entity)) { sb.append('>'); } else { - sb.append(AMP).append(entity).append(';'); + sb.append('&').append(entity).append(';'); } } // skip past the entity we just parsed. From 93ffca36c357c489cc283ecc2a103281b8b73037 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 28 Sep 2016 20:23:30 -0400 Subject: [PATCH 261/451] fixes spacing --- XML.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/XML.java b/XML.java index 047c701..78dd6a0 100644 --- a/XML.java +++ b/XML.java @@ -166,12 +166,12 @@ public class XML { && cp != 0x9 && cp != 0xA && cp != 0xD - ) || !( - // valid the range of acceptable characters that aren't control - (cp >= 0x20 && cp <= 0xD7FF) - || (cp >= 0xE000 && cp <= 0xFFFD) - || (cp >= 0x10000 && cp <= 0x10FFFF) - ) + ) || !( + // valid the range of acceptable characters that aren't control + (cp >= 0x20 && cp <= 0xD7FF) + || (cp >= 0xE000 && cp <= 0xFFFD) + || (cp >= 0x10000 && cp <= 0x10FFFF) + ) ; } From e0616a129e113b55e59f7d1fef759d87e240a244 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Wed, 5 Oct 2016 14:57:42 +0200 Subject: [PATCH 262/451] fixing #291 --- JSONPointer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JSONPointer.java b/JSONPointer.java index 563047b..82de7f9 100644 --- a/JSONPointer.java +++ b/JSONPointer.java @@ -138,7 +138,7 @@ public class JSONPointer { if (pointer == null) { throw new NullPointerException("pointer cannot be null"); } - if (pointer.isEmpty()) { + if (pointer.isEmpty() || pointer.equals("#")) { refTokens = Collections.emptyList(); return; } From 97e3d6c7cee211eac60deb7a3cc3d0994e167135 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bence=20Er=C5=91s?= Date: Wed, 5 Oct 2016 14:59:36 +0200 Subject: [PATCH 263/451] testcase for stleary/JSON-java#292 and adding .idea to .gitiignore --- .gitignore | 1 + src/test/java/org/json/junit/JSONPointerTest.java | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/.gitignore b/.gitignore index 7afd420..b7025e6 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ build /gradlew.bat .gitmodules src/main/ +.idea diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index 95fa73b..75f4ea8 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -78,6 +78,11 @@ public class JSONPointerTest { assertSame(document.get("foo"), query("#/foo")); } + @Test + public void uriFragmentNotationRoot() { + assertSame(document, query("#")); + } + @Test public void uriFragmentPercentHandling() { assertSame(document.get("c%d"), query("#/c%25d")); From 5ef4f58ef14b274d6cf0b88f3d89c223988893d5 Mon Sep 17 00:00:00 2001 From: joumar Date: Mon, 5 Dec 2016 11:55:24 -0300 Subject: [PATCH 264/451] [FIX] Update README Fixed C&P typo --- README | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README b/README index ce78da4..e5be06b 100644 --- a/README +++ b/README @@ -22,7 +22,7 @@ JSONObject.java: The JSONObject can parse text from a String or a JSONTokener to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. -JSONArray.java: The JSONObject can parse text from a String or a JSONTokener +JSONArray.java: The JSONArray can parse text from a String or a JSONTokener to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization. From eb806f4c14a1ec98045cfde56fcf1079ebc727c0 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 10 Feb 2017 10:07:28 -0500 Subject: [PATCH 265/451] make sure locale independent data is not upper/lowercased incorrectly. See #315 --- HTTP.java | 3 ++- JSONObject.java | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/HTTP.java b/HTTP.java index b14d04e..9b444ce 100644 --- a/HTTP.java +++ b/HTTP.java @@ -25,6 +25,7 @@ SOFTWARE. */ import java.util.Iterator; +import java.util.Locale; /** * Convert an HTTP header to a JSONObject and back. @@ -74,7 +75,7 @@ public class HTTP { String token; token = x.nextToken(); - if (token.toUpperCase().startsWith("HTTP")) { + if (token.toUpperCase(Locale.ROOT).startsWith("HTTP")) { // Response diff --git a/JSONObject.java b/JSONObject.java index 4df256a..1eab694 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1157,9 +1157,9 @@ public class JSONObject { && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { - key = key.toLowerCase(); + key = key.toLowerCase(Locale.ROOT); } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() + key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1); } From 928179a1f3d2bd0817803277298af3bf4ee706c9 Mon Sep 17 00:00:00 2001 From: stleary Date: Tue, 14 Feb 2017 08:30:22 -0600 Subject: [PATCH 266/451] locale tests --- build.gradle | 6 +++ .../org/json/junit/JSONObjectLocaleTest.java | 48 +++++++++++++++++++ .../java/org/json/junit/JunitTestSuite.java | 1 + .../java/org/json/junit/MyLocaleBean.java | 12 +++++ 4 files changed, 67 insertions(+) create mode 100755 src/test/java/org/json/junit/JSONObjectLocaleTest.java create mode 100755 src/test/java/org/json/junit/MyLocaleBean.java diff --git a/build.gradle b/build.gradle index d2969d4..58259f9 100644 --- a/build.gradle +++ b/build.gradle @@ -2,6 +2,12 @@ apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'jacoco' +tasks.withType(JavaCompile) { + // this subproject requires -parameters option + options.compilerArgs << '-parameters' + options.encoding = 'UTF-8' +} + sourceSets { // Uncomment main if you have merged JSON-Java and JSON-Java-unit-test code main diff --git a/src/test/java/org/json/junit/JSONObjectLocaleTest.java b/src/test/java/org/json/junit/JSONObjectLocaleTest.java new file mode 100755 index 0000000..a6cb996 --- /dev/null +++ b/src/test/java/org/json/junit/JSONObjectLocaleTest.java @@ -0,0 +1,48 @@ +package org.json.junit; + +import static org.junit.Assert.*; + +import java.util.*; + +import org.json.*; +import org.junit.*; + +/** + * Note: This file is saved as UTF-8. Do not save as ASCII or the tests will + * fail. + * + */ +public class JSONObjectLocaleTest { + /** + * JSONObject built from a bean with locale-specific keys - that is, the key + * fields are not LANG_ENGLISH. + */ + @Test + public void jsonObjectByLocaleBean() { + + MyLocaleBean myLocaleBean = new MyLocaleBean(); + + Locale.setDefault(new Locale("en")); + JSONObject jsonen = new JSONObject(myLocaleBean); + System.out.println("jsonen " + jsonen); + + Locale.setDefault(new Locale("tr")); + JSONObject jsontr = new JSONObject(myLocaleBean); + System.out.println("jsontr " + jsontr); + /** + * In this test we exercise code that handles keys of 1-char and + * multi-char length that include text from a non-English locale. + * Turkish in this case. The JSONObject code should correctly retain the + * non-EN_LANG chars in the key. + */ + assertTrue("expected beanId", + "Tlocaleüx".equals(jsonObject.getString(""))); + assertTrue("expected Tlocalü", + "Tlocaleü".equals(jsonObject.getString("ü"))); + assertTrue("expected Tlocaleüx", + "Tlocaleüx".equals((String)(jsonObject.query("/üx")))); + assertTrue("expected Tlocalü", + "Tlocaleü".equals((String)(jsonObject.query("/ü")))); + } + +} diff --git a/src/test/java/org/json/junit/JunitTestSuite.java b/src/test/java/org/json/junit/JunitTestSuite.java index 3a7223e..36bec60 100644 --- a/src/test/java/org/json/junit/JunitTestSuite.java +++ b/src/test/java/org/json/junit/JunitTestSuite.java @@ -13,6 +13,7 @@ import org.junit.runners.Suite; HTTPTest.class, JSONStringerTest.class, JSONObjectTest.class, + JSONObjectLocaleTest.class, JSONArrayTest.class, EnumTest.class, JSONPointerTest.class, diff --git a/src/test/java/org/json/junit/MyLocaleBean.java b/src/test/java/org/json/junit/MyLocaleBean.java new file mode 100755 index 0000000..0d68c39 --- /dev/null +++ b/src/test/java/org/json/junit/MyLocaleBean.java @@ -0,0 +1,12 @@ +package org.json.junit; + +public class MyLocaleBean { + private final String id = "beanId"; + private final String i = "beanI"; + public String getId() { + return id; + } + public String getI() { + return i; + } +} From f41e1d012aa5dbc012a22e6890a9755d03d0fae8 Mon Sep 17 00:00:00 2001 From: stleary Date: Thu, 16 Feb 2017 20:49:37 -0600 Subject: [PATCH 267/451] tests for locale-independent keys --- .../org/json/junit/JSONObjectLocaleTest.java | 45 +++++++++++-------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectLocaleTest.java b/src/test/java/org/json/junit/JSONObjectLocaleTest.java index a6cb996..9c80ab6 100755 --- a/src/test/java/org/json/junit/JSONObjectLocaleTest.java +++ b/src/test/java/org/json/junit/JSONObjectLocaleTest.java @@ -14,35 +14,42 @@ import org.junit.*; */ public class JSONObjectLocaleTest { /** - * JSONObject built from a bean with locale-specific keys - that is, the key - * fields are not LANG_ENGLISH. + * JSONObject built from a bean with locale-specific keys. + * In the Turkish alphabet, there are 2 versions of the letter "i". + * 'eh' I ı (dotless i) + * 'ee' İ i (dotted i) + * A problem can occur when parsing the public get methods for a bean. + * If the method starts with getI... then the key name will be lowercased + * to 'i' in English, and 'ı' in Turkish. + * We want the keys to be consistent regardless of locale, so JSON-Java + * lowercase operations are made to be locale-neutral by specifying + * Locale.ROOT. This causes 'I' to be universally lowercased to 'i' + * regardless of the locale currently in effect. */ @Test public void jsonObjectByLocaleBean() { MyLocaleBean myLocaleBean = new MyLocaleBean(); + /** + * This is just the control case which happens when the locale.ROOT + * lowercasing behavior is the same as the current locale. + */ Locale.setDefault(new Locale("en")); JSONObject jsonen = new JSONObject(myLocaleBean); - System.out.println("jsonen " + jsonen); + assertEquals("expected size 2, found: " +jsonen.length(), 2, jsonen.length()); + assertEquals("expected jsonen[i] == beanI", "beanI", jsonen.getString("i")); + assertEquals("expected jsonen[id] == beanId", "beanId", jsonen.getString("id")); + /** + * Without the JSON-Java change, these keys would be stored internally as + * starting with the letter, 'ı' (dotless i), since the lowercasing of + * the getI and getId keys would be specific to the Turkish locale. + */ Locale.setDefault(new Locale("tr")); JSONObject jsontr = new JSONObject(myLocaleBean); - System.out.println("jsontr " + jsontr); - /** - * In this test we exercise code that handles keys of 1-char and - * multi-char length that include text from a non-English locale. - * Turkish in this case. The JSONObject code should correctly retain the - * non-EN_LANG chars in the key. - */ - assertTrue("expected beanId", - "Tlocaleüx".equals(jsonObject.getString(""))); - assertTrue("expected Tlocalü", - "Tlocaleü".equals(jsonObject.getString("ü"))); - assertTrue("expected Tlocaleüx", - "Tlocaleüx".equals((String)(jsonObject.query("/üx")))); - assertTrue("expected Tlocalü", - "Tlocaleü".equals((String)(jsonObject.query("/ü")))); + assertEquals("expected size 2, found: " +jsontr.length(), 2, jsontr.length()); + assertEquals("expected jsontr[i] == beanI", "beanI", jsontr.getString("i")); + assertEquals("expected jsontr[id] == beanId", "beanId", jsontr.getString("id")); } - } From 9e0fc5e6804b205ba907e819028ff6c31d6907e8 Mon Sep 17 00:00:00 2001 From: alessandro rao Date: Sat, 25 Feb 2017 13:27:50 +0100 Subject: [PATCH 268/451] Allow user to invoke query and optQuery ,with a JSONPointer,directly from JSONArray or JSONObject --- JSONArray.java | 40 +++++++++++++++++++++++++++++++++++++--- JSONObject.java | 39 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 73 insertions(+), 6 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 2446fd6..8647f0a 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -980,7 +980,30 @@ public class JSONArray implements Iterable { * @return the item matched by the JSONPointer, otherwise null */ public Object query(String jsonPointer) { - return new JSONPointer(jsonPointer).queryFrom(this); + return query(new JSONPointer(jsonPointer)); + } + + /** + * Uses a uaer initialized JSONPointer and tries to + * match it to an item whithin this JSONArray. For example, given a + * JSONArray initialized with this document: + *
+     * [
+     *     {"b":"c"}
+     * ]
+     * 
+ * and this JSONPointer: + *
+     * "/0/b"
+     * 
+ * Then this method will return the String "c" + * A JSONPointerException may be thrown from code called by this method. + * + * @param jsonPointer string that can be used to create a JSONPointer + * @return the item matched by the JSONPointer, otherwise null + */ + public Object query(JSONPointer jsonPointer) { + return jsonPointer.queryFrom(this); } /** @@ -992,9 +1015,20 @@ public class JSONArray implements Iterable { * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ public Object optQuery(String jsonPointer) { - JSONPointer pointer = new JSONPointer(jsonPointer); + return query(new JSONPointer(jsonPointer)); + } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param The JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(JSONPointer jsonPointer) { try { - return pointer.queryFrom(this); + return jsonPointer.queryFrom(this); } catch (JSONPointerException e) { return null; } diff --git a/JSONObject.java b/JSONObject.java index 1eab694..b71b3b6 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1359,7 +1359,29 @@ public class JSONObject { * @return the item matched by the JSONPointer, otherwise null */ public Object query(String jsonPointer) { - return new JSONPointer(jsonPointer).queryFrom(this); + return query(new JSONPointer(jsonPointer)); + } + /** + * Uses a uaer initialized JSONPointer and tries to + * match it to an item within this JSONObject. For example, given a + * JSONObject initialized with this document: + *
+     * {
+     *     "a":{"b":"c"}
+     * }
+     * 
+ * and this JSONPointer: + *
+     * "/a/b"
+     * 
+ * Then this method will return the String "c". + * A JSONPointerException may be thrown from code called by this method. + * + * @param jsonPointer string that can be used to create a JSONPointer + * @return the item matched by the JSONPointer, otherwise null + */ + public Object query(JSONPointer jsonPointer) { + return jsonPointer.queryFrom(this); } /** @@ -1371,9 +1393,20 @@ public class JSONObject { * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ public Object optQuery(String jsonPointer) { - JSONPointer pointer = new JSONPointer(jsonPointer); + return optQuery(new JSONPointer(jsonPointer)); + } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param The JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(JSONPointer jsonPointer) { try { - return pointer.queryFrom(this); + return jsonPointer.queryFrom(this); } catch (JSONPointerException e) { return null; } From 2917104b5377a1a7ee4a5a2eb2487457d78dd71c Mon Sep 17 00:00:00 2001 From: alessandro rao Date: Sat, 25 Feb 2017 14:35:02 +0100 Subject: [PATCH 269/451] Allow user to invoke query and optQuery ,with a JSONPointer,directly from JSONArray or JSONObject fix JSONArray --- JSONArray.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JSONArray.java b/JSONArray.java index 8647f0a..132d46d 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1015,7 +1015,7 @@ public class JSONArray implements Iterable { * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ public Object optQuery(String jsonPointer) { - return query(new JSONPointer(jsonPointer)); + return optQuery(new JSONPointer(jsonPointer)); } /** From e41972a57426c1e65646a2ab0634693655e33495 Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 26 Feb 2017 11:09:41 -0600 Subject: [PATCH 270/451] add a test for unquoted values --- .../java/org/json/junit/JSONObjectTest.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 1b50e7a..1dec2fd 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -51,6 +51,23 @@ public class JSONObjectTest { new JSONObject(myBean); } + /** + * The JSON parser is permissive of unambiguous unquoted keys and values. + * Such JSON text should be allowed, even if it does not strictly conform + * to the spec. However, after being parsed, toString() should emit strictly + * conforming JSON text. + */ + @Test + public void unquotedText() { + String str = "{key1:value1, key2:42}"; + JSONObject jsonObject = new JSONObject(str); + String textStr = jsonObject.toString(); + assertTrue("expected key1", textStr.contains("\"key1\"")); + assertTrue("expected value1", textStr.contains("\"value1\"")); + assertTrue("expected key2", textStr.contains("\"key2\"")); + assertTrue("expected 42", textStr.contains("42")); + } + /** * A JSONObject can be created with no content */ From d1a5f15f0c0e1bb55322816d3e90cb084ba5dead Mon Sep 17 00:00:00 2001 From: stleary Date: Sun, 26 Mar 2017 15:03:09 -0500 Subject: [PATCH 271/451] unit tests for query-by-JSONPointer --- .../java/org/json/junit/JSONPointerTest.java | 111 +++++++++++++++++- 1 file changed, 109 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index 75f4ea8..0904b9e 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -157,7 +157,7 @@ public class JSONPointerTest { } /** - * Coverage for JSONObject queryFrom() + * Coverage for JSONObject query(String) */ @Test public void queryFromJSONObject() { @@ -187,7 +187,61 @@ public class JSONPointerTest { } /** - * Coverage for JSONArray queryFrom() + * Coverage for JSONObject query(JSONPointer) + */ + @Test + public void queryFromJSONObjectUsingPointer() { + String str = "{"+ + "\"stringKey\":\"hello world!\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\": {"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + Object obj = jsonObject.query(new JSONPointer("/stringKey")); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonObject.query(new JSONPointer("/arrayKey/1")); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonObject.query(new JSONPointer("/objectKey/b")); + assertTrue("Expected bVal", "bVal".equals(obj)); + try { + obj = jsonObject.query(new JSONPointer("/a/b/c")); + assertTrue("Expected JSONPointerException", false); + } catch (JSONPointerException e) { + assertTrue("Expected bad key/value exception", + "value [null] is not an array or object therefore its key b cannot be resolved". + equals(e.getMessage())); + } + } + + /** + * Coverage for JSONObject optQuery(JSONPointer) + */ + @Test + public void optQueryFromJSONObjectUsingPointer() { + String str = "{"+ + "\"stringKey\":\"hello world!\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\": {"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + Object obj = jsonObject.optQuery(new JSONPointer("/stringKey")); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonObject.optQuery(new JSONPointer("/arrayKey/1")); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonObject.optQuery(new JSONPointer("/objectKey/b")); + assertTrue("Expected bVal", "bVal".equals(obj)); + obj = jsonObject.optQuery(new JSONPointer("/a/b/c")); + assertTrue("Expected null", obj == null); + } + + /** + * Coverage for JSONArray query(String) */ @Test public void queryFromJSONArray() { @@ -214,4 +268,57 @@ public class JSONPointerTest { "a is not an array index".equals(e.getMessage())); } } + + /** + * Coverage for JSONArray query(JSONPointer) + */ + @Test + public void queryFromJSONArrayUsingPointer() { + String str = "["+ + "\"hello world!\","+ + "[0,1,2],"+ + "{"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "]"; + JSONArray jsonArray = new JSONArray(str); + Object obj = jsonArray.query(new JSONPointer("/0")); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonArray.query(new JSONPointer("/1/1")); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonArray.query(new JSONPointer("/2/b")); + assertTrue("Expected bVal", "bVal".equals(obj)); + try { + obj = jsonArray.query(new JSONPointer("/a/b/c")); + assertTrue("Expected JSONPointerException", false); + } catch (JSONPointerException e) { + assertTrue("Expected bad index exception", + "a is not an array index".equals(e.getMessage())); + } + } + + /** + * Coverage for JSONArray optQuery(JSONPointer) + */ + @Test + public void optQueryFromJSONArrayUsingPointer() { + String str = "["+ + "\"hello world!\","+ + "[0,1,2],"+ + "{"+ + "\"a\":\"aVal\","+ + "\"b\":\"bVal\""+ + "}"+ + "]"; + JSONArray jsonArray = new JSONArray(str); + Object obj = jsonArray.optQuery(new JSONPointer("/0")); + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + obj = jsonArray.optQuery(new JSONPointer("/1/1")); + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + obj = jsonArray.optQuery(new JSONPointer("/2/b")); + assertTrue("Expected bVal", "bVal".equals(obj)); + obj = jsonArray.optQuery(new JSONPointer("/a/b/c")); + assertTrue("Expected null", obj == null); + } } From ae1e9e2b6ad7ed48c9274c6900d2329f462b33e0 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 3 Apr 2017 11:59:36 -0400 Subject: [PATCH 272/451] fix spelling in javadoc comment --- JSONML.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JSONML.java b/JSONML.java index 82853a9..9cb767f 100644 --- a/JSONML.java +++ b/JSONML.java @@ -42,7 +42,7 @@ public class JSONML { * @param arrayForm true if array form, false if object form. * @param ja The JSONArray that is containing the current tag or null * if we are at the outermost level. - * @param keepStrings Don't type-convert text nodes and attibute values + * @param keepStrings Don't type-convert text nodes and attribute values * @return A JSONArray if the value is the outermost tag, otherwise null. * @throws JSONException */ From f12fa9ba5f760a01f635a5334c2ba44e24424c86 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 18 Apr 2017 08:32:10 -0500 Subject: [PATCH 273/451] Update LICENSE --- LICENSE | 2 ++ 1 file changed, 2 insertions(+) diff --git a/LICENSE b/LICENSE index 87d1411..02ee0ef 100644 --- a/LICENSE +++ b/LICENSE @@ -1,3 +1,5 @@ +============================================================================ + Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy From 9df5d34bbee13a5d228e0feedf22d8b1039d01ed Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 27 Apr 2017 12:39:42 -0400 Subject: [PATCH 274/451] * Update link in the README to the main JSON-Java repo * Cleans up some warnings * Adds new test for bug https://github.com/stleary/JSON-java/issues/332 * Adds some resource handling for string writers using pre-java1.7 support. I know StringWriters don't need a close method called, but the tests should still handle their resources properly. --- README.md | 2 +- src/test/java/org/json/junit/EnumTest.java | 3 +- .../java/org/json/junit/JSONArrayTest.java | 100 +- src/test/java/org/json/junit/JSONMLTest.java | 75 +- .../java/org/json/junit/JSONObjectTest.java | 4707 +++++++++-------- .../java/org/json/junit/JSONStringTest.java | 681 +-- src/test/java/org/json/junit/MyEnumField.java | 8 +- .../java/org/json/junit/MyPublicClass.java | 1 + .../org/json/junit/StringsResourceBundle.java | 1 + src/test/java/org/json/junit/XMLTest.java | 3 - 10 files changed, 2878 insertions(+), 2703 deletions(-) diff --git a/README.md b/README.md index faf400a..0772d3b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Unit tests to validate the JSON-Java GitHub project code
-https://github.com/douglascrockford/JSON-java
+https://github.com/stleary/JSON-java
Gradle and Eclipse is the recommended build tool and IDE.
Run individual tests or JunitTestSuite using EclEmma Coverage, or execute the **TestRunner** application directly.
diff --git a/src/test/java/org/json/junit/EnumTest.java b/src/test/java/org/json/junit/EnumTest.java index ab4a1e5..6b97107 100644 --- a/src/test/java/org/json/junit/EnumTest.java +++ b/src/test/java/org/json/junit/EnumTest.java @@ -5,7 +5,6 @@ import static org.junit.Assert.assertTrue; import java.util.EnumSet; import java.util.List; import java.util.Map; -import java.util.Set; import org.json.JSONArray; import org.json.JSONObject; @@ -92,7 +91,7 @@ public class EnumTest { assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/VAL1"))); assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/VAL2"))); - assertTrue("expected VAL3", myEnumField.VAL3.equals(jsonObject.query("/VAL3"))); + assertTrue("expected VAL3", MyEnumField.VAL3.equals(jsonObject.query("/VAL3"))); } /** diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 244a693..80b78a5 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -1,11 +1,11 @@ package org.json.junit; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; +import java.io.IOException; import java.io.StringWriter; -import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; @@ -61,7 +61,7 @@ public class JSONArrayTest { @Test(expected=NullPointerException.class) public void nullException() { String str = null; - new JSONArray(str); + assertNull("Should throw an exception", new JSONArray(str)); } /** @@ -72,8 +72,7 @@ public class JSONArrayTest { public void emptStr() { String str = ""; try { - new JSONArray(str); - assertTrue("Should throw an exception", false); + assertNull("Should throw an exception", new JSONArray(str)); } catch (JSONException e) { assertTrue("Expected an exception message", "A JSONArray text must start with '[' at 1 [character 2 line 1]". @@ -90,8 +89,7 @@ public class JSONArrayTest { public void badObject() { String str = "abc"; try { - new JSONArray((Object)str); - assertTrue("Should throw an exception", false); + assertNull("Should throw an exception", new JSONArray((Object)str)); } catch (JSONException e) { assertTrue("Expected an exception message", "JSONArray initial value should be a string or collection or array.". @@ -100,7 +98,7 @@ public class JSONArrayTest { } /** - * Verifies that the constructor has backwards compatability with RAW types pre-java5. + * Verifies that the constructor has backwards compatibility with RAW types pre-java5. */ @Test public void verifyConstructor() { @@ -130,7 +128,7 @@ public class JSONArrayTest { } /** - * Verifies that the put Collection has backwards compatability with RAW types pre-java5. + * Verifies that the put Collection has backwards compatibility with RAW types pre-java5. */ @Test public void verifyPutCollection() { @@ -164,7 +162,7 @@ public class JSONArrayTest { /** - * Verifies that the put Map has backwards compatability with RAW types pre-java5. + * Verifies that the put Map has backwards compatibility with RAW types pre-java5. */ @Test public void verifyPutMap() { @@ -209,9 +207,10 @@ public class JSONArrayTest { * Create a JSONArray doc with a variety of different elements. * Confirm that the values can be accessed via the get[type]() API methods */ + @SuppressWarnings("boxing") @Test public void getArrayValues() { - JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray jsonArray = new JSONArray(this.arrayStr); // booleans assertTrue("Array true", true == jsonArray.getBoolean(0)); @@ -255,7 +254,7 @@ public class JSONArrayTest { */ @Test public void failedGetArrayValues() { - JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray jsonArray = new JSONArray(this.arrayStr); try { jsonArray.getBoolean(4); assertTrue("expected getBoolean to fail", false); @@ -321,7 +320,7 @@ public class JSONArrayTest { */ @Test public void join() { - JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray jsonArray = new JSONArray(this.arrayStr); String joinStr = jsonArray.join(","); // validate JSON @@ -357,7 +356,7 @@ public class JSONArrayTest { public void length() { assertTrue("expected empty JSONArray length 0", new JSONArray().length() == 0); - JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray jsonArray = new JSONArray(this.arrayStr); assertTrue("expected JSONArray length 13", jsonArray.length() == 13); JSONArray nestedJsonArray = jsonArray.getJSONArray(9); assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1); @@ -368,9 +367,10 @@ public class JSONArrayTest { * Confirm that the values can be accessed via the opt[type](index) * and opt[type](index, default) API methods. */ + @SuppressWarnings("boxing") @Test public void opt() { - JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray jsonArray = new JSONArray(this.arrayStr); assertTrue("Array opt value true", Boolean.TRUE == jsonArray.opt(0)); assertTrue("Array opt value out of range", @@ -441,6 +441,7 @@ public class JSONArrayTest { * Exercise the JSONArray.put(value) method with various parameters * and confirm the resulting JSONArray. */ + @SuppressWarnings("boxing") @Test public void put() { JSONArray jsonArray = new JSONArray(); @@ -516,6 +517,7 @@ public class JSONArrayTest { * Exercise the JSONArray.put(index, value) method with various parameters * and confirm the resulting JSONArray. */ + @SuppressWarnings("boxing") @Test public void putIndex() { JSONArray jsonArray = new JSONArray(); @@ -596,11 +598,11 @@ public class JSONArrayTest { */ @Test public void remove() { - String arrayStr = + String arrayStr1 = "["+ "1"+ "]"; - JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray jsonArray = new JSONArray(arrayStr1); jsonArray.remove(0); assertTrue("array should be empty", null == jsonArray.remove(5)); assertTrue("jsonArray should be empty", jsonArray.length() == 0); @@ -612,11 +614,11 @@ public class JSONArrayTest { */ @Test public void notSimilar() { - String arrayStr = + String arrayStr1 = "["+ "1"+ "]"; - JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray jsonArray = new JSONArray(arrayStr1); JSONArray otherJsonArray = new JSONArray(); assertTrue("arrays lengths differ", !jsonArray.similar(otherJsonArray)); @@ -745,9 +747,10 @@ public class JSONArrayTest { /** * Exercise the JSONArray iterator. */ + @SuppressWarnings("boxing") @Test public void iterator() { - JSONArray jsonArray = new JSONArray(arrayStr); + JSONArray jsonArray = new JSONArray(this.arrayStr); Iterator it = jsonArray.iterator(); assertTrue("Array true", Boolean.TRUE.equals(it.next())); @@ -803,16 +806,20 @@ public class JSONArrayTest { * Exercise the JSONArray write() method */ @Test - public void write() { + public void write() throws IOException { String str = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":2,\"key3\":3}]"; JSONArray jsonArray = new JSONArray(str); String expectedStr = str; StringWriter stringWriter = new StringWriter(); - Writer writer = jsonArray.write(stringWriter); - String actualStr = writer.toString(); - assertTrue("write() expected " + expectedStr + - " but found " + actualStr, - expectedStr.equals(actualStr)); + try { + jsonArray.write(stringWriter); + String actualStr = stringWriter.toString(); + assertTrue("write() expected " + expectedStr + + " but found " + actualStr, + expectedStr.equals(actualStr)); + } finally { + stringWriter.close(); + } } /** @@ -837,7 +844,7 @@ public class JSONArrayTest { * Exercise the JSONArray write(Writer, int, int) method */ @Test - public void write3Param() { + public void write3Param() throws IOException { String str0 = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":false,\"key3\":3.14}]"; String str2 = "[\n" + @@ -852,15 +859,20 @@ public class JSONArrayTest { JSONArray jsonArray = new JSONArray(str0); String expectedStr = str0; StringWriter stringWriter = new StringWriter(); - Writer writer = jsonArray.write(stringWriter, 0, 0); - String actualStr = writer.toString(); - assertEquals(expectedStr, actualStr); - - expectedStr = str2; + try { + String actualStr = jsonArray.write(stringWriter, 0, 0).toString(); + assertEquals(expectedStr, actualStr); + } finally { + stringWriter.close(); + } stringWriter = new StringWriter(); - writer = jsonArray.write(stringWriter, 2, 1); - actualStr = writer.toString(); - assertEquals(expectedStr, actualStr); + try { + expectedStr = str2; + String actualStr = jsonArray.write(stringWriter, 2, 1).toString(); + assertEquals(expectedStr, actualStr); + } finally { + stringWriter.close(); + } } /** @@ -917,49 +929,49 @@ public class JSONArrayTest { "]"; JSONArray jsonArray = new JSONArray(jsonArrayStr); - List list = jsonArray.toList(); + List list = jsonArray.toList(); assertTrue("List should not be null", list != null); assertTrue("List should have 3 elements", list.size() == 3); - List val1List = (List) list.get(0); + List val1List = (List) list.get(0); assertTrue("val1 should not be null", val1List != null); assertTrue("val1 should have 3 elements", val1List.size() == 3); assertTrue("val1 value 1 should be 1", val1List.get(0).equals(Integer.valueOf(1))); assertTrue("val1 value 2 should be 2", val1List.get(1).equals(Integer.valueOf(2))); - Map key1Value3Map = (Map)val1List.get(2); + Map key1Value3Map = (Map)val1List.get(2); assertTrue("Map should not be null", key1Value3Map != null); assertTrue("Map should have 1 element", key1Value3Map.size() == 1); assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); - Map val2Map = (Map) list.get(1); + Map val2Map = (Map) list.get(1); assertTrue("val2 should not be null", val2Map != null); assertTrue("val2 should have 4 elements", val2Map.size() == 4); assertTrue("val2 map key 1 should be val1", val2Map.get("key1").equals("val1")); assertTrue("val2 map key 3 should be 42", val2Map.get("key3").equals(Integer.valueOf(42))); - Map val2Key2Map = (Map)val2Map.get("key2"); + Map val2Key2Map = (Map)val2Map.get("key2"); assertTrue("val2 map key 2 should not be null", val2Key2Map != null); assertTrue("val2 map key 2 should have an entry", val2Key2Map.containsKey("key2")); assertTrue("val2 map key 2 value should be null", val2Key2Map.get("key2") == null); - List val2Key4List = (List)val2Map.get("key4"); + List val2Key4List = (List)val2Map.get("key4"); assertTrue("val2 map key 4 should not be null", val2Key4List != null); assertTrue("val2 map key 4 should be empty", val2Key4List.isEmpty()); - List val3List = (List) list.get(2); + List val3List = (List) list.get(2); assertTrue("val3 should not be null", val3List != null); assertTrue("val3 should have 2 elements", val3List.size() == 2); - List val3Val1List = (List)val3List.get(0); + List val3Val1List = (List)val3List.get(0); assertTrue("val3 list val 1 should not be null", val3Val1List != null); assertTrue("val3 list val 1 should have 2 elements", val3Val1List.size() == 2); assertTrue("val3 list val 1 list element 1 should be value1", val3Val1List.get(0).equals("value1")); assertTrue("val3 list val 1 list element 2 should be 2.1", val3Val1List.get(1).equals(Double.valueOf("2.1"))); - List val3Val2List = (List)val3List.get(1); + List val3Val2List = (List)val3List.get(1); assertTrue("val3 list val 2 should not be null", val3Val2List != null); assertTrue("val3 list val 2 should have 1 element", val3Val2List.size() == 1); assertTrue("val3 list val 2 list element 1 should be null", val3Val2List.get(0) == null); diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 1298591..1ad2cb4 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -711,8 +711,7 @@ public class JSONMLTest { } /** - * JSON string cannot be reverted to original xml. See test result in - * comment below. + * JSON string cannot be reverted to original xml when type guessing is used. */ @Test public void testToJSONArray_reversibility() { @@ -722,10 +721,11 @@ public class JSONMLTest { } /** - * test passes when using the new method toJsonML. + * JSON string cannot be reverted to original xml when type guessing is used. + * When we force all the values as string, the original text comes back. */ @Test - public void testToJsonML() { + public void testToJSONArray_reversibility2() { final String originalXml = "011000True"; final String expectedJsonString = "[\"root\",[\"id\",\"01\"],[\"id\",\"1\"],[\"id\",\"00\"],[\"id\",\"0\"],[\"item\",{\"id\":\"01\"}],[\"title\",\"True\"]]"; final JSONArray json = JSONML.toJSONArray(originalXml,true); @@ -735,4 +735,71 @@ public class JSONMLTest { assertEquals(originalXml, reverseXml); } + /** + * JSON can be reverted to original xml. + */ + @Test + public void testToJSONArray_reversibility3() { + final String originalXml = "400402"; + final JSONArray jsonArray = JSONML.toJSONArray(originalXml, false); + final String revertedXml = JSONML.toString(jsonArray); + assertEquals(revertedXml, originalXml); + } + + /** + * JSON string cannot be reverted to original xml. See test result in + * comment below. + */ + @Test + public void testToJSONObject_reversibility() { + final String originalXml = "400402"; + final JSONObject originalObject=JSONML.toJSONObject(originalXml,false); + final String originalJson = originalObject.toString(); + final String xml = JSONML.toString(originalObject); + final JSONObject revertedObject = JSONML.toJSONObject(xml, false); + final String newJson = revertedObject.toString(); + assertTrue("JSON Objects are not similar",originalObject.similar(revertedObject)); + assertEquals("original JSON does not equal the new JSON",originalJson, newJson); + } + + /** + * Test texts taken from jsonml.org. Currently our implementation FAILS this conversion but shouldn't. + * Technically JsonML should be able to transform any valid xhtml document, but ours only supports + * standard XML entities, not HTML entities. + */ + @Test + public void testAttributeConversionReversabilityHTML() { + final String originalXml = "
#5D28D1Example text here
#AF44EF127310656
#AAD034 © 
"; + final String expectedJsonString = "[\"table\",{\"class\" : \"MyTable\",\"style\" : \"background-color:yellow\"},[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#550758\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:red\"},\"Example text here\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#993101\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:green\"},\"127624015\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#E33D87\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:blue\"},\"\u00A0\",[\"span\",{ \"style\" : \"background-color:maroon\" },\"\u00A9\"],\"\u00A0\"]]]"; + final JSONArray json = JSONML.toJSONArray(originalXml,true); + final String actualJsonString = json.toString(); + + final String reverseXml = JSONML.toString(json); + assertNotEquals(originalXml, reverseXml); + + assertNotEquals(expectedJsonString, actualJsonString); + } + +// this test does not pass for the following reasons: +// 1. Our XML parser does not handle generic HTML entities, only valid XML entities. Hence   +// or other HTML specific entites would fail on reversability +// 2. Our JSON implementation for storing the XML attributes uses the standard unordered map. +// This means that can not be reversed reliably. +// /** +// * Test texts taken from jsonml.org but modified to have XML entities only. +// */ +// @Test +// public void testAttributeConversionReversabilityXML() { +// final String originalXml = "
#5D28D1Example text here
#AF44EF127310656
#AAD034&><
"; +// final String expectedJsonString = "[\"table\",{\"class\" : \"MyTable\",\"style\" : \"background-color:yellow\"},[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#550758\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:red\"},\"Example text here\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#993101\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:green\"},\"127624015\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#E33D87\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:blue\"},\"&\",[\"span\",{ \"style\" : \"background-color:maroon\" },\">\"],\"<\"]]]"; +// final JSONArray jsonML = JSONML.toJSONArray(originalXml,true); +// final String actualJsonString = jsonML.toString(); +// +// final String reverseXml = JSONML.toString(jsonML); +// // currently not equal because the hashing of the attribute objects makes the attribute +// // order not happen the same way twice +// assertEquals(originalXml, reverseXml); +// +// assertEquals(expectedJsonString, actualJsonString); +// } } diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 1dec2fd..fb32cda 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1,2336 +1,2371 @@ -package org.json.junit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; - -import org.json.CDL; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.json.JSONPointerException; -import org.json.XML; -import org.junit.Test; - -import com.jayway.jsonpath.Configuration; -import com.jayway.jsonpath.JsonPath; - -/** - * JSONObject, along with JSONArray, are the central classes of the reference app. - * All of the other classes interact with them, and JSON functionality would - * otherwise be impossible. - */ -public class JSONObjectTest { - - /** - * JSONObject built from a bean, but only using a null value. - * Nothing good is expected to happen. - * Expects NullPointerException - */ - @Test(expected=NullPointerException.class) - public void jsonObjectByNullBean() { - MyBean myBean = null; - new JSONObject(myBean); - } - - /** - * The JSON parser is permissive of unambiguous unquoted keys and values. - * Such JSON text should be allowed, even if it does not strictly conform - * to the spec. However, after being parsed, toString() should emit strictly - * conforming JSON text. - */ - @Test - public void unquotedText() { - String str = "{key1:value1, key2:42}"; - JSONObject jsonObject = new JSONObject(str); - String textStr = jsonObject.toString(); - assertTrue("expected key1", textStr.contains("\"key1\"")); - assertTrue("expected value1", textStr.contains("\"value1\"")); - assertTrue("expected key2", textStr.contains("\"key2\"")); - assertTrue("expected 42", textStr.contains("42")); - } - - /** - * A JSONObject can be created with no content - */ - @Test - public void emptyJsonObject() { - JSONObject jsonObject = new JSONObject(); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); - } - - /** - * A JSONObject can be created from another JSONObject plus a list of names. - * In this test, some of the starting JSONObject keys are not in the - * names list. - */ - @Test - public void jsonObjectByNames() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"nullKey\":null,"+ - "\"stringKey\":\"hello world!\","+ - "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ - "\"intKey\":42,"+ - "\"doubleKey\":-23.45e67"+ - "}"; - String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"}; - JSONObject jsonObject = new JSONObject(str); - - // validate JSON - JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey"))); - assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObjectByName.query("/doubleKey"))); - } - - /** - * JSONObjects can be built from a Map. - * In this test the map is null. - * the JSONObject(JsonTokener) ctor is not tested directly since it already - * has full coverage from other tests. - */ - @Test - public void jsonObjectByNullMap() { - Map map = null; - JSONObject jsonObject = new JSONObject(map); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); - } - - /** - * JSONObjects can be built from a Map. - * In this test all of the map entries are valid JSON types. - */ - @Test - public void jsonObjectByMap() { - Map map = new HashMap(); - map.put("trueKey", new Boolean(true)); - map.put("falseKey", new Boolean(false)); - map.put("stringKey", "hello world!"); - map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); - map.put("intKey", new Long(42)); - map.put("doubleKey", new Double(-23.45e67)); - JSONObject jsonObject = new JSONObject(map); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); - } - - /** - * Verifies that the constructor has backwards compatability with RAW types pre-java5. - */ - @Test - public void verifyConstructor() { - - final JSONObject expected = new JSONObject("{\"myKey\":10}"); - - @SuppressWarnings("rawtypes") - Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); - JSONObject jaRaw = new JSONObject(myRawC); - - Map myCStrObj = Collections.singletonMap("myKey", - (Object) Integer.valueOf(10)); - JSONObject jaStrObj = new JSONObject(myCStrObj); - - Map myCStrInt = Collections.singletonMap("myKey", - Integer.valueOf(10)); - JSONObject jaStrInt = new JSONObject(myCStrInt); - - Map myCObjObj = Collections.singletonMap((Object) "myKey", - (Object) Integer.valueOf(10)); - JSONObject jaObjObj = new JSONObject(myCObjObj); - - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); - } - - /** - * Tests Number serialization. - */ - @Test - public void verifyNumberOutput(){ - /** - * MyNumberContainer is a POJO, so call JSONObject(bean), - * which builds a map of getter names/values - * The only getter is getMyNumber (key=myNumber), - * whose return value is MyNumber. MyNumber extends Number, - * but is not recognized as such by wrap() per current - * implementation, so wrap() returns the default new JSONObject(bean). - * The only getter is getNumber (key=number), whose return value is - * BigDecimal(42). - */ - JSONObject jsonObject = new JSONObject(new MyNumberContainer()); - String actual = jsonObject.toString(); - String expected = "{\"myNumber\":{\"number\":42}}"; - assertEquals("Not Equal", expected , actual); - - /** - * JSONObject.put() handles objects differently than the - * bean constructor. Where the bean ctor wraps objects before - * placing them in the map, put() inserts the object without wrapping. - * In this case, a MyNumber instance is the value. - * The MyNumber.toString() method is responsible for - * returning a reasonable value: the string '42'. - */ - jsonObject = new JSONObject(); - jsonObject.put("myNumber", new MyNumber()); - actual = jsonObject.toString(); - expected = "{\"myNumber\":42}"; - assertEquals("Not Equal", expected , actual); - - /** - * Calls the JSONObject(Map) ctor, which calls wrap() for values. - * AtomicInteger is a Number, but is not recognized by wrap(), per - * current implementation. However, the type is - * 'java.util.concurrent.atomic', so due to the 'java' prefix, - * wrap() inserts the value as a string. That is why 42 comes back - * wrapped in quotes. - */ - jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); - actual = jsonObject.toString(); - expected = "{\"myNumber\":\"42\"}"; - assertEquals("Not Equal", expected , actual); - - /** - * JSONObject.put() inserts the AtomicInteger directly into the - * map not calling wrap(). In toString()->write()->writeValue(), - * AtomicInteger is recognized as a Number, and converted via - * numberToString() into the unquoted string '42'. - */ - jsonObject = new JSONObject(); - jsonObject.put("myNumber", new AtomicInteger(42)); - actual = jsonObject.toString(); - expected = "{\"myNumber\":42}"; - assertEquals("Not Equal", expected , actual); - - /** - * Calls the JSONObject(Map) ctor, which calls wrap() for values. - * Fraction is a Number, but is not recognized by wrap(), per - * current implementation. As a POJO, Franction is handled as a - * bean and inserted into a contained JSONObject. It has 2 getters, - * for numerator and denominator. - */ - jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2))); - assertEquals(1, jsonObject.length()); - assertEquals(2, ((JSONObject)(jsonObject.get("myNumber"))).length()); - assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject.query("/myNumber/numerator")); - assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject.query("/myNumber/denominator")); - - /** - * JSONObject.put() inserts the Fraction directly into the - * map not calling wrap(). In toString()->write()->writeValue(), - * Fraction is recognized as a Number, and converted via - * numberToString() into the unquoted string '4/2'. But the - * BigDecimal sanity check fails, so writeValue() defaults - * to returning a safe JSON quoted string. Pretty slick! - */ - jsonObject = new JSONObject(); - jsonObject.put("myNumber", new Fraction(4,2)); - actual = jsonObject.toString(); - expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed - assertEquals("Not Equal", expected , actual); - } - - /** - * Verifies that the put Collection has backwards compatability with RAW types pre-java5. - */ - @Test - public void verifyPutCollection() { - - final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); - - @SuppressWarnings("rawtypes") - Collection myRawC = Collections.singleton(Integer.valueOf(10)); - JSONObject jaRaw = new JSONObject(); - jaRaw.put("myCollection", myRawC); - - Collection myCObj = Collections.singleton((Object) Integer - .valueOf(10)); - JSONObject jaObj = new JSONObject(); - jaObj.put("myCollection", myCObj); - - Collection myCInt = Collections.singleton(Integer - .valueOf(10)); - JSONObject jaInt = new JSONObject(); - jaInt.put("myCollection", myCInt); - - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaInt)); - } - - - /** - * Verifies that the put Map has backwards compatability with RAW types pre-java5. - */ - @Test - public void verifyPutMap() { - - final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); - - @SuppressWarnings("rawtypes") - Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); - JSONObject jaRaw = new JSONObject(); - jaRaw.put("myMap", myRawC); - - Map myCStrObj = Collections.singletonMap("myKey", - (Object) Integer.valueOf(10)); - JSONObject jaStrObj = new JSONObject(); - jaStrObj.put("myMap", myCStrObj); - - Map myCStrInt = Collections.singletonMap("myKey", - Integer.valueOf(10)); - JSONObject jaStrInt = new JSONObject(); - jaStrInt.put("myMap", myCStrInt); - - Map myCObjObj = Collections.singletonMap((Object) "myKey", - (Object) Integer.valueOf(10)); - JSONObject jaObjObj = new JSONObject(); - jaObjObj.put("myMap", myCObjObj); - - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); - assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); - } - - - /** - * JSONObjects can be built from a Map. - * In this test the map entries are not valid JSON types. - * The actual conversion is kind of interesting. - */ - @Test - public void jsonObjectByMapWithUnsupportedValues() { - Map jsonMap = new HashMap(); - // Just insert some random objects - jsonMap.put("key1", new CDL()); - jsonMap.put("key2", new Exception()); - - JSONObject jsonObject = new JSONObject(jsonMap); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected 0 key1 items", ((Map)(JsonPath.read(doc, "$.key1"))).size() == 0); - assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2"))); - } - - /** - * JSONObjects can be built from a Map. - * In this test one of the map values is null - */ - @Test - public void jsonObjectByMapWithNullValue() { - Map map = new HashMap(); - map.put("trueKey", new Boolean(true)); - map.put("falseKey", new Boolean(false)); - map.put("stringKey", "hello world!"); - map.put("nullKey", null); - map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); - map.put("intKey", new Long(42)); - map.put("doubleKey", new Double(-23.45e67)); - JSONObject jsonObject = new JSONObject(map); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); - assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); - } - - /** - * JSONObject built from a bean. In this case all but one of the - * bean getters return valid JSON types - */ - @Test - public void jsonObjectByBean() { - /** - * Default access classes have to be mocked since JSONObject, which is - * not in the same package, cannot call MyBean methods by reflection. - */ - MyBean myBean = mock(MyBean.class); - when(myBean.getDoubleKey()).thenReturn(-23.45e7); - when(myBean.getIntKey()).thenReturn(42); - when(myBean.getStringKey()).thenReturn("hello world!"); - when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!"); - when(myBean.isTrueKey()).thenReturn(true); - when(myBean.isFalseKey()).thenReturn(false); - when(myBean.getStringReaderKey()).thenReturn( - new StringReader("") { - }); - - JSONObject jsonObject = new JSONObject(myBean); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); - assertTrue("expected 0 items in stringReaderKey", ((Map) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected hello world!","hello world!".equals(jsonObject.query("/stringKey"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); - assertTrue("expected 42", Integer.valueOf("42").equals(jsonObject.query("/intKey"))); - assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(jsonObject.query("/doubleKey"))); - // sorry, mockito artifact - assertTrue("expected 2 callbacks items", ((List)(JsonPath.read(doc, "$.callbacks"))).size() == 2); - assertTrue("expected 0 handler items", ((Map)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0); - assertTrue("expected 0 callbacks[1] items", ((Map)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0); - } - - /** - * A bean is also an object. But in order to test the JSONObject - * ctor that takes an object and a list of names, - * this particular bean needs some public - * data members, which have been added to the class. - */ - @Test - public void jsonObjectByObjectAndNames() { - String[] keys = {"publicString", "publicInt"}; - // just need a class that has public data members - MyPublicClass myPublicClass = new MyPublicClass(); - JSONObject jsonObject = new JSONObject(myPublicClass, keys); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString"))); - assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt"))); - } - - /** - * Exercise the JSONObject from resource bundle functionality. - * The test resource bundle is uncomplicated, but provides adequate test coverage. - */ - @Test - public void jsonObjectByResourceBundle() { - JSONObject jsonObject = new - JSONObject("org.json.junit.StringsResourceBundle", - Locale.getDefault()); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected 2 greetings items", ((Map)(JsonPath.read(doc, "$.greetings"))).size() == 2); - assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello"))); - assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world"))); - assertTrue("expected 2 farewells items", ((Map)(JsonPath.read(doc, "$.farewells"))).size() == 2); - assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later"))); - assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator"))); - } - - /** - * Exercise the JSONObject.accumulate() method - */ - @Test - public void jsonObjectAccumulate() { - - JSONObject jsonObject = new JSONObject(); - jsonObject.accumulate("myArray", true); - jsonObject.accumulate("myArray", false); - jsonObject.accumulate("myArray", "hello world!"); - jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); - jsonObject.accumulate("myArray", 42); - jsonObject.accumulate("myArray", -23.45e7); - // include an unsupported object for coverage - try { - jsonObject.accumulate("myArray", Double.NaN); - assertTrue("Expected exception", false); - } catch (JSONException ignored) {} - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1"))); - assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); - assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); - assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); - } - - /** - * Exercise the JSONObject append() functionality - */ - @Test - public void jsonObjectAppend() { - JSONObject jsonObject = new JSONObject(); - jsonObject.append("myArray", true); - jsonObject.append("myArray", false); - jsonObject.append("myArray", "hello world!"); - jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); - jsonObject.append("myArray", 42); - jsonObject.append("myArray", -23.45e7); - // include an unsupported object for coverage - try { - jsonObject.append("myArray", Double.NaN); - assertTrue("Expected exception", false); - } catch (JSONException ignored) {} - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1/"))); - assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); - assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); - assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); - } - - /** - * Exercise the JSONObject doubleToString() method - */ - @Test - public void jsonObjectDoubleToString() { - String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; - Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, - Double.NaN, Double.NEGATIVE_INFINITY }; - for (int i = 0; i < expectedStrs.length; ++i) { - String actualStr = JSONObject.doubleToString(doubles[i]); - assertTrue("value expected ["+expectedStrs[i]+ - "] found ["+actualStr+ "]", - expectedStrs[i].equals(actualStr)); - } - } - - /** - * Exercise some JSONObject get[type] and opt[type] methods - */ - @Test - public void jsonObjectValues() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"trueStrKey\":\"true\","+ - "\"falseStrKey\":\"false\","+ - "\"stringKey\":\"hello world!\","+ - "\"intKey\":42,"+ - "\"intStrKey\":\"43\","+ - "\"longKey\":1234567890123456789,"+ - "\"longStrKey\":\"987654321098765432\","+ - "\"doubleKey\":-23.45e7,"+ - "\"doubleStrKey\":\"00001.000\","+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{\"myKey\":\"myVal\"}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); - assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); - assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); - assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); - assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); - assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); - assertTrue("stringKey should be string", - jsonObject.getString("stringKey").equals("hello world!")); - assertTrue("doubleKey should be double", - jsonObject.getDouble("doubleKey") == -23.45e7); - assertTrue("doubleStrKey should be double", - jsonObject.getDouble("doubleStrKey") == 1); - assertTrue("opt doubleKey should be double", - jsonObject.optDouble("doubleKey") == -23.45e7); - assertTrue("opt doubleKey with Default should be double", - jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); - assertTrue("intKey should be int", - jsonObject.optInt("intKey") == 42); - assertTrue("opt intKey should be int", - jsonObject.optInt("intKey", 0) == 42); - assertTrue("opt intKey with default should be int", - jsonObject.getInt("intKey") == 42); - assertTrue("intStrKey should be int", - jsonObject.getInt("intStrKey") == 43); - assertTrue("longKey should be long", - jsonObject.getLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey should be long", - jsonObject.optLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey with default should be long", - jsonObject.optLong("longKey", 0) == 1234567890123456789L); - assertTrue("longStrKey should be long", - jsonObject.getLong("longStrKey") == 987654321098765432L); - assertTrue("xKey should not exist", - jsonObject.isNull("xKey")); - assertTrue("stringKey should exist", - jsonObject.has("stringKey")); - assertTrue("opt stringKey should string", - jsonObject.optString("stringKey").equals("hello world!")); - assertTrue("opt stringKey with default should string", - jsonObject.optString("stringKey", "not found").equals("hello world!")); - JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); - assertTrue("arrayKey should be JSONArray", - jsonArray.getInt(0) == 0 && - jsonArray.getInt(1) == 1 && - jsonArray.getInt(2) == 2); - jsonArray = jsonObject.optJSONArray("arrayKey"); - assertTrue("opt arrayKey should be JSONArray", - jsonArray.getInt(0) == 0 && - jsonArray.getInt(1) == 1 && - jsonArray.getInt(2) == 2); - JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); - assertTrue("objectKey should be JSONObject", - jsonObjectInner.get("myKey").equals("myVal")); - } - - /** - * Check whether JSONObject handles large or high precision numbers correctly - */ - @Test - public void stringToValueNumbersTest() { - assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0") instanceof Double); - assertTrue("-0.0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double); - assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String); - assertTrue( "0.2 should be a Double!", - JSONObject.stringToValue( "0.2" ) instanceof Double ); - assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", - JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double ); - /** - * This test documents a need for BigDecimal conversion. - */ - Object obj = JSONObject.stringToValue( "299792.457999999984" ); - assertTrue( "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!", - obj.equals(new Double(299792.458)) ); - assertTrue( "1 should be an Integer!", - JSONObject.stringToValue( "1" ) instanceof Integer ); - assertTrue( "Integer.MAX_VALUE should still be an Integer!", - JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); - assertTrue( "Large integers should be a Long!", - JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); - assertTrue( "Long.MAX_VALUE should still be an Integer!", - JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); - - String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString(); - assertTrue( "Really large integers currently evaluate to string", - JSONObject.stringToValue(str).equals("9223372036854775808")); - } - - /** - * This test documents numeric values which could be numerically - * handled as BigDecimal or BigInteger. It helps determine what outputs - * will change if those types are supported. - */ - @Test - public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { - // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects - String str = - "{"+ - "\"numberWithDecimals\":299792.457999999984,"+ - "\"largeNumber\":12345678901234567890,"+ - "\"preciseNumber\":0.2000000000000000111,"+ - "\"largeExponent\":-23.45e2327"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - // Comes back as a double, but loses precision - assertTrue( "numberWithDecimals currently evaluates to double 299792.458", - jsonObject.get( "numberWithDecimals" ).equals( new Double( "299792.458" ) ) ); - Object obj = jsonObject.get( "largeNumber" ); - assertTrue("largeNumber currently evaluates to string", - "12345678901234567890".equals(obj)); - // comes back as a double but loses precision - assertTrue( "preciseNumber currently evaluates to double 0.2", - jsonObject.get( "preciseNumber" ).equals(new Double(0.2))); - obj = jsonObject.get( "largeExponent" ); - assertTrue("largeExponent should currently evaluates as a string", - "-23.45e2327".equals(obj)); - } - - /** - * This test documents how JSON-Java handles invalid numeric input. - */ - @Test - public void jsonInvalidNumberValues() { - // Number-notations supported by Java and invalid as JSON - String str = - "{"+ - "\"hexNumber\":-0x123,"+ - "\"tooManyZeros\":00,"+ - "\"negativeInfinite\":-Infinity,"+ - "\"negativeNaN\":-NaN,"+ - "\"negativeFraction\":-.01,"+ - "\"tooManyZerosFraction\":00.001,"+ - "\"negativeHexFloat\":-0x1.fffp1,"+ - "\"hexFloat\":0x1.0P-1074,"+ - "\"floatIdentifier\":0.1f,"+ - "\"doubleIdentifier\":0.1d"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - Object obj; - obj = jsonObject.get( "hexNumber" ); - assertFalse( "hexNumber must not be a number (should throw exception!?)", - obj instanceof Number ); - assertTrue("hexNumber currently evaluates to string", - obj.equals("-0x123")); - assertTrue( "tooManyZeros currently evaluates to string", - jsonObject.get( "tooManyZeros" ).equals("00")); - obj = jsonObject.get("negativeInfinite"); - assertTrue( "negativeInfinite currently evaluates to string", - obj.equals("-Infinity")); - obj = jsonObject.get("negativeNaN"); - assertTrue( "negativeNaN currently evaluates to string", - obj.equals("-NaN")); - assertTrue( "negativeFraction currently evaluates to double -0.01", - jsonObject.get( "negativeFraction" ).equals(new Double(-0.01))); - assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", - jsonObject.get( "tooManyZerosFraction" ).equals(new Double(0.001))); - assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875", - jsonObject.get( "negativeHexFloat" ).equals(new Double(-3.99951171875))); - assertTrue("hexFloat currently evaluates to double 4.9E-324", - jsonObject.get("hexFloat").equals(new Double(4.9E-324))); - assertTrue("floatIdentifier currently evaluates to double 0.1", - jsonObject.get("floatIdentifier").equals(new Double(0.1))); - assertTrue("doubleIdentifier currently evaluates to double 0.1", - jsonObject.get("doubleIdentifier").equals(new Double(0.1))); - } - - /** - * Tests how JSONObject get[type] handles incorrect types - */ - @Test - public void jsonObjectNonAndWrongValues() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"trueStrKey\":\"true\","+ - "\"falseStrKey\":\"false\","+ - "\"stringKey\":\"hello world!\","+ - "\"intKey\":42,"+ - "\"intStrKey\":\"43\","+ - "\"longKey\":1234567890123456789,"+ - "\"longStrKey\":\"987654321098765432\","+ - "\"doubleKey\":-23.45e7,"+ - "\"doubleStrKey\":\"00001.000\","+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{\"myKey\":\"myVal\"}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - try { - jsonObject.getBoolean("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("expecting an exception message", - "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); - } - try { - jsonObject.getBoolean("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a Boolean.". - equals(e.getMessage())); - } - try { - jsonObject.getString("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getString("trueKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"trueKey\"] not a string.". - equals(e.getMessage())); - } - try { - jsonObject.getDouble("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getDouble("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a number.". - equals(e.getMessage())); - } - try { - jsonObject.getInt("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getInt("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not an int.". - equals(e.getMessage())); - } - try { - jsonObject.getLong("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getLong("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a long.". - equals(e.getMessage())); - } - try { - jsonObject.getJSONArray("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getJSONArray("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a JSONArray.". - equals(e.getMessage())); - } - try { - jsonObject.getJSONObject("nonKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.". - equals(e.getMessage())); - } - try { - jsonObject.getJSONObject("stringKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a JSONObject.". - equals(e.getMessage())); - } - } - - /** - * This test documents an unexpected numeric behavior. - * A double that ends with .0 is parsed, serialized, then - * parsed again. On the second parse, it has become an int. - */ - @Test - public void unexpectedDoubleToIntConversion() { - String key30 = "key30"; - String key31 = "key31"; - JSONObject jsonObject = new JSONObject(); - jsonObject.put(key30, new Double(3.0)); - jsonObject.put(key31, new Double(3.1)); - - assertTrue("3.0 should remain a double", - jsonObject.getDouble(key30) == 3); - assertTrue("3.1 should remain a double", - jsonObject.getDouble(key31) == 3.1); - - // turns 3.0 into 3. - String serializedString = jsonObject.toString(); - JSONObject deserialized = new JSONObject(serializedString); - assertTrue("3.0 is now an int", deserialized.get(key30) instanceof Integer); - assertTrue("3.0 can still be interpreted as a double", - deserialized.getDouble(key30) == 3.0); - assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); - } - - /** - * Document behaviors of big numbers. Includes both JSONObject - * and JSONArray tests - */ - @Test - public void bigNumberOperations() { - /** - * JSONObject tries to parse BigInteger as a bean, but it only has - * one getter, getLowestBitSet(). The value is lost and an unhelpful - * value is stored. This should be fixed. - */ - BigInteger bigInteger = new BigInteger("123456789012345678901234567890"); - JSONObject jsonObject = new JSONObject(bigInteger); - Object obj = jsonObject.get("lowestSetBit"); - assertTrue("JSONObject only has 1 value", jsonObject.length() == 1); - assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet", - obj instanceof Integer); - assertTrue("this bigInteger lowestBitSet happens to be 1", - obj.equals(1)); - - /** - * JSONObject tries to parse BigDecimal as a bean, but it has - * no getters, The value is lost and no value is stored. - * This should be fixed. - */ - BigDecimal bigDecimal = new BigDecimal( - "123456789012345678901234567890.12345678901234567890123456789"); - jsonObject = new JSONObject(bigDecimal); - assertTrue("large bigDecimal is not stored", jsonObject.length() == 0); - - /** - * JSONObject put(String, Object) method stores and serializes - * bigInt and bigDec correctly. Nothing needs to change. - */ - jsonObject = new JSONObject(); - jsonObject.put("bigInt", bigInteger); - assertTrue("jsonObject.put() handles bigInt correctly", - jsonObject.get("bigInt").equals(bigInteger)); - assertTrue("jsonObject.getBigInteger() handles bigInt correctly", - jsonObject.getBigInteger("bigInt").equals(bigInteger)); - assertTrue("jsonObject.optBigInteger() handles bigInt correctly", - jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); - assertTrue("jsonObject serializes bigInt correctly", - jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); - jsonObject = new JSONObject(); - jsonObject.put("bigDec", bigDecimal); - assertTrue("jsonObject.put() handles bigDec correctly", - jsonObject.get("bigDec").equals(bigDecimal)); - assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", - jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); - assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", - jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); - assertTrue("jsonObject serializes bigDec correctly", - jsonObject.toString().equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - - /** - * exercise some exceptions - */ - try { - jsonObject.getBigDecimal("bigInt"); - assertTrue("expected an exeption", false); - } catch (JSONException ignored) {} - obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); - assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); - try { - jsonObject.getBigInteger("bigDec"); - assertTrue("expected an exeption", false); - } catch (JSONException ignored) {} - jsonObject.put("stringKey", "abc"); - try { - jsonObject.getBigDecimal("stringKey"); - assertTrue("expected an exeption", false); - } catch (JSONException ignored) {} - obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); - assertTrue("expected BigInteger", obj.equals(BigInteger.ONE)); - - /** - * JSONObject.numberToString() works correctly, nothing to change. - */ - String str = JSONObject.numberToString(bigInteger); - assertTrue("numberToString() handles bigInteger correctly", - str.equals("123456789012345678901234567890")); - str = JSONObject.numberToString(bigDecimal); - assertTrue("numberToString() handles bigDecimal correctly", - str.equals("123456789012345678901234567890.12345678901234567890123456789")); - - /** - * JSONObject.stringToValue() turns bigInt into an accurate string, - * and rounds bigDec. This incorrect, but users may have come to - * expect this behavior. Change would be marginally better, but - * might inconvenience users. - */ - obj = JSONObject.stringToValue(bigInteger.toString()); - assertTrue("stringToValue() turns bigInteger string into string", - obj instanceof String); - obj = JSONObject.stringToValue(bigDecimal.toString()); - assertTrue("stringToValue() changes bigDecimal string", - !obj.toString().equals(bigDecimal.toString())); - - /** - * wrap() vs put() big number behavior is now the same. - */ - // bigInt map ctor - Map map = new HashMap(); - map.put("bigInt", bigInteger); - jsonObject = new JSONObject(map); - String actualFromMapStr = jsonObject.toString(); - assertTrue("bigInt in map (or array or bean) is a string", - actualFromMapStr.equals( - "{\"bigInt\":123456789012345678901234567890}")); - // bigInt put - jsonObject = new JSONObject(); - jsonObject.put("bigInt", bigInteger); - String actualFromPutStr = jsonObject.toString(); - assertTrue("bigInt from put is a number", - actualFromPutStr.equals( - "{\"bigInt\":123456789012345678901234567890}")); - // bigDec map ctor - map = new HashMap(); - map.put("bigDec", bigDecimal); - jsonObject = new JSONObject(map); - actualFromMapStr = jsonObject.toString(); - assertTrue("bigDec in map (or array or bean) is a bigDec", - actualFromMapStr.equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - // bigDec put - jsonObject = new JSONObject(); - jsonObject.put("bigDec", bigDecimal); - actualFromPutStr = jsonObject.toString(); - assertTrue("bigDec from put is a number", - actualFromPutStr.equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - // bigInt,bigDec put - JSONArray jsonArray = new JSONArray(); - jsonArray.put(bigInteger); - jsonArray.put(bigDecimal); - actualFromPutStr = jsonArray.toString(); - assertTrue("bigInt, bigDec from put is a number", - actualFromPutStr.equals( - "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); - assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger)); - assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal)); - assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); - assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); - jsonArray.put(Boolean.TRUE); - try { - jsonArray.getBigInteger(2); - assertTrue("should not be able to get big int", false); - } catch (Exception ignored) {} - try { - jsonArray.getBigDecimal(2); - assertTrue("should not be able to get big dec", false); - } catch (Exception ignored) {} - assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); - assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); - - // bigInt,bigDec list ctor - List list = new ArrayList(); - list.add(bigInteger); - list.add(bigDecimal); - jsonArray = new JSONArray(list); - String actualFromListStr = jsonArray.toString(); - assertTrue("bigInt, bigDec in list is a bigInt, bigDec", - actualFromListStr.equals( - "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); - // bigInt bean ctor - MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); - when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); - jsonObject = new JSONObject(myBigNumberBean); - String actualFromBeanStr = jsonObject.toString(); - // can't do a full string compare because mockery adds an extra key/value - assertTrue("bigInt from bean ctor is a bigInt", - actualFromBeanStr.contains("123456789012345678901234567890")); - // bigDec bean ctor - myBigNumberBean = mock(MyBigNumberBean.class); - when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); - jsonObject = new JSONObject(myBigNumberBean); - actualFromBeanStr = jsonObject.toString(); - // can't do a full string compare because mockery adds an extra key/value - assertTrue("bigDec from bean ctor is a bigDec", - actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789")); - // bigInt,bigDec wrap() - obj = JSONObject.wrap(bigInteger); - assertTrue("wrap() returns big num",obj.equals(bigInteger)); - obj = JSONObject.wrap(bigDecimal); - assertTrue("wrap() returns string",obj.equals(bigDecimal)); - - } - - /** - * The purpose for the static method getNames() methods are not clear. - * This method is not called from within JSON-Java. Most likely - * uses are to prep names arrays for: - * JSONObject(JSONObject jo, String[] names) - * JSONObject(Object object, String names[]), - */ - @Test - public void jsonObjectNames() { - JSONObject jsonObject; - - // getNames() from null JSONObject - assertTrue("null names from null Object", - null == JSONObject.getNames((Object)null)); - - // getNames() from object with no fields - assertTrue("null names from Object with no fields", - null == JSONObject.getNames(new MyJsonString())); - - // getNames from new JSONOjbect - jsonObject = new JSONObject(); - String [] names = JSONObject.getNames(jsonObject); - assertTrue("names should be null", names == null); - - - // getNames() from empty JSONObject - String emptyStr = "{}"; - jsonObject = new JSONObject(emptyStr); - assertTrue("empty JSONObject should have null names", - null == JSONObject.getNames(jsonObject)); - - // getNames() from JSONObject - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "}"; - jsonObject = new JSONObject(str); - names = JSONObject.getNames(jsonObject); - JSONArray jsonArray = new JSONArray(names); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - List docList = JsonPath.read(doc, "$"); - assertTrue("expected 3 items", docList.size() == 3); - assertTrue( - "expected to find trueKey", - ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); - assertTrue( - "expected to find falseKey", - ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); - assertTrue( - "expected to find stringKey", - ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); - - /** - * getNames() from an enum with properties has an interesting result. - * It returns the enum values, not the selected enum properties - */ - MyEnumField myEnumField = MyEnumField.VAL1; - names = JSONObject.getNames(myEnumField); - - // validate JSON - jsonArray = new JSONArray(names); - doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - docList = JsonPath.read(doc, "$"); - assertTrue("expected 3 items", docList.size() == 3); - assertTrue( - "expected to find VAL1", - ((List) JsonPath.read(doc, "$[?(@=='VAL1')]")).size() == 1); - assertTrue( - "expected to find VAL2", - ((List) JsonPath.read(doc, "$[?(@=='VAL2')]")).size() == 1); - assertTrue( - "expected to find VAL3", - ((List) JsonPath.read(doc, "$[?(@=='VAL3')]")).size() == 1); - - /** - * A bean is also an object. But in order to test the static - * method getNames(), this particular bean needs some public - * data members. - */ - MyPublicClass myPublicClass = new MyPublicClass(); - names = JSONObject.getNames(myPublicClass); - - // validate JSON - jsonArray = new JSONArray(names); - doc = Configuration.defaultConfiguration().jsonProvider() - .parse(jsonArray.toString()); - docList = JsonPath.read(doc, "$"); - assertTrue("expected 2 items", docList.size() == 2); - assertTrue( - "expected to find publicString", - ((List) JsonPath.read(doc, "$[?(@=='publicString')]")).size() == 1); - assertTrue( - "expected to find publicInt", - ((List) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1); - } - - /** - * Populate a JSONArray from an empty JSONObject names() method. - * It should be empty. - */ - @Test - public void emptyJsonObjectNamesToJsonAray() { - JSONObject jsonObject = new JSONObject(); - JSONArray jsonArray = jsonObject.names(); - assertTrue("jsonArray should be null", jsonArray == null); - } - - /** - * Populate a JSONArray from a JSONObject names() method. - * Confirm that it contains the expected names. - */ - @Test - public void jsonObjectNamesToJsonAray() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"stringKey\":\"hello world!\","+ - "}"; - - JSONObject jsonObject = new JSONObject(str); - JSONArray jsonArray = jsonObject.names(); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected to find trueKey", ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); - assertTrue("expected to find falseKey", ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); - assertTrue("expected to find stringKey", ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); - } - - /** - * Exercise the JSONObject increment() method. - */ - @Test - public void jsonObjectIncrement() { - String str = - "{"+ - "\"keyLong\":9999999991,"+ - "\"keyDouble\":1.1"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.increment("keyInt"); - jsonObject.increment("keyInt"); - jsonObject.increment("keyLong"); - jsonObject.increment("keyDouble"); - jsonObject.increment("keyInt"); - jsonObject.increment("keyLong"); - jsonObject.increment("keyDouble"); - /** - * JSONObject constructor won't handle these types correctly, but - * adding them via put works. - */ - jsonObject.put("keyFloat", new Float(1.1)); - jsonObject.put("keyBigInt", new BigInteger("123456789123456789123456789123456780")); - jsonObject.put("keyBigDec", new BigDecimal("123456789123456789123456789123456780.1")); - jsonObject.increment("keyFloat"); - jsonObject.increment("keyFloat"); - jsonObject.increment("keyBigInt"); - jsonObject.increment("keyBigDec"); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/keyInt"))); - assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(jsonObject.query("/keyLong"))); - assertTrue("expected 3.1", Double.valueOf(3.1).equals(jsonObject.query("/keyDouble"))); - assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(jsonObject.query("/keyBigInt"))); - assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(jsonObject.query("/keyBigDec"))); - - /** - * Should work the same way on any platform! @see https://docs.oracle - * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is the - * effect of a float to double conversion and is inherent to the - * shortcomings of the IEEE 754 format, when converting 32-bit into - * double-precision 64-bit. Java type-casts float to double. A 32 bit - * float is type-casted to 64 bit double by simply appending zero-bits - * to the mantissa (and extended the signed exponent by 3 bits.) and - * there is no way to obtain more information than it is stored in the - * 32-bits float. - * - * Like 1/3 cannot be represented as base10 number because it is - * periodically, 1/5 (for example) cannot be represented as base2 number - * since it is periodically in base2 (take a look at - * http://www.h-schmidt.net/FloatConverter/) The same happens to 3.1, - * that decimal number (base10 representation) is periodic in base2 - * representation, therefore appending zero-bits is inaccurate. Only - * repeating the periodically occuring bits (0110) would be a proper - * conversion. However one cannot detect from a 32 bit IEE754 - * representation which bits would "repeat infinitely", since the - * missing bits would not fit into the 32 bit float, i.e. the - * information needed simply is not there! - */ - assertTrue("expected 3.0999999046325684", Double.valueOf(3.0999999046325684).equals(jsonObject.query("/keyFloat"))); - - /** - * float f = 3.1f; double df = (double) f; double d = 3.1d; - * System.out.println - * (Integer.toBinaryString(Float.floatToRawIntBits(f))); - * System.out.println - * (Long.toBinaryString(Double.doubleToRawLongBits(df))); - * System.out.println - * (Long.toBinaryString(Double.doubleToRawLongBits(d))); - * - * - Float: - * seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm - * 1000000010001100110011001100110 - * - Double - * seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - * 10000000 10001100110011001100110 - * 100000000001000110011001100110011000000000000000000000000000000 - * 100000000001000110011001100110011001100110011001100110011001101 - */ - - /** - * Examples of well documented but probably unexpected behavior in - * java / with 32-bit float to 64-bit float conversion. - */ - assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d ); - assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d ); - Double d1 = new Double( 1.1f ); - Double d2 = new Double( "1.1f" ); - assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); - - assertTrue( "Correctly converting float to double via base10 (string) representation!", new Double( 3.1d ).equals( new Double( new Float( 3.1f ).toString() ) ) ); - - // Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject - JSONObject jo = new JSONObject(); - jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double - assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); - - JSONObject inc = new JSONObject(); - inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) - assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); - inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! - // this.put(key, (Float) value + 1); - // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. - // 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects! - // 3. A float+float operation will be performed and results into a float primitive. - // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method - // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa - assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Double ); - // correct implementation (with change of behavior) would be: - // this.put(key, new Float((Float) value + 1)); - // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not - // really in the the scope of a JSON-library (IMHO.) - - } - - /** - * Exercise JSONObject numberToString() method - */ - @Test - public void jsonObjectNumberToString() { - String str; - Double dVal; - Integer iVal = 1; - str = JSONObject.numberToString(iVal); - assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); - dVal = 12.34; - str = JSONObject.numberToString(dVal); - assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); - dVal = 12.34e27; - str = JSONObject.numberToString(dVal); - assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); - // trailing .0 is truncated, so it doesn't quite match toString() - dVal = 5000000.0000000; - str = JSONObject.numberToString(dVal); - assertTrue("expected 5000000 actual "+str, str.equals("5000000")); - } - - /** - * Exercise JSONObject put() and similar() methods - */ - @Test - public void jsonObjectPut() { - String expectedStr = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{"+ - "\"myKey1\":\"myVal1\","+ - "\"myKey2\":\"myVal2\","+ - "\"myKey3\":\"myVal3\","+ - "\"myKey4\":\"myVal4\""+ - "}"+ - "}"; - JSONObject jsonObject = new JSONObject(); - jsonObject.put("trueKey", true); - jsonObject.put("falseKey", false); - Integer [] intArray = { 0, 1, 2 }; - jsonObject.put("arrayKey", Arrays.asList(intArray)); - Map myMap = new HashMap(); - myMap.put("myKey1", "myVal1"); - myMap.put("myKey2", "myVal2"); - myMap.put("myKey3", "myVal3"); - myMap.put("myKey4", "myVal4"); - jsonObject.put("objectKey", myMap); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); - assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); - assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); - assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); - assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); - assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); - assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); - - jsonObject.remove("trueKey"); - JSONObject expectedJsonObject = new JSONObject(expectedStr); - assertTrue("unequal jsonObjects should not be similar", - !jsonObject.similar(expectedJsonObject)); - assertTrue("jsonObject should not be similar to jsonArray", - !jsonObject.similar(new JSONArray())); - - String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; - String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; - JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); - JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); - assertTrue("different values should not be similar", - !aCompareValueJsonObject.similar(bCompareValueJsonObject)); - - String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; - String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; - JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); - JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); - assertTrue("different nested JSONObjects should not be similar", - !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); - - String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; - String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; - JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); - JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); - assertTrue("different nested JSONArrays should not be similar", - !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); - } - - /** - * Exercise JSONObject toString() method - */ - @Test - public void jsonObjectToString() { - String str = - "{"+ - "\"trueKey\":true,"+ - "\"falseKey\":false,"+ - "\"arrayKey\":[0,1,2],"+ - "\"objectKey\":{"+ - "\"myKey1\":\"myVal1\","+ - "\"myKey2\":\"myVal2\","+ - "\"myKey3\":\"myVal3\","+ - "\"myKey4\":\"myVal4\""+ - "}"+ - "}"; - JSONObject jsonObject = new JSONObject(str); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); - assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); - assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); - assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); - assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); - assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); - assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); - } - - /** - * Exercise JSONObject toString() method with various indent levels. - */ - @Test - public void jsonObjectToStringIndent() { - String jsonObject0Str = - "{"+ - "\"key1\":" + - "[1,2," + - "{\"key3\":true}" + - "],"+ - "\"key2\":" + - "{\"key1\":\"val1\",\"key2\":" + - "{\"key2\":\"val2\"}" + - "},"+ - "\"key3\":" + - "[" + - "[1,2.1]" + - "," + - "[null]" + - "]"+ - "}"; - - String jsonObject1Str = - "{\n" + - " \"key1\": [\n" + - " 1,\n" + - " 2,\n" + - " {\"key3\": true}\n" + - " ],\n" + - " \"key2\": {\n" + - " \"key1\": \"val1\",\n" + - " \"key2\": {\"key2\": \"val2\"}\n" + - " },\n" + - " \"key3\": [\n" + - " [\n" + - " 1,\n" + - " 2.1\n" + - " ],\n" + - " [null]\n" + - " ]\n" + - "}"; - String jsonObject4Str = - "{\n" + - " \"key1\": [\n" + - " 1,\n" + - " 2,\n" + - " {\"key3\": true}\n" + - " ],\n" + - " \"key2\": {\n" + - " \"key1\": \"val1\",\n" + - " \"key2\": {\"key2\": \"val2\"}\n" + - " },\n" + - " \"key3\": [\n" + - " [\n" + - " 1,\n" + - " 2.1\n" + - " ],\n" + - " [null]\n" + - " ]\n" + - "}"; - JSONObject jsonObject = new JSONObject(jsonObject0Str); - assertEquals(jsonObject0Str, jsonObject.toString()); - assertEquals(jsonObject0Str, jsonObject.toString(0)); - assertEquals(jsonObject1Str, jsonObject.toString(1)); - assertEquals(jsonObject4Str, jsonObject.toString(4)); - } - - /** - * Explores how JSONObject handles maps. Insert a string/string map - * as a value in a JSONObject. It will remain a map. Convert the - * JSONObject to string, then create a new JSONObject from the string. - * In the new JSONObject, the value will be stored as a nested JSONObject. - * Confirm that map and nested JSONObject have the same contents. - */ - @Test - public void jsonObjectToStringSuppressWarningOnCastToMap() { - JSONObject jsonObject = new JSONObject(); - Map map = new HashMap<>(); - map.put("abc", "def"); - jsonObject.put("key", map); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 1 key item", ((Map)(JsonPath.read(doc, "$.key"))).size() == 1); - assertTrue("expected def", "def".equals(jsonObject.query("/key/abc"))); - } - - /** - * Explores how JSONObject handles collections. Insert a string collection - * as a value in a JSONObject. It will remain a collection. Convert the - * JSONObject to string, then create a new JSONObject from the string. - * In the new JSONObject, the value will be stored as a nested JSONArray. - * Confirm that collection and nested JSONArray have the same contents. - */ - @Test - public void jsonObjectToStringSuppressWarningOnCastToCollection() { - JSONObject jsonObject = new JSONObject(); - Collection collection = new ArrayList(); - collection.add("abc"); - // ArrayList will be added as an object - jsonObject.put("key", collection); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 1 key item", ((List)(JsonPath.read(doc, "$.key"))).size() == 1); - assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0"))); - } - - /** - * Exercises the JSONObject.valueToString() method for various types - */ - @Test - public void valueToString() { - - assertTrue("null valueToString() incorrect", - "null".equals(JSONObject.valueToString(null))); - MyJsonString jsonString = new MyJsonString(); - assertTrue("jsonstring valueToString() incorrect", - "my string".equals(JSONObject.valueToString(jsonString))); - assertTrue("boolean valueToString() incorrect", - "true".equals(JSONObject.valueToString(Boolean.TRUE))); - assertTrue("non-numeric double", - "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); - String jsonObjectStr = - "{"+ - "\"key1\":\"val1\","+ - "\"key2\":\"val2\","+ - "\"key3\":\"val3\""+ - "}"; - JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("jsonObject valueToString() incorrect", - JSONObject.valueToString(jsonObject).equals(jsonObject.toString())); - String jsonArrayStr = - "[1,2,3]"; - JSONArray jsonArray = new JSONArray(jsonArrayStr); - assertTrue("jsonArray valueToString() incorrect", - JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); - Map map = new HashMap(); - map.put("key1", "val1"); - map.put("key2", "val2"); - map.put("key3", "val3"); - assertTrue("map valueToString() incorrect", - jsonObject.toString().equals(JSONObject.valueToString(map))); - Collection collection = new ArrayList(); - collection.add(new Integer(1)); - collection.add(new Integer(2)); - collection.add(new Integer(3)); - assertTrue("collection valueToString() expected: "+ - jsonArray.toString()+ " actual: "+ - JSONObject.valueToString(collection), - jsonArray.toString().equals(JSONObject.valueToString(collection))); - Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; - assertTrue("array valueToString() incorrect", - jsonArray.toString().equals(JSONObject.valueToString(array))); - } - - /** - * Confirm that https://github.com/douglascrockford/JSON-java/issues/167 is fixed. - * The following code was throwing a ClassCastException in the - * JSONObject(Map) constructor - */ - @Test - public void valueToStringConfirmException() { - Map myMap = new HashMap(); - myMap.put(1, "myValue"); - // this is the test, it should not throw an exception - String str = JSONObject.valueToString(myMap); - // confirm result, just in case - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1"))); - } - - /** - * Exercise the JSONObject wrap() method. Sometimes wrap() will change - * the object being wrapped, other times not. The purpose of wrap() is - * to ensure the value is packaged in a way that is compatible with how - * a JSONObject value or JSONArray value is supposed to be stored. - */ - @Test - public void wrapObject() { - // wrap(null) returns NULL - assertTrue("null wrap() incorrect", - JSONObject.NULL == JSONObject.wrap(null)); - - // wrap(Integer) returns Integer - Integer in = new Integer(1); - assertTrue("Integer wrap() incorrect", - in == JSONObject.wrap(in)); - - /** - * This test is to document the preferred behavior if BigDecimal is - * supported. Previously bd returned as a string, since it - * is recognized as being a Java package class. Now with explicit - * support for big numbers, it remains a BigDecimal - */ - Object bdWrap = JSONObject.wrap(BigDecimal.ONE); - assertTrue("BigDecimal.ONE evaluates to ONE", - bdWrap.equals(BigDecimal.ONE)); - - // wrap JSONObject returns JSONObject - String jsonObjectStr = - "{"+ - "\"key1\":\"val1\","+ - "\"key2\":\"val2\","+ - "\"key3\":\"val3\""+ - "}"; - JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("JSONObject wrap() incorrect", - jsonObject == JSONObject.wrap(jsonObject)); - - // wrap collection returns JSONArray - Collection collection = new ArrayList(); - collection.add(new Integer(1)); - collection.add(new Integer(2)); - collection.add(new Integer(3)); - JSONArray jsonArray = (JSONArray) (JSONObject.wrap(collection)); - - // validate JSON - Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); - - // wrap Array returns JSONArray - Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; - JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); - - // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); - - // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); - - // wrap map returns JSONObject - Map map = new HashMap(); - map.put("key1", "val1"); - map.put("key2", "val2"); - map.put("key3", "val3"); - JSONObject mapJsonObject = (JSONObject) (JSONObject.wrap(map)); - - // validate JSON - doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString()); - assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1"))); - assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2"))); - assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3"))); - } - - - /** - * RFC 7159 defines control characters to be U+0000 through U+001F. This test verifies that the parser is checking for these in expected ways. - */ - @Test - public void jsonObjectParseControlCharacters(){ - for(int i = 0;i<=0x001f;i++){ - final String charString = String.valueOf((char)i); - final String source = "{\"key\":\""+charString+"\"}"; - try { - JSONObject jo = new JSONObject(source); - assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key"))); - } catch (JSONException ex) { - assertTrue("Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error", - i=='\0' || i=='\n' || i=='\r' - ); - } - } - } - - /** - * Explore how JSONObject handles parsing errors. - */ - @Test - public void jsonObjectParsingErrors() { - try { - // does not start with '{' - String str = "abc"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "A JSONObject text must begin with '{' at 1 [character 2 line 1]". - equals(e.getMessage())); - } - try { - // does not end with '}' - String str = "{"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "A JSONObject text must end with '}' at 2 [character 3 line 1]". - equals(e.getMessage())); - } - try { - // key with no ':' - String str = "{\"myKey\" = true}"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Expected a ':' after a key at 10 [character 11 line 1]". - equals(e.getMessage())); - } - try { - // entries with no ',' separator - String str = "{\"myKey\":true \"myOtherKey\":false}"; - new JSONObject(str); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Expected a ',' or '}' at 15 [character 16 line 1]". - equals(e.getMessage())); - } - try { - // append to wrong key - String str = "{\"myKey\":true, \"myOtherKey\":false}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.append("myKey", "hello"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[myKey] is not a JSONArray.". - equals(e.getMessage())); - } - try { - // increment wrong key - String str = "{\"myKey\":true, \"myOtherKey\":false}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.increment("myKey"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Unable to increment [\"myKey\"].". - equals(e.getMessage())); - } - try { - // invalid key - String str = "{\"myKey\":true, \"myOtherKey\":false}"; - JSONObject jsonObject = new JSONObject(str); - jsonObject.get(null); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Null key.". - equals(e.getMessage())); - } - try { - // invalid numberToString() - JSONObject.numberToString((Number)null); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Null pointer". - equals(e.getMessage())); - } - try { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, 0); - assertTrue("Expected an exception", false); - } catch (NullPointerException ignored) { - } - try { - // multiple putOnce key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.putOnce("hello", "world"); - jsonObject.putOnce("hello", "world!"); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("", true); - } - try { - // test validity of invalid double - JSONObject.testValidity(Double.NaN); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("", true); - } - try { - // test validity of invalid float - JSONObject.testValidity(Float.NEGATIVE_INFINITY); - assertTrue("Expected an exception", false); - } catch (JSONException e) { - assertTrue("", true); - } - } - - /** - * Confirm behavior when putOnce() is called with null parameters - */ - @Test - public void jsonObjectPutOnceNull() { - JSONObject jsonObject = new JSONObject(); - jsonObject.putOnce(null, null); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); - } - - /** - * Exercise JSONObject opt(key, default) method. - */ - @Test - public void jsonObjectOptDefault() { - - String str = "{\"myKey\": \"myval\", \"hiKey\": null}"; - JSONObject jsonObject = new JSONObject(str); - - assertTrue("optBigDecimal() should return default BigDecimal", - BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); - assertTrue("optBigInteger() should return default BigInteger", - BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); - assertTrue("optBoolean() should return default boolean", - jsonObject.optBoolean("myKey", true)); - assertTrue("optInt() should return default int", - 42 == jsonObject.optInt("myKey", 42)); - assertTrue("optEnum() should return default Enum", - MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); - assertTrue("optJSONArray() should return null ", - null==jsonObject.optJSONArray("myKey")); - assertTrue("optJSONObject() should return null ", - null==jsonObject.optJSONObject("myKey")); - assertTrue("optLong() should return default long", - 42 == jsonObject.optLong("myKey", 42)); - assertTrue("optDouble() should return default double", - 42.3 == jsonObject.optDouble("myKey", 42.3)); - assertTrue("optString() should return default string", - "hi".equals(jsonObject.optString("hiKey", "hi"))); - } - - /** - * Exercise JSONObject opt(key, default) method when the key doesn't exist. - */ - @Test - public void jsonObjectOptNoKey() { - - JSONObject jsonObject = new JSONObject(); - - assertTrue("optBigDecimal() should return default BigDecimal", - BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); - assertTrue("optBigInteger() should return default BigInteger", - BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); - assertTrue("optBoolean() should return default boolean", - jsonObject.optBoolean("myKey", true)); - assertTrue("optInt() should return default int", - 42 == jsonObject.optInt("myKey", 42)); - assertTrue("optEnum() should return default Enum", - MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); - assertTrue("optJSONArray() should return null ", - null==jsonObject.optJSONArray("myKey")); - assertTrue("optJSONObject() should return null ", - null==jsonObject.optJSONObject("myKey")); - assertTrue("optLong() should return default long", - 42 == jsonObject.optLong("myKey", 42)); - assertTrue("optDouble() should return default double", - 42.3 == jsonObject.optDouble("myKey", 42.3)); - assertTrue("optString() should return default string", - "hi".equals(jsonObject.optString("hiKey", "hi"))); - } - - /** - * Verifies that the opt methods properly convert string values. - */ - @Test - public void jsonObjectOptStringConversion() { - JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\"}"); - assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true); - assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false); - assertTrue("unexpected optInt value",jo.optInt("int",0)==123); - assertTrue("unexpected optLong value",jo.optLong("int",0)==123); - assertTrue("unexpected optDouble value",jo.optDouble("int",0.0)==123.0); - assertTrue("unexpected optBigInteger value",jo.optBigInteger("int",BigInteger.ZERO).compareTo(new BigInteger("123"))==0); - assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); - - } - - /** - * Confirm behavior when JSONObject put(key, null object) is called - */ - @Test - public void jsonObjectputNull() { - - // put null should remove the item. - String str = "{\"myKey\": \"myval\"}"; - JSONObject jsonObjectRemove = new JSONObject(str); - jsonObjectRemove.remove("myKey"); - - JSONObject jsonObjectPutNull = new JSONObject(str); - jsonObjectPutNull.put("myKey", (Object) null); - - // validate JSON - assertTrue("jsonObject should be empty", jsonObjectRemove.length() == 0 - && jsonObjectPutNull.length() == 0); - } - - /** - * Exercise JSONObject quote() method - * This purpose of quote() is to ensure that for strings with embedded - * quotes, the quotes are properly escaped. - */ - @Test - public void jsonObjectQuote() { - String str; - str = ""; - String quotedStr; - quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found "+quotedStr, - "\"\"".equals(quotedStr)); - str = "\"\""; - quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found "+quotedStr, - "\"\\\"\\\"\"".equals(quotedStr)); - str = "null and null will be emitted as "" - */ - String sJONull = XML.toString(jsonObjectJONull); - assertTrue("JSONObject.NULL should emit a null value", - "null".equals(sJONull)); - String sNull = XML.toString(jsonObjectNull); - assertTrue("null should emit an empty string", "".equals(sNull)); - } - - @Test(expected = JSONPointerException.class) - public void queryWithNoResult() { - new JSONObject().query("/a/b"); - } - - @Test - public void optQueryWithNoResult() { - assertNull(new JSONObject().optQuery("/a/b")); - } - - @Test(expected = IllegalArgumentException.class) - public void optQueryWithSyntaxError() { - new JSONObject().optQuery("invalid"); - } - - @Test(expected = JSONException.class) - public void invalidEscapeSequence() { - String json = "{ \"\\url\": \"value\" }"; - new JSONObject(json); - } - - /** - * Exercise JSONObject toMap() method. - */ - @Test - public void toMap() { - String jsonObjectStr = - "{" + - "\"key1\":" + - "[1,2," + - "{\"key3\":true}" + - "]," + - "\"key2\":" + - "{\"key1\":\"val1\",\"key2\":" + - "{\"key2\":null}," + - "\"key3\":42" + - "}," + - "\"key3\":" + - "[" + - "[\"value1\",2.1]" + - "," + - "[null]" + - "]" + - "}"; - - JSONObject jsonObject = new JSONObject(jsonObjectStr); - Map map = jsonObject.toMap(); - - assertTrue("Map should not be null", map != null); - assertTrue("Map should have 3 elements", map.size() == 3); - - List key1List = (List)map.get("key1"); - assertTrue("key1 should not be null", key1List != null); - assertTrue("key1 list should have 3 elements", key1List.size() == 3); - assertTrue("key1 value 1 should be 1", key1List.get(0).equals(Integer.valueOf(1))); - assertTrue("key1 value 2 should be 2", key1List.get(1).equals(Integer.valueOf(2))); - - Map key1Value3Map = (Map)key1List.get(2); - assertTrue("Map should not be null", key1Value3Map != null); - assertTrue("Map should have 1 element", key1Value3Map.size() == 1); - assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); - - Map key2Map = (Map)map.get("key2"); - assertTrue("key2 should not be null", key2Map != null); - assertTrue("key2 map should have 3 elements", key2Map.size() == 3); - assertTrue("key2 map key 1 should be val1", key2Map.get("key1").equals("val1")); - assertTrue("key2 map key 3 should be 42", key2Map.get("key3").equals(Integer.valueOf(42))); - - Map key2Val2Map = (Map)key2Map.get("key2"); - assertTrue("key2 map key 2 should not be null", key2Val2Map != null); - assertTrue("key2 map key 2 should have an entry", key2Val2Map.containsKey("key2")); - assertTrue("key2 map key 2 value should be null", key2Val2Map.get("key2") == null); - - List key3List = (List)map.get("key3"); - assertTrue("key3 should not be null", key3List != null); - assertTrue("key3 list should have 3 elements", key3List.size() == 2); - - List key3Val1List = (List)key3List.get(0); - assertTrue("key3 list val 1 should not be null", key3Val1List != null); - assertTrue("key3 list val 1 should have 2 elements", key3Val1List.size() == 2); - assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); - assertTrue("key3 list val 1 list element 2 should be 2.1", key3Val1List.get(1).equals(Double.valueOf("2.1"))); - - List key3Val2List = (List)key3List.get(1); - assertTrue("key3 list val 2 should not be null", key3Val2List != null); - assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1); - assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null); - - // Assert that toMap() is a deep copy - jsonObject.getJSONArray("key3").getJSONArray(0).put(0, "still value 1"); - assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); - - // assert that the new map is mutable - assertTrue("Removing a key should succeed", map.remove("key3") != null); - assertTrue("Map should have 2 elements", map.size() == 2); - - } -} +package org.json.junit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import org.json.CDL; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONPointerException; +import org.json.XML; +import org.junit.Test; + +import com.jayway.jsonpath.Configuration; +import com.jayway.jsonpath.JsonPath; + +/** + * JSONObject, along with JSONArray, are the central classes of the reference app. + * All of the other classes interact with them, and JSON functionality would + * otherwise be impossible. + */ +public class JSONObjectTest { + + /** + * JSONObject built from a bean, but only using a null value. + * Nothing good is expected to happen. + * Expects NullPointerException + */ + @Test(expected=NullPointerException.class) + public void jsonObjectByNullBean() { + assertNull("Expected an exception",new JSONObject((MyBean)null)); + } + + /** + * The JSON parser is permissive of unambiguous unquoted keys and values. + * Such JSON text should be allowed, even if it does not strictly conform + * to the spec. However, after being parsed, toString() should emit strictly + * conforming JSON text. + */ + @Test + public void unquotedText() { + String str = "{key1:value1, key2:42}"; + JSONObject jsonObject = new JSONObject(str); + String textStr = jsonObject.toString(); + assertTrue("expected key1", textStr.contains("\"key1\"")); + assertTrue("expected value1", textStr.contains("\"value1\"")); + assertTrue("expected key2", textStr.contains("\"key2\"")); + assertTrue("expected 42", textStr.contains("42")); + } + + @Test + public void testLongFromString(){ + String str = "26315000000253009"; + JSONObject json = new JSONObject(); + json.put("key", str); + + final Object actualKey = json.opt("key"); + assert str.equals(actualKey) : "Incorrect key value. Got " + actualKey + + " expected " + str; + + final long actualLong = json.optLong("key"); + assert actualLong != 0 : "Unable to extract long value for string " + str; + assert 26315000000253009L == actualLong : "Incorrect key value. Got " + + actualLong + " expected " + str; + + final String actualString = json.optString("key"); + assert str.equals(actualString) : "Incorrect key value. Got " + + actualString + " expected " + str; + } + + /** + * A JSONObject can be created with no content + */ + @Test + public void emptyJsonObject() { + JSONObject jsonObject = new JSONObject(); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + /** + * A JSONObject can be created from another JSONObject plus a list of names. + * In this test, some of the starting JSONObject keys are not in the + * names list. + */ + @Test + public void jsonObjectByNames() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"nullKey\":null,"+ + "\"stringKey\":\"hello world!\","+ + "\"escapeStringKey\":\"h\be\tllo w\u1234orld!\","+ + "\"intKey\":42,"+ + "\"doubleKey\":-23.45e67"+ + "}"; + String[] keys = {"falseKey", "stringKey", "nullKey", "doubleKey"}; + JSONObject jsonObject = new JSONObject(str); + + // validate JSON + JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey"))); + assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObjectByName.query("/doubleKey"))); + } + + /** + * JSONObjects can be built from a Map. + * In this test the map is null. + * the JSONObject(JsonTokener) ctor is not tested directly since it already + * has full coverage from other tests. + */ + @Test + public void jsonObjectByNullMap() { + Map map = null; + JSONObject jsonObject = new JSONObject(map); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + /** + * JSONObjects can be built from a Map. + * In this test all of the map entries are valid JSON types. + */ + @Test + public void jsonObjectByMap() { + Map map = new HashMap(); + map.put("trueKey", new Boolean(true)); + map.put("falseKey", new Boolean(false)); + map.put("stringKey", "hello world!"); + map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); + map.put("intKey", new Long(42)); + map.put("doubleKey", new Double(-23.45e67)); + JSONObject jsonObject = new JSONObject(map); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); + } + + /** + * Verifies that the constructor has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyConstructor() { + + final JSONObject expected = new JSONObject("{\"myKey\":10}"); + + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(myRawC); + + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONObject jaStrObj = new JSONObject(myCStrObj); + + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONObject jaStrInt = new JSONObject(myCStrInt); + + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONObject jaObjObj = new JSONObject(myCObjObj); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); + } + + /** + * Tests Number serialization. + */ + @Test + public void verifyNumberOutput(){ + /** + * MyNumberContainer is a POJO, so call JSONObject(bean), + * which builds a map of getter names/values + * The only getter is getMyNumber (key=myNumber), + * whose return value is MyNumber. MyNumber extends Number, + * but is not recognized as such by wrap() per current + * implementation, so wrap() returns the default new JSONObject(bean). + * The only getter is getNumber (key=number), whose return value is + * BigDecimal(42). + */ + JSONObject jsonObject = new JSONObject(new MyNumberContainer()); + String actual = jsonObject.toString(); + String expected = "{\"myNumber\":{\"number\":42}}"; + assertEquals("Not Equal", expected , actual); + + /** + * JSONObject.put() handles objects differently than the + * bean constructor. Where the bean ctor wraps objects before + * placing them in the map, put() inserts the object without wrapping. + * In this case, a MyNumber instance is the value. + * The MyNumber.toString() method is responsible for + * returning a reasonable value: the string '42'. + */ + jsonObject = new JSONObject(); + jsonObject.put("myNumber", new MyNumber()); + actual = jsonObject.toString(); + expected = "{\"myNumber\":42}"; + assertEquals("Not Equal", expected , actual); + + /** + * Calls the JSONObject(Map) ctor, which calls wrap() for values. + * AtomicInteger is a Number, but is not recognized by wrap(), per + * current implementation. However, the type is + * 'java.util.concurrent.atomic', so due to the 'java' prefix, + * wrap() inserts the value as a string. That is why 42 comes back + * wrapped in quotes. + */ + jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); + actual = jsonObject.toString(); + expected = "{\"myNumber\":\"42\"}"; + assertEquals("Not Equal", expected , actual); + + /** + * JSONObject.put() inserts the AtomicInteger directly into the + * map not calling wrap(). In toString()->write()->writeValue(), + * AtomicInteger is recognized as a Number, and converted via + * numberToString() into the unquoted string '42'. + */ + jsonObject = new JSONObject(); + jsonObject.put("myNumber", new AtomicInteger(42)); + actual = jsonObject.toString(); + expected = "{\"myNumber\":42}"; + assertEquals("Not Equal", expected , actual); + + /** + * Calls the JSONObject(Map) ctor, which calls wrap() for values. + * Fraction is a Number, but is not recognized by wrap(), per + * current implementation. As a POJO, Fraction is handled as a + * bean and inserted into a contained JSONObject. It has 2 getters, + * for numerator and denominator. + */ + jsonObject = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2))); + assertEquals(1, jsonObject.length()); + assertEquals(2, ((JSONObject)(jsonObject.get("myNumber"))).length()); + assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject.query("/myNumber/numerator")); + assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject.query("/myNumber/denominator")); + + /** + * JSONObject.put() inserts the Fraction directly into the + * map not calling wrap(). In toString()->write()->writeValue(), + * Fraction is recognized as a Number, and converted via + * numberToString() into the unquoted string '4/2'. But the + * BigDecimal sanity check fails, so writeValue() defaults + * to returning a safe JSON quoted string. Pretty slick! + */ + jsonObject = new JSONObject(); + jsonObject.put("myNumber", new Fraction(4,2)); + actual = jsonObject.toString(); + expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed + assertEquals("Not Equal", expected , actual); + } + + /** + * Verifies that the put Collection has backwards compatibility with RAW types pre-java5. + */ + @Test + public void verifyPutCollection() { + + final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); + + @SuppressWarnings("rawtypes") + Collection myRawC = Collections.singleton(Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(); + jaRaw.put("myCollection", myRawC); + + Collection myCObj = Collections.singleton((Object) Integer + .valueOf(10)); + JSONObject jaObj = new JSONObject(); + jaObj.put("myCollection", myCObj); + + Collection myCInt = Collections.singleton(Integer + .valueOf(10)); + JSONObject jaInt = new JSONObject(); + jaInt.put("myCollection", myCInt); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaInt)); + } + + + /** + * Verifies that the put Map has backwards compatability with RAW types pre-java5. + */ + @Test + public void verifyPutMap() { + + final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); + + @SuppressWarnings("rawtypes") + Map myRawC = Collections.singletonMap("myKey", Integer.valueOf(10)); + JSONObject jaRaw = new JSONObject(); + jaRaw.put("myMap", myRawC); + + Map myCStrObj = Collections.singletonMap("myKey", + (Object) Integer.valueOf(10)); + JSONObject jaStrObj = new JSONObject(); + jaStrObj.put("myMap", myCStrObj); + + Map myCStrInt = Collections.singletonMap("myKey", + Integer.valueOf(10)); + JSONObject jaStrInt = new JSONObject(); + jaStrInt.put("myMap", myCStrInt); + + Map myCObjObj = Collections.singletonMap((Object) "myKey", + (Object) Integer.valueOf(10)); + JSONObject jaObjObj = new JSONObject(); + jaObjObj.put("myMap", myCObjObj); + + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaRaw)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrObj)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaStrInt)); + assertTrue( + "The RAW Collection should give me the same as the Typed Collection", + expected.similar(jaObjObj)); + } + + + /** + * JSONObjects can be built from a Map. + * In this test the map entries are not valid JSON types. + * The actual conversion is kind of interesting. + */ + @Test + public void jsonObjectByMapWithUnsupportedValues() { + Map jsonMap = new HashMap(); + // Just insert some random objects + jsonMap.put("key1", new CDL()); + jsonMap.put("key2", new Exception()); + + JSONObject jsonObject = new JSONObject(jsonMap); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected 0 key1 items", ((Map)(JsonPath.read(doc, "$.key1"))).size() == 0); + assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2"))); + } + + /** + * JSONObjects can be built from a Map. + * In this test one of the map values is null + */ + @Test + public void jsonObjectByMapWithNullValue() { + Map map = new HashMap(); + map.put("trueKey", new Boolean(true)); + map.put("falseKey", new Boolean(false)); + map.put("stringKey", "hello world!"); + map.put("nullKey", null); + map.put("escapeStringKey", "h\be\tllo w\u1234orld!"); + map.put("intKey", new Long(42)); + map.put("doubleKey", new Double(-23.45e67)); + JSONObject jsonObject = new JSONObject(map); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); + assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); + assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); + assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); + } + + /** + * JSONObject built from a bean. In this case all but one of the + * bean getters return valid JSON types + */ + @SuppressWarnings("boxing") + @Test + public void jsonObjectByBean() { + /** + * Default access classes have to be mocked since JSONObject, which is + * not in the same package, cannot call MyBean methods by reflection. + */ + MyBean myBean = mock(MyBean.class); + when(myBean.getDoubleKey()).thenReturn(-23.45e7); + when(myBean.getIntKey()).thenReturn(42); + when(myBean.getStringKey()).thenReturn("hello world!"); + when(myBean.getEscapeStringKey()).thenReturn("h\be\tllo w\u1234orld!"); + when(myBean.isTrueKey()).thenReturn(true); + when(myBean.isFalseKey()).thenReturn(false); + when(myBean.getStringReaderKey()).thenReturn( + new StringReader("") { + }); + + JSONObject jsonObject = new JSONObject(myBean); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); + assertTrue("expected 0 items in stringReaderKey", ((Map) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); + assertTrue("expected hello world!","hello world!".equals(jsonObject.query("/stringKey"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); + assertTrue("expected 42", Integer.valueOf("42").equals(jsonObject.query("/intKey"))); + assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(jsonObject.query("/doubleKey"))); + // sorry, mockito artifact + assertTrue("expected 2 callbacks items", ((List)(JsonPath.read(doc, "$.callbacks"))).size() == 2); + assertTrue("expected 0 handler items", ((Map)(JsonPath.read(doc, "$.callbacks[0].handler"))).size() == 0); + assertTrue("expected 0 callbacks[1] items", ((Map)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0); + } + + /** + * A bean is also an object. But in order to test the JSONObject + * ctor that takes an object and a list of names, + * this particular bean needs some public + * data members, which have been added to the class. + */ + @Test + public void jsonObjectByObjectAndNames() { + String[] keys = {"publicString", "publicInt"}; + // just need a class that has public data members + MyPublicClass myPublicClass = new MyPublicClass(); + JSONObject jsonObject = new JSONObject(myPublicClass, keys); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString"))); + assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt"))); + } + + /** + * Exercise the JSONObject from resource bundle functionality. + * The test resource bundle is uncomplicated, but provides adequate test coverage. + */ + @Test + public void jsonObjectByResourceBundle() { + JSONObject jsonObject = new + JSONObject("org.json.junit.StringsResourceBundle", + Locale.getDefault()); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); + assertTrue("expected 2 greetings items", ((Map)(JsonPath.read(doc, "$.greetings"))).size() == 2); + assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello"))); + assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world"))); + assertTrue("expected 2 farewells items", ((Map)(JsonPath.read(doc, "$.farewells"))).size() == 2); + assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later"))); + assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator"))); + } + + /** + * Exercise the JSONObject.accumulate() method + */ + @SuppressWarnings("boxing") + @Test + public void jsonObjectAccumulate() { + + JSONObject jsonObject = new JSONObject(); + jsonObject.accumulate("myArray", true); + jsonObject.accumulate("myArray", false); + jsonObject.accumulate("myArray", "hello world!"); + jsonObject.accumulate("myArray", "h\be\tllo w\u1234orld!"); + jsonObject.accumulate("myArray", 42); + jsonObject.accumulate("myArray", -23.45e7); + // include an unsupported object for coverage + try { + jsonObject.accumulate("myArray", Double.NaN); + assertTrue("Expected exception", false); + } catch (JSONException ignored) {} + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1"))); + assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); + assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); + assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); + } + + /** + * Exercise the JSONObject append() functionality + */ + @SuppressWarnings("boxing") + @Test + public void jsonObjectAppend() { + JSONObject jsonObject = new JSONObject(); + jsonObject.append("myArray", true); + jsonObject.append("myArray", false); + jsonObject.append("myArray", "hello world!"); + jsonObject.append("myArray", "h\be\tllo w\u1234orld!"); + jsonObject.append("myArray", 42); + jsonObject.append("myArray", -23.45e7); + // include an unsupported object for coverage + try { + jsonObject.append("myArray", Double.NaN); + assertTrue("Expected exception", false); + } catch (JSONException ignored) {} + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1/"))); + assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); + assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); + assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); + assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); + } + + /** + * Exercise the JSONObject doubleToString() method + */ + @SuppressWarnings("boxing") + @Test + public void jsonObjectDoubleToString() { + String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; + Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, + Double.NaN, Double.NEGATIVE_INFINITY }; + for (int i = 0; i < expectedStrs.length; ++i) { + String actualStr = JSONObject.doubleToString(doubles[i]); + assertTrue("value expected ["+expectedStrs[i]+ + "] found ["+actualStr+ "]", + expectedStrs[i].equals(actualStr)); + } + } + + /** + * Exercise some JSONObject get[type] and opt[type] methods + */ + @Test + public void jsonObjectValues() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"trueStrKey\":\"true\","+ + "\"falseStrKey\":\"false\","+ + "\"stringKey\":\"hello world!\","+ + "\"intKey\":42,"+ + "\"intStrKey\":\"43\","+ + "\"longKey\":1234567890123456789,"+ + "\"longStrKey\":\"987654321098765432\","+ + "\"doubleKey\":-23.45e7,"+ + "\"doubleStrKey\":\"00001.000\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{\"myKey\":\"myVal\"}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); + assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); + assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); + assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); + assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); + assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); + assertTrue("stringKey should be string", + jsonObject.getString("stringKey").equals("hello world!")); + assertTrue("doubleKey should be double", + jsonObject.getDouble("doubleKey") == -23.45e7); + assertTrue("doubleStrKey should be double", + jsonObject.getDouble("doubleStrKey") == 1); + assertTrue("opt doubleKey should be double", + jsonObject.optDouble("doubleKey") == -23.45e7); + assertTrue("opt doubleKey with Default should be double", + jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); + assertTrue("intKey should be int", + jsonObject.optInt("intKey") == 42); + assertTrue("opt intKey should be int", + jsonObject.optInt("intKey", 0) == 42); + assertTrue("opt intKey with default should be int", + jsonObject.getInt("intKey") == 42); + assertTrue("intStrKey should be int", + jsonObject.getInt("intStrKey") == 43); + assertTrue("longKey should be long", + jsonObject.getLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey should be long", + jsonObject.optLong("longKey") == 1234567890123456789L); + assertTrue("opt longKey with default should be long", + jsonObject.optLong("longKey", 0) == 1234567890123456789L); + assertTrue("longStrKey should be long", + jsonObject.getLong("longStrKey") == 987654321098765432L); + assertTrue("xKey should not exist", + jsonObject.isNull("xKey")); + assertTrue("stringKey should exist", + jsonObject.has("stringKey")); + assertTrue("opt stringKey should string", + jsonObject.optString("stringKey").equals("hello world!")); + assertTrue("opt stringKey with default should string", + jsonObject.optString("stringKey", "not found").equals("hello world!")); + JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); + assertTrue("arrayKey should be JSONArray", + jsonArray.getInt(0) == 0 && + jsonArray.getInt(1) == 1 && + jsonArray.getInt(2) == 2); + jsonArray = jsonObject.optJSONArray("arrayKey"); + assertTrue("opt arrayKey should be JSONArray", + jsonArray.getInt(0) == 0 && + jsonArray.getInt(1) == 1 && + jsonArray.getInt(2) == 2); + JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); + assertTrue("objectKey should be JSONObject", + jsonObjectInner.get("myKey").equals("myVal")); + } + + /** + * Check whether JSONObject handles large or high precision numbers correctly + */ + @Test + public void stringToValueNumbersTest() { + assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0") instanceof Double); + assertTrue("-0.0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double); + assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String); + assertTrue( "0.2 should be a Double!", + JSONObject.stringToValue( "0.2" ) instanceof Double ); + assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", + JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double ); + /** + * This test documents a need for BigDecimal conversion. + */ + Object obj = JSONObject.stringToValue( "299792.457999999984" ); + assertTrue( "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!", + obj.equals(new Double(299792.458)) ); + assertTrue( "1 should be an Integer!", + JSONObject.stringToValue( "1" ) instanceof Integer ); + assertTrue( "Integer.MAX_VALUE should still be an Integer!", + JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); + assertTrue( "Large integers should be a Long!", + JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); + assertTrue( "Long.MAX_VALUE should still be an Integer!", + JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); + + String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString(); + assertTrue( "Really large integers currently evaluate to string", + JSONObject.stringToValue(str).equals("9223372036854775808")); + } + + /** + * This test documents numeric values which could be numerically + * handled as BigDecimal or BigInteger. It helps determine what outputs + * will change if those types are supported. + */ + @Test + public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { + // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects + String str = + "{"+ + "\"numberWithDecimals\":299792.457999999984,"+ + "\"largeNumber\":12345678901234567890,"+ + "\"preciseNumber\":0.2000000000000000111,"+ + "\"largeExponent\":-23.45e2327"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + // Comes back as a double, but loses precision + assertTrue( "numberWithDecimals currently evaluates to double 299792.458", + jsonObject.get( "numberWithDecimals" ).equals( new Double( "299792.458" ) ) ); + Object obj = jsonObject.get( "largeNumber" ); + assertTrue("largeNumber currently evaluates to string", + "12345678901234567890".equals(obj)); + // comes back as a double but loses precision + assertTrue( "preciseNumber currently evaluates to double 0.2", + jsonObject.get( "preciseNumber" ).equals(new Double(0.2))); + obj = jsonObject.get( "largeExponent" ); + assertTrue("largeExponent should currently evaluates as a string", + "-23.45e2327".equals(obj)); + } + + /** + * This test documents how JSON-Java handles invalid numeric input. + */ + @Test + public void jsonInvalidNumberValues() { + // Number-notations supported by Java and invalid as JSON + String str = + "{"+ + "\"hexNumber\":-0x123,"+ + "\"tooManyZeros\":00,"+ + "\"negativeInfinite\":-Infinity,"+ + "\"negativeNaN\":-NaN,"+ + "\"negativeFraction\":-.01,"+ + "\"tooManyZerosFraction\":00.001,"+ + "\"negativeHexFloat\":-0x1.fffp1,"+ + "\"hexFloat\":0x1.0P-1074,"+ + "\"floatIdentifier\":0.1f,"+ + "\"doubleIdentifier\":0.1d"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + Object obj; + obj = jsonObject.get( "hexNumber" ); + assertFalse( "hexNumber must not be a number (should throw exception!?)", + obj instanceof Number ); + assertTrue("hexNumber currently evaluates to string", + obj.equals("-0x123")); + assertTrue( "tooManyZeros currently evaluates to string", + jsonObject.get( "tooManyZeros" ).equals("00")); + obj = jsonObject.get("negativeInfinite"); + assertTrue( "negativeInfinite currently evaluates to string", + obj.equals("-Infinity")); + obj = jsonObject.get("negativeNaN"); + assertTrue( "negativeNaN currently evaluates to string", + obj.equals("-NaN")); + assertTrue( "negativeFraction currently evaluates to double -0.01", + jsonObject.get( "negativeFraction" ).equals(new Double(-0.01))); + assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", + jsonObject.get( "tooManyZerosFraction" ).equals(new Double(0.001))); + assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875", + jsonObject.get( "negativeHexFloat" ).equals(new Double(-3.99951171875))); + assertTrue("hexFloat currently evaluates to double 4.9E-324", + jsonObject.get("hexFloat").equals(new Double(4.9E-324))); + assertTrue("floatIdentifier currently evaluates to double 0.1", + jsonObject.get("floatIdentifier").equals(new Double(0.1))); + assertTrue("doubleIdentifier currently evaluates to double 0.1", + jsonObject.get("doubleIdentifier").equals(new Double(0.1))); + } + + /** + * Tests how JSONObject get[type] handles incorrect types + */ + @Test + public void jsonObjectNonAndWrongValues() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"trueStrKey\":\"true\","+ + "\"falseStrKey\":\"false\","+ + "\"stringKey\":\"hello world!\","+ + "\"intKey\":42,"+ + "\"intStrKey\":\"43\","+ + "\"longKey\":1234567890123456789,"+ + "\"longStrKey\":\"987654321098765432\","+ + "\"doubleKey\":-23.45e7,"+ + "\"doubleStrKey\":\"00001.000\","+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{\"myKey\":\"myVal\"}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + try { + jsonObject.getBoolean("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("expecting an exception message", + "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); + } + try { + jsonObject.getBoolean("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a Boolean.". + equals(e.getMessage())); + } + try { + jsonObject.getString("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getString("trueKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"trueKey\"] not a string.". + equals(e.getMessage())); + } + try { + jsonObject.getDouble("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getDouble("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a number.". + equals(e.getMessage())); + } + try { + jsonObject.getInt("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getInt("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not an int.". + equals(e.getMessage())); + } + try { + jsonObject.getLong("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getLong("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a long.". + equals(e.getMessage())); + } + try { + jsonObject.getJSONArray("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getJSONArray("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a JSONArray.". + equals(e.getMessage())); + } + try { + jsonObject.getJSONObject("nonKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getJSONObject("stringKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a JSONObject.". + equals(e.getMessage())); + } + } + + /** + * This test documents an unexpected numeric behavior. + * A double that ends with .0 is parsed, serialized, then + * parsed again. On the second parse, it has become an int. + */ + @Test + public void unexpectedDoubleToIntConversion() { + String key30 = "key30"; + String key31 = "key31"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put(key30, new Double(3.0)); + jsonObject.put(key31, new Double(3.1)); + + assertTrue("3.0 should remain a double", + jsonObject.getDouble(key30) == 3); + assertTrue("3.1 should remain a double", + jsonObject.getDouble(key31) == 3.1); + + // turns 3.0 into 3. + String serializedString = jsonObject.toString(); + JSONObject deserialized = new JSONObject(serializedString); + assertTrue("3.0 is now an int", deserialized.get(key30) instanceof Integer); + assertTrue("3.0 can still be interpreted as a double", + deserialized.getDouble(key30) == 3.0); + assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); + } + + /** + * Document behaviors of big numbers. Includes both JSONObject + * and JSONArray tests + */ + @SuppressWarnings("boxing") + @Test + public void bigNumberOperations() { + /** + * JSONObject tries to parse BigInteger as a bean, but it only has + * one getter, getLowestBitSet(). The value is lost and an unhelpful + * value is stored. This should be fixed. + */ + BigInteger bigInteger = new BigInteger("123456789012345678901234567890"); + JSONObject jsonObject = new JSONObject(bigInteger); + Object obj = jsonObject.get("lowestSetBit"); + assertTrue("JSONObject only has 1 value", jsonObject.length() == 1); + assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet", + obj instanceof Integer); + assertTrue("this bigInteger lowestBitSet happens to be 1", + obj.equals(1)); + + /** + * JSONObject tries to parse BigDecimal as a bean, but it has + * no getters, The value is lost and no value is stored. + * This should be fixed. + */ + BigDecimal bigDecimal = new BigDecimal( + "123456789012345678901234567890.12345678901234567890123456789"); + jsonObject = new JSONObject(bigDecimal); + assertTrue("large bigDecimal is not stored", jsonObject.length() == 0); + + /** + * JSONObject put(String, Object) method stores and serializes + * bigInt and bigDec correctly. Nothing needs to change. + */ + jsonObject = new JSONObject(); + jsonObject.put("bigInt", bigInteger); + assertTrue("jsonObject.put() handles bigInt correctly", + jsonObject.get("bigInt").equals(bigInteger)); + assertTrue("jsonObject.getBigInteger() handles bigInt correctly", + jsonObject.getBigInteger("bigInt").equals(bigInteger)); + assertTrue("jsonObject.optBigInteger() handles bigInt correctly", + jsonObject.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); + assertTrue("jsonObject serializes bigInt correctly", + jsonObject.toString().equals("{\"bigInt\":123456789012345678901234567890}")); + jsonObject = new JSONObject(); + jsonObject.put("bigDec", bigDecimal); + assertTrue("jsonObject.put() handles bigDec correctly", + jsonObject.get("bigDec").equals(bigDecimal)); + assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", + jsonObject.getBigDecimal("bigDec").equals(bigDecimal)); + assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", + jsonObject.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); + assertTrue("jsonObject serializes bigDec correctly", + jsonObject.toString().equals( + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + + /** + * exercise some exceptions + */ + try { + jsonObject.getBigDecimal("bigInt"); + assertTrue("expected an exeption", false); + } catch (JSONException ignored) {} + obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); + assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); + try { + jsonObject.getBigInteger("bigDec"); + assertTrue("expected an exeption", false); + } catch (JSONException ignored) {} + jsonObject.put("stringKey", "abc"); + try { + jsonObject.getBigDecimal("stringKey"); + assertTrue("expected an exeption", false); + } catch (JSONException ignored) {} + obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); + assertTrue("expected BigInteger", obj.equals(BigInteger.ONE)); + + /** + * JSONObject.numberToString() works correctly, nothing to change. + */ + String str = JSONObject.numberToString(bigInteger); + assertTrue("numberToString() handles bigInteger correctly", + str.equals("123456789012345678901234567890")); + str = JSONObject.numberToString(bigDecimal); + assertTrue("numberToString() handles bigDecimal correctly", + str.equals("123456789012345678901234567890.12345678901234567890123456789")); + + /** + * JSONObject.stringToValue() turns bigInt into an accurate string, + * and rounds bigDec. This incorrect, but users may have come to + * expect this behavior. Change would be marginally better, but + * might inconvenience users. + */ + obj = JSONObject.stringToValue(bigInteger.toString()); + assertTrue("stringToValue() turns bigInteger string into string", + obj instanceof String); + obj = JSONObject.stringToValue(bigDecimal.toString()); + assertTrue("stringToValue() changes bigDecimal string", + !obj.toString().equals(bigDecimal.toString())); + + /** + * wrap() vs put() big number behavior is now the same. + */ + // bigInt map ctor + Map map = new HashMap(); + map.put("bigInt", bigInteger); + jsonObject = new JSONObject(map); + String actualFromMapStr = jsonObject.toString(); + assertTrue("bigInt in map (or array or bean) is a string", + actualFromMapStr.equals( + "{\"bigInt\":123456789012345678901234567890}")); + // bigInt put + jsonObject = new JSONObject(); + jsonObject.put("bigInt", bigInteger); + String actualFromPutStr = jsonObject.toString(); + assertTrue("bigInt from put is a number", + actualFromPutStr.equals( + "{\"bigInt\":123456789012345678901234567890}")); + // bigDec map ctor + map = new HashMap(); + map.put("bigDec", bigDecimal); + jsonObject = new JSONObject(map); + actualFromMapStr = jsonObject.toString(); + assertTrue("bigDec in map (or array or bean) is a bigDec", + actualFromMapStr.equals( + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + // bigDec put + jsonObject = new JSONObject(); + jsonObject.put("bigDec", bigDecimal); + actualFromPutStr = jsonObject.toString(); + assertTrue("bigDec from put is a number", + actualFromPutStr.equals( + "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + // bigInt,bigDec put + JSONArray jsonArray = new JSONArray(); + jsonArray.put(bigInteger); + jsonArray.put(bigDecimal); + actualFromPutStr = jsonArray.toString(); + assertTrue("bigInt, bigDec from put is a number", + actualFromPutStr.equals( + "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); + assertTrue("getBigInt is bigInt", jsonArray.getBigInteger(0).equals(bigInteger)); + assertTrue("getBigDec is bigDec", jsonArray.getBigDecimal(1).equals(bigDecimal)); + assertTrue("optBigInt is bigInt", jsonArray.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); + assertTrue("optBigDec is bigDec", jsonArray.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); + jsonArray.put(Boolean.TRUE); + try { + jsonArray.getBigInteger(2); + assertTrue("should not be able to get big int", false); + } catch (Exception ignored) {} + try { + jsonArray.getBigDecimal(2); + assertTrue("should not be able to get big dec", false); + } catch (Exception ignored) {} + assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); + assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); + + // bigInt,bigDec list ctor + List list = new ArrayList(); + list.add(bigInteger); + list.add(bigDecimal); + jsonArray = new JSONArray(list); + String actualFromListStr = jsonArray.toString(); + assertTrue("bigInt, bigDec in list is a bigInt, bigDec", + actualFromListStr.equals( + "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); + // bigInt bean ctor + MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); + when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); + jsonObject = new JSONObject(myBigNumberBean); + String actualFromBeanStr = jsonObject.toString(); + // can't do a full string compare because mockery adds an extra key/value + assertTrue("bigInt from bean ctor is a bigInt", + actualFromBeanStr.contains("123456789012345678901234567890")); + // bigDec bean ctor + myBigNumberBean = mock(MyBigNumberBean.class); + when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); + jsonObject = new JSONObject(myBigNumberBean); + actualFromBeanStr = jsonObject.toString(); + // can't do a full string compare because mockery adds an extra key/value + assertTrue("bigDec from bean ctor is a bigDec", + actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789")); + // bigInt,bigDec wrap() + obj = JSONObject.wrap(bigInteger); + assertTrue("wrap() returns big num",obj.equals(bigInteger)); + obj = JSONObject.wrap(bigDecimal); + assertTrue("wrap() returns string",obj.equals(bigDecimal)); + + } + + /** + * The purpose for the static method getNames() methods are not clear. + * This method is not called from within JSON-Java. Most likely + * uses are to prep names arrays for: + * JSONObject(JSONObject jo, String[] names) + * JSONObject(Object object, String names[]), + */ + @Test + public void jsonObjectNames() { + JSONObject jsonObject; + + // getNames() from null JSONObject + assertTrue("null names from null Object", + null == JSONObject.getNames((Object)null)); + + // getNames() from object with no fields + assertTrue("null names from Object with no fields", + null == JSONObject.getNames(new MyJsonString())); + + // getNames from new JSONOjbect + jsonObject = new JSONObject(); + String [] names = JSONObject.getNames(jsonObject); + assertTrue("names should be null", names == null); + + + // getNames() from empty JSONObject + String emptyStr = "{}"; + jsonObject = new JSONObject(emptyStr); + assertTrue("empty JSONObject should have null names", + null == JSONObject.getNames(jsonObject)); + + // getNames() from JSONObject + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; + jsonObject = new JSONObject(str); + names = JSONObject.getNames(jsonObject); + JSONArray jsonArray = new JSONArray(names); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + List docList = JsonPath.read(doc, "$"); + assertTrue("expected 3 items", docList.size() == 3); + assertTrue( + "expected to find trueKey", + ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); + assertTrue( + "expected to find falseKey", + ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); + assertTrue( + "expected to find stringKey", + ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); + + /** + * getNames() from an enum with properties has an interesting result. + * It returns the enum values, not the selected enum properties + */ + MyEnumField myEnumField = MyEnumField.VAL1; + names = JSONObject.getNames(myEnumField); + + // validate JSON + jsonArray = new JSONArray(names); + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + docList = JsonPath.read(doc, "$"); + assertTrue("expected 3 items", docList.size() == 3); + assertTrue( + "expected to find VAL1", + ((List) JsonPath.read(doc, "$[?(@=='VAL1')]")).size() == 1); + assertTrue( + "expected to find VAL2", + ((List) JsonPath.read(doc, "$[?(@=='VAL2')]")).size() == 1); + assertTrue( + "expected to find VAL3", + ((List) JsonPath.read(doc, "$[?(@=='VAL3')]")).size() == 1); + + /** + * A bean is also an object. But in order to test the static + * method getNames(), this particular bean needs some public + * data members. + */ + MyPublicClass myPublicClass = new MyPublicClass(); + names = JSONObject.getNames(myPublicClass); + + // validate JSON + jsonArray = new JSONArray(names); + doc = Configuration.defaultConfiguration().jsonProvider() + .parse(jsonArray.toString()); + docList = JsonPath.read(doc, "$"); + assertTrue("expected 2 items", docList.size() == 2); + assertTrue( + "expected to find publicString", + ((List) JsonPath.read(doc, "$[?(@=='publicString')]")).size() == 1); + assertTrue( + "expected to find publicInt", + ((List) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1); + } + + /** + * Populate a JSONArray from an empty JSONObject names() method. + * It should be empty. + */ + @Test + public void emptyJsonObjectNamesToJsonAray() { + JSONObject jsonObject = new JSONObject(); + JSONArray jsonArray = jsonObject.names(); + assertTrue("jsonArray should be null", jsonArray == null); + } + + /** + * Populate a JSONArray from a JSONObject names() method. + * Confirm that it contains the expected names. + */ + @Test + public void jsonObjectNamesToJsonAray() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"stringKey\":\"hello world!\","+ + "}"; + + JSONObject jsonObject = new JSONObject(str); + JSONArray jsonArray = jsonObject.names(); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected to find trueKey", ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); + assertTrue("expected to find falseKey", ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); + assertTrue("expected to find stringKey", ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); + } + + /** + * Exercise the JSONObject increment() method. + */ + @SuppressWarnings("cast") + @Test + public void jsonObjectIncrement() { + String str = + "{"+ + "\"keyLong\":9999999991,"+ + "\"keyDouble\":1.1"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("keyInt"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); + jsonObject.increment("keyInt"); + jsonObject.increment("keyLong"); + jsonObject.increment("keyDouble"); + /** + * JSONObject constructor won't handle these types correctly, but + * adding them via put works. + */ + jsonObject.put("keyFloat", new Float(1.1)); + jsonObject.put("keyBigInt", new BigInteger("123456789123456789123456789123456780")); + jsonObject.put("keyBigDec", new BigDecimal("123456789123456789123456789123456780.1")); + jsonObject.increment("keyFloat"); + jsonObject.increment("keyFloat"); + jsonObject.increment("keyBigInt"); + jsonObject.increment("keyBigDec"); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/keyInt"))); + assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(jsonObject.query("/keyLong"))); + assertTrue("expected 3.1", Double.valueOf(3.1).equals(jsonObject.query("/keyDouble"))); + assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(jsonObject.query("/keyBigInt"))); + assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(jsonObject.query("/keyBigDec"))); + + /** + * Should work the same way on any platform! @see https://docs.oracle + * .com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3 This is the + * effect of a float to double conversion and is inherent to the + * shortcomings of the IEEE 754 format, when converting 32-bit into + * double-precision 64-bit. Java type-casts float to double. A 32 bit + * float is type-casted to 64 bit double by simply appending zero-bits + * to the mantissa (and extended the signed exponent by 3 bits.) and + * there is no way to obtain more information than it is stored in the + * 32-bits float. + * + * Like 1/3 cannot be represented as base10 number because it is + * periodically, 1/5 (for example) cannot be represented as base2 number + * since it is periodically in base2 (take a look at + * http://www.h-schmidt.net/FloatConverter/) The same happens to 3.1, + * that decimal number (base10 representation) is periodic in base2 + * representation, therefore appending zero-bits is inaccurate. Only + * repeating the periodically occurring bits (0110) would be a proper + * conversion. However one cannot detect from a 32 bit IEE754 + * representation which bits would "repeat infinitely", since the + * missing bits would not fit into the 32 bit float, i.e. the + * information needed simply is not there! + */ + assertTrue("expected 3.0999999046325684", Double.valueOf(3.0999999046325684).equals(jsonObject.query("/keyFloat"))); + + /** + * float f = 3.1f; double df = (double) f; double d = 3.1d; + * System.out.println + * (Integer.toBinaryString(Float.floatToRawIntBits(f))); + * System.out.println + * (Long.toBinaryString(Double.doubleToRawLongBits(df))); + * System.out.println + * (Long.toBinaryString(Double.doubleToRawLongBits(d))); + * + * - Float: + * seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm + * 1000000010001100110011001100110 + * - Double + * seeeeeeeeeeemmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + * 10000000 10001100110011001100110 + * 100000000001000110011001100110011000000000000000000000000000000 + * 100000000001000110011001100110011001100110011001100110011001101 + */ + + /** + * Examples of well documented but probably unexpected behavior in + * java / with 32-bit float to 64-bit float conversion. + */ + assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d ); + assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d ); + Double d1 = new Double( 1.1f ); + Double d2 = new Double( "1.1f" ); + assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); + + assertTrue( "Correctly converting float to double via base10 (string) representation!", new Double( 3.1d ).equals( new Double( new Float( 3.1f ).toString() ) ) ); + + // Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject + JSONObject jo = new JSONObject(); + jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double + assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( new Double( 3.1d ) ) ); + + JSONObject inc = new JSONObject(); + inc.put( "bug", new Float( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) + assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); + inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! + // this.put(key, (Float) value + 1); + // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. + // 2. Float instance will be autoboxed into float because the + operator will work on primitives not Objects! + // 3. A float+float operation will be performed and results into a float primitive. + // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method + // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa + assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Double ); + // correct implementation (with change of behavior) would be: + // this.put(key, new Float((Float) value + 1)); + // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not + // really in the the scope of a JSON-library (IMHO.) + + } + + /** + * Exercise JSONObject numberToString() method + */ + @SuppressWarnings("boxing") + @Test + public void jsonObjectNumberToString() { + String str; + Double dVal; + Integer iVal = 1; + str = JSONObject.numberToString(iVal); + assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); + dVal = 12.34; + str = JSONObject.numberToString(dVal); + assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + dVal = 12.34e27; + str = JSONObject.numberToString(dVal); + assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + // trailing .0 is truncated, so it doesn't quite match toString() + dVal = 5000000.0000000; + str = JSONObject.numberToString(dVal); + assertTrue("expected 5000000 actual "+str, str.equals("5000000")); + } + + /** + * Exercise JSONObject put() and similar() methods + */ + @SuppressWarnings("boxing") + @Test + public void jsonObjectPut() { + String expectedStr = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(); + jsonObject.put("trueKey", true); + jsonObject.put("falseKey", false); + Integer [] intArray = { 0, 1, 2 }; + jsonObject.put("arrayKey", Arrays.asList(intArray)); + Map myMap = new HashMap(); + myMap.put("myKey1", "myVal1"); + myMap.put("myKey2", "myVal2"); + myMap.put("myKey3", "myVal3"); + myMap.put("myKey4", "myVal4"); + jsonObject.put("objectKey", myMap); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); + assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); + assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); + assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); + assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); + assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); + assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); + assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); + + jsonObject.remove("trueKey"); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + assertTrue("unequal jsonObjects should not be similar", + !jsonObject.similar(expectedJsonObject)); + assertTrue("jsonObject should not be similar to jsonArray", + !jsonObject.similar(new JSONArray())); + + String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; + String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; + JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); + JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); + assertTrue("different values should not be similar", + !aCompareValueJsonObject.similar(bCompareValueJsonObject)); + + String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; + String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; + JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); + JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); + assertTrue("different nested JSONObjects should not be similar", + !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); + + String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; + String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; + JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); + JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); + assertTrue("different nested JSONArrays should not be similar", + !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); + } + + /** + * Exercise JSONObject toString() method + */ + @Test + public void jsonObjectToString() { + String str = + "{"+ + "\"trueKey\":true,"+ + "\"falseKey\":false,"+ + "\"arrayKey\":[0,1,2],"+ + "\"objectKey\":{"+ + "\"myKey1\":\"myVal1\","+ + "\"myKey2\":\"myVal2\","+ + "\"myKey3\":\"myVal3\","+ + "\"myKey4\":\"myVal4\""+ + "}"+ + "}"; + JSONObject jsonObject = new JSONObject(str); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); + assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); + assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); + assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); + assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); + assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); + assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); + assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); + assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); + } + + /** + * Exercise JSONObject toString() method with various indent levels. + */ + @Test + public void jsonObjectToStringIndent() { + String jsonObject0Str = + "{"+ + "\"key1\":" + + "[1,2," + + "{\"key3\":true}" + + "],"+ + "\"key2\":" + + "{\"key1\":\"val1\",\"key2\":" + + "{\"key2\":\"val2\"}" + + "},"+ + "\"key3\":" + + "[" + + "[1,2.1]" + + "," + + "[null]" + + "]"+ + "}"; + + String jsonObject1Str = + "{\n" + + " \"key1\": [\n" + + " 1,\n" + + " 2,\n" + + " {\"key3\": true}\n" + + " ],\n" + + " \"key2\": {\n" + + " \"key1\": \"val1\",\n" + + " \"key2\": {\"key2\": \"val2\"}\n" + + " },\n" + + " \"key3\": [\n" + + " [\n" + + " 1,\n" + + " 2.1\n" + + " ],\n" + + " [null]\n" + + " ]\n" + + "}"; + String jsonObject4Str = + "{\n" + + " \"key1\": [\n" + + " 1,\n" + + " 2,\n" + + " {\"key3\": true}\n" + + " ],\n" + + " \"key2\": {\n" + + " \"key1\": \"val1\",\n" + + " \"key2\": {\"key2\": \"val2\"}\n" + + " },\n" + + " \"key3\": [\n" + + " [\n" + + " 1,\n" + + " 2.1\n" + + " ],\n" + + " [null]\n" + + " ]\n" + + "}"; + JSONObject jsonObject = new JSONObject(jsonObject0Str); + assertEquals(jsonObject0Str, jsonObject.toString()); + assertEquals(jsonObject0Str, jsonObject.toString(0)); + assertEquals(jsonObject1Str, jsonObject.toString(1)); + assertEquals(jsonObject4Str, jsonObject.toString(4)); + } + + /** + * Explores how JSONObject handles maps. Insert a string/string map + * as a value in a JSONObject. It will remain a map. Convert the + * JSONObject to string, then create a new JSONObject from the string. + * In the new JSONObject, the value will be stored as a nested JSONObject. + * Confirm that map and nested JSONObject have the same contents. + */ + @Test + public void jsonObjectToStringSuppressWarningOnCastToMap() { + JSONObject jsonObject = new JSONObject(); + Map map = new HashMap<>(); + map.put("abc", "def"); + jsonObject.put("key", map); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 1 key item", ((Map)(JsonPath.read(doc, "$.key"))).size() == 1); + assertTrue("expected def", "def".equals(jsonObject.query("/key/abc"))); + } + + /** + * Explores how JSONObject handles collections. Insert a string collection + * as a value in a JSONObject. It will remain a collection. Convert the + * JSONObject to string, then create a new JSONObject from the string. + * In the new JSONObject, the value will be stored as a nested JSONArray. + * Confirm that collection and nested JSONArray have the same contents. + */ + @Test + public void jsonObjectToStringSuppressWarningOnCastToCollection() { + JSONObject jsonObject = new JSONObject(); + Collection collection = new ArrayList(); + collection.add("abc"); + // ArrayList will be added as an object + jsonObject.put("key", collection); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected 1 key item", ((List)(JsonPath.read(doc, "$.key"))).size() == 1); + assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0"))); + } + + /** + * Exercises the JSONObject.valueToString() method for various types + */ + @Test + public void valueToString() { + + assertTrue("null valueToString() incorrect", + "null".equals(JSONObject.valueToString(null))); + MyJsonString jsonString = new MyJsonString(); + assertTrue("jsonstring valueToString() incorrect", + "my string".equals(JSONObject.valueToString(jsonString))); + assertTrue("boolean valueToString() incorrect", + "true".equals(JSONObject.valueToString(Boolean.TRUE))); + assertTrue("non-numeric double", + "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); + String jsonObjectStr = + "{"+ + "\"key1\":\"val1\","+ + "\"key2\":\"val2\","+ + "\"key3\":\"val3\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("jsonObject valueToString() incorrect", + JSONObject.valueToString(jsonObject).equals(jsonObject.toString())); + String jsonArrayStr = + "[1,2,3]"; + JSONArray jsonArray = new JSONArray(jsonArrayStr); + assertTrue("jsonArray valueToString() incorrect", + JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); + Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + assertTrue("map valueToString() incorrect", + jsonObject.toString().equals(JSONObject.valueToString(map))); + Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + assertTrue("collection valueToString() expected: "+ + jsonArray.toString()+ " actual: "+ + JSONObject.valueToString(collection), + jsonArray.toString().equals(JSONObject.valueToString(collection))); + Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; + assertTrue("array valueToString() incorrect", + jsonArray.toString().equals(JSONObject.valueToString(array))); + } + + /** + * Confirm that https://github.com/douglascrockford/JSON-java/issues/167 is fixed. + * The following code was throwing a ClassCastException in the + * JSONObject(Map) constructor + */ + @SuppressWarnings("boxing") + @Test + public void valueToStringConfirmException() { + Map myMap = new HashMap(); + myMap.put(1, "myValue"); + // this is the test, it should not throw an exception + String str = JSONObject.valueToString(myMap); + // confirm result, just in case + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str); + assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); + assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1"))); + } + + /** + * Exercise the JSONObject wrap() method. Sometimes wrap() will change + * the object being wrapped, other times not. The purpose of wrap() is + * to ensure the value is packaged in a way that is compatible with how + * a JSONObject value or JSONArray value is supposed to be stored. + */ + @Test + public void wrapObject() { + // wrap(null) returns NULL + assertTrue("null wrap() incorrect", + JSONObject.NULL == JSONObject.wrap(null)); + + // wrap(Integer) returns Integer + Integer in = new Integer(1); + assertTrue("Integer wrap() incorrect", + in == JSONObject.wrap(in)); + + /** + * This test is to document the preferred behavior if BigDecimal is + * supported. Previously bd returned as a string, since it + * is recognized as being a Java package class. Now with explicit + * support for big numbers, it remains a BigDecimal + */ + Object bdWrap = JSONObject.wrap(BigDecimal.ONE); + assertTrue("BigDecimal.ONE evaluates to ONE", + bdWrap.equals(BigDecimal.ONE)); + + // wrap JSONObject returns JSONObject + String jsonObjectStr = + "{"+ + "\"key1\":\"val1\","+ + "\"key2\":\"val2\","+ + "\"key3\":\"val3\""+ + "}"; + JSONObject jsonObject = new JSONObject(jsonObjectStr); + assertTrue("JSONObject wrap() incorrect", + jsonObject == JSONObject.wrap(jsonObject)); + + // wrap collection returns JSONArray + Collection collection = new ArrayList(); + collection.add(new Integer(1)); + collection.add(new Integer(2)); + collection.add(new Integer(3)); + JSONArray jsonArray = (JSONArray) (JSONObject.wrap(collection)); + + // validate JSON + Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); + + // wrap Array returns JSONArray + Integer[] array = { new Integer(1), new Integer(2), new Integer(3) }; + JSONArray integerArrayJsonArray = (JSONArray)(JSONObject.wrap(array)); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString()); + assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); + assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); + assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); + + // wrap map returns JSONObject + Map map = new HashMap(); + map.put("key1", "val1"); + map.put("key2", "val2"); + map.put("key3", "val3"); + JSONObject mapJsonObject = (JSONObject) (JSONObject.wrap(map)); + + // validate JSON + doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString()); + assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); + assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1"))); + assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2"))); + assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3"))); + } + + + /** + * RFC 7159 defines control characters to be U+0000 through U+001F. This test verifies that the parser is checking for these in expected ways. + */ + @Test + public void jsonObjectParseControlCharacters(){ + for(int i = 0;i<=0x001f;i++){ + final String charString = String.valueOf((char)i); + final String source = "{\"key\":\""+charString+"\"}"; + try { + JSONObject jo = new JSONObject(source); + assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key"))); + } catch (JSONException ex) { + assertTrue("Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error", + i=='\0' || i=='\n' || i=='\r' + ); + } + } + } + + /** + * Explore how JSONObject handles parsing errors. + */ + @SuppressWarnings("boxing") + @Test + public void jsonObjectParsingErrors() { + try { + // does not start with '{' + String str = "abc"; + assertNull("Expected an exception",new JSONObject(str)); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "A JSONObject text must begin with '{' at 1 [character 2 line 1]". + equals(e.getMessage())); + } + try { + // does not end with '}' + String str = "{"; + assertNull("Expected an exception",new JSONObject(str)); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "A JSONObject text must end with '}' at 2 [character 3 line 1]". + equals(e.getMessage())); + } + try { + // key with no ':' + String str = "{\"myKey\" = true}"; + assertNull("Expected an exception",new JSONObject(str)); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Expected a ':' after a key at 10 [character 11 line 1]". + equals(e.getMessage())); + } + try { + // entries with no ',' separator + String str = "{\"myKey\":true \"myOtherKey\":false}"; + assertNull("Expected an exception",new JSONObject(str)); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Expected a ',' or '}' at 15 [character 16 line 1]". + equals(e.getMessage())); + } + try { + // append to wrong key + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.append("myKey", "hello"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[myKey] is not a JSONArray.". + equals(e.getMessage())); + } + try { + // increment wrong key + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.increment("myKey"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Unable to increment [\"myKey\"].". + equals(e.getMessage())); + } + try { + // invalid key + String str = "{\"myKey\":true, \"myOtherKey\":false}"; + JSONObject jsonObject = new JSONObject(str); + jsonObject.get(null); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Null key.". + equals(e.getMessage())); + } + try { + // invalid numberToString() + JSONObject.numberToString((Number)null); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "Null pointer". + equals(e.getMessage())); + } + try { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0); + assertTrue("Expected an exception", false); + } catch (NullPointerException ignored) { + } + try { + // multiple putOnce key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.putOnce("hello", "world"); + jsonObject.putOnce("hello", "world!"); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("", true); + } + try { + // test validity of invalid double + JSONObject.testValidity(Double.NaN); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("", true); + } + try { + // test validity of invalid float + JSONObject.testValidity(Float.NEGATIVE_INFINITY); + assertTrue("Expected an exception", false); + } catch (JSONException e) { + assertTrue("", true); + } + } + + /** + * Confirm behavior when putOnce() is called with null parameters + */ + @Test + public void jsonObjectPutOnceNull() { + JSONObject jsonObject = new JSONObject(); + jsonObject.putOnce(null, null); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + } + + /** + * Exercise JSONObject opt(key, default) method. + */ + @Test + public void jsonObjectOptDefault() { + + String str = "{\"myKey\": \"myval\", \"hiKey\": null}"; + JSONObject jsonObject = new JSONObject(str); + + assertTrue("optBigDecimal() should return default BigDecimal", + BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); + assertTrue("optBigInteger() should return default BigInteger", + BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); + assertTrue("optBoolean() should return default boolean", + jsonObject.optBoolean("myKey", true)); + assertTrue("optInt() should return default int", + 42 == jsonObject.optInt("myKey", 42)); + assertTrue("optEnum() should return default Enum", + MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); + assertTrue("optJSONArray() should return null ", + null==jsonObject.optJSONArray("myKey")); + assertTrue("optJSONObject() should return null ", + null==jsonObject.optJSONObject("myKey")); + assertTrue("optLong() should return default long", + 42 == jsonObject.optLong("myKey", 42)); + assertTrue("optDouble() should return default double", + 42.3 == jsonObject.optDouble("myKey", 42.3)); + assertTrue("optString() should return default string", + "hi".equals(jsonObject.optString("hiKey", "hi"))); + } + + /** + * Exercise JSONObject opt(key, default) method when the key doesn't exist. + */ + @Test + public void jsonObjectOptNoKey() { + + JSONObject jsonObject = new JSONObject(); + + assertTrue("optBigDecimal() should return default BigDecimal", + BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); + assertTrue("optBigInteger() should return default BigInteger", + BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); + assertTrue("optBoolean() should return default boolean", + jsonObject.optBoolean("myKey", true)); + assertTrue("optInt() should return default int", + 42 == jsonObject.optInt("myKey", 42)); + assertTrue("optEnum() should return default Enum", + MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); + assertTrue("optJSONArray() should return null ", + null==jsonObject.optJSONArray("myKey")); + assertTrue("optJSONObject() should return null ", + null==jsonObject.optJSONObject("myKey")); + assertTrue("optLong() should return default long", + 42 == jsonObject.optLong("myKey", 42)); + assertTrue("optDouble() should return default double", + 42.3 == jsonObject.optDouble("myKey", 42.3)); + assertTrue("optString() should return default string", + "hi".equals(jsonObject.optString("hiKey", "hi"))); + } + + /** + * Verifies that the opt methods properly convert string values. + */ + @Test + public void jsonObjectOptStringConversion() { + JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\"}"); + assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true); + assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false); + assertTrue("unexpected optInt value",jo.optInt("int",0)==123); + assertTrue("unexpected optLong value",jo.optLong("int",0)==123); + assertTrue("unexpected optDouble value",jo.optDouble("int",0.0)==123.0); + assertTrue("unexpected optBigInteger value",jo.optBigInteger("int",BigInteger.ZERO).compareTo(new BigInteger("123"))==0); + assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); + + } + + /** + * Confirm behavior when JSONObject put(key, null object) is called + */ + @Test + public void jsonObjectputNull() { + + // put null should remove the item. + String str = "{\"myKey\": \"myval\"}"; + JSONObject jsonObjectRemove = new JSONObject(str); + jsonObjectRemove.remove("myKey"); + + JSONObject jsonObjectPutNull = new JSONObject(str); + jsonObjectPutNull.put("myKey", (Object) null); + + // validate JSON + assertTrue("jsonObject should be empty", jsonObjectRemove.length() == 0 + && jsonObjectPutNull.length() == 0); + } + + /** + * Exercise JSONObject quote() method + * This purpose of quote() is to ensure that for strings with embedded + * quotes, the quotes are properly escaped. + */ + @Test + public void jsonObjectQuote() { + String str; + str = ""; + String quotedStr; + quotedStr = JSONObject.quote(str); + assertTrue("quote() expected escaped quotes, found "+quotedStr, + "\"\"".equals(quotedStr)); + str = "\"\""; + quotedStr = JSONObject.quote(str); + assertTrue("quote() expected escaped quotes, found "+quotedStr, + "\"\\\"\\\"\"".equals(quotedStr)); + str = "null and null will be emitted as "" + */ + String sJONull = XML.toString(jsonObjectJONull); + assertTrue("JSONObject.NULL should emit a null value", + "null".equals(sJONull)); + String sNull = XML.toString(jsonObjectNull); + assertTrue("null should emit an empty string", "".equals(sNull)); + } + + @Test(expected = JSONPointerException.class) + public void queryWithNoResult() { + new JSONObject().query("/a/b"); + } + + @Test + public void optQueryWithNoResult() { + assertNull(new JSONObject().optQuery("/a/b")); + } + + @Test(expected = IllegalArgumentException.class) + public void optQueryWithSyntaxError() { + new JSONObject().optQuery("invalid"); + } + + @Test(expected = JSONException.class) + public void invalidEscapeSequence() { + String json = "{ \"\\url\": \"value\" }"; + assertNull("Expected an exception",new JSONObject(json)); + } + + /** + * Exercise JSONObject toMap() method. + */ + @Test + public void toMap() { + String jsonObjectStr = + "{" + + "\"key1\":" + + "[1,2," + + "{\"key3\":true}" + + "]," + + "\"key2\":" + + "{\"key1\":\"val1\",\"key2\":" + + "{\"key2\":null}," + + "\"key3\":42" + + "}," + + "\"key3\":" + + "[" + + "[\"value1\",2.1]" + + "," + + "[null]" + + "]" + + "}"; + + JSONObject jsonObject = new JSONObject(jsonObjectStr); + Map map = jsonObject.toMap(); + + assertTrue("Map should not be null", map != null); + assertTrue("Map should have 3 elements", map.size() == 3); + + List key1List = (List)map.get("key1"); + assertTrue("key1 should not be null", key1List != null); + assertTrue("key1 list should have 3 elements", key1List.size() == 3); + assertTrue("key1 value 1 should be 1", key1List.get(0).equals(Integer.valueOf(1))); + assertTrue("key1 value 2 should be 2", key1List.get(1).equals(Integer.valueOf(2))); + + Map key1Value3Map = (Map)key1List.get(2); + assertTrue("Map should not be null", key1Value3Map != null); + assertTrue("Map should have 1 element", key1Value3Map.size() == 1); + assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); + + Map key2Map = (Map)map.get("key2"); + assertTrue("key2 should not be null", key2Map != null); + assertTrue("key2 map should have 3 elements", key2Map.size() == 3); + assertTrue("key2 map key 1 should be val1", key2Map.get("key1").equals("val1")); + assertTrue("key2 map key 3 should be 42", key2Map.get("key3").equals(Integer.valueOf(42))); + + Map key2Val2Map = (Map)key2Map.get("key2"); + assertTrue("key2 map key 2 should not be null", key2Val2Map != null); + assertTrue("key2 map key 2 should have an entry", key2Val2Map.containsKey("key2")); + assertTrue("key2 map key 2 value should be null", key2Val2Map.get("key2") == null); + + List key3List = (List)map.get("key3"); + assertTrue("key3 should not be null", key3List != null); + assertTrue("key3 list should have 3 elements", key3List.size() == 2); + + List key3Val1List = (List)key3List.get(0); + assertTrue("key3 list val 1 should not be null", key3Val1List != null); + assertTrue("key3 list val 1 should have 2 elements", key3Val1List.size() == 2); + assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); + assertTrue("key3 list val 1 list element 2 should be 2.1", key3Val1List.get(1).equals(Double.valueOf("2.1"))); + + List key3Val2List = (List)key3List.get(1); + assertTrue("key3 list val 2 should not be null", key3Val2List != null); + assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1); + assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null); + + // Assert that toMap() is a deep copy + jsonObject.getJSONArray("key3").getJSONArray(0).put(0, "still value 1"); + assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); + + // assert that the new map is mutable + assertTrue("Removing a key should succeed", map.remove("key3") != null); + assertTrue("Map should have 2 elements", map.size() == 2); + + } +} diff --git a/src/test/java/org/json/junit/JSONStringTest.java b/src/test/java/org/json/junit/JSONStringTest.java index cba5d09..617b9e3 100644 --- a/src/test/java/org/json/junit/JSONStringTest.java +++ b/src/test/java/org/json/junit/JSONStringTest.java @@ -1,310 +1,371 @@ -package org.json.junit; - -import static org.junit.Assert.*; - -import java.io.StringWriter; -import java.util.*; - -import org.json.*; -import org.junit.Test; - -/** - * Tests for JSONString implementations, and the difference between - * {@link JSONObject#valueToString} and {@link JSONObject#writeValue}. - */ -public class JSONStringTest { - - /** - * This tests the JSONObject.writeValue() method. We can't test directly - * due to it being a package-protected method. Instead, we can call - * JSONArray.write(), which delegates the writing of each entry to - * writeValue(). - */ - @Test - public void writeValues() throws Exception { - JSONArray jsonArray = new JSONArray(); - jsonArray.put((Object)null); - - StringWriter writer = new StringWriter(); - String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[null]".equals(output)); - - jsonArray = new JSONArray(); - jsonArray.put(JSONObject.NULL); - writer = new StringWriter(); - output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[null]".equals(output)); - - jsonArray = new JSONArray(); - jsonArray.put(new JSONObject()); - writer = new StringWriter(); - output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[{}]".equals(output)); - - jsonArray = new JSONArray(); - jsonArray.put(new JSONArray()); - writer = new StringWriter(); - output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[[]]".equals(output)); - - jsonArray = new JSONArray(); - Map singleMap = Collections.singletonMap("key1", "value1"); - jsonArray.put((Object)singleMap); - writer = new StringWriter(); - output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[{\"key1\":\"value1\"}]".equals(output)); - - jsonArray = new JSONArray(); - List singleList = Collections.singletonList("entry1"); - jsonArray.put((Object)singleList); - writer = new StringWriter(); - output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[[\"entry1\"]]".equals(output)); - - jsonArray = new JSONArray(); - int[] intArray = new int[] { 1, 2, 3 }; - jsonArray.put(intArray); - writer = new StringWriter(); - output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[[1,2,3]]".equals(output)); - - jsonArray = new JSONArray(); - jsonArray.put(24); - writer = new StringWriter(); - output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[24]".equals(output)); - - jsonArray = new JSONArray(); - jsonArray.put("string value"); - writer = new StringWriter(); - output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"string value\"]".equals(output)); - - jsonArray = new JSONArray(); - jsonArray.put(true); - writer = new StringWriter(); - output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[true]".equals(output)); - - } - - /** - * This tests the JSONObject.valueToString() method. These should be - * identical to the values above, except for the enclosing [ and ]. - */ - @Test - public void valuesToString() throws Exception { - - String output = JSONObject.valueToString(null); - assertTrue("String values should be equal", "null".equals(output)); - - output = JSONObject.valueToString(JSONObject.NULL); - assertTrue("String values should be equal", "null".equals(output)); - - output = JSONObject.valueToString(new JSONObject()); - assertTrue("String values should be equal", "{}".equals(output)); - - output = JSONObject.valueToString(new JSONArray()); - assertTrue("String values should be equal", "[]".equals(output)); - - Map singleMap = Collections.singletonMap("key1", "value1"); - output = JSONObject.valueToString(singleMap); - assertTrue("String values should be equal", "{\"key1\":\"value1\"}".equals(output)); - - List singleList = Collections.singletonList("entry1"); - output = JSONObject.valueToString(singleList); - assertTrue("String values should be equal", "[\"entry1\"]".equals(output)); - - int[] intArray = new int[] { 1, 2, 3 }; - output = JSONObject.valueToString(intArray); - assertTrue("String values should be equal", "[1,2,3]".equals(output)); - - output = JSONObject.valueToString(24); - assertTrue("String values should be equal", "24".equals(output)); - - output = JSONObject.valueToString("string value"); - assertTrue("String values should be equal", "\"string value\"".equals(output)); - - output = JSONObject.valueToString(true); - assertTrue("String values should be equal", "true".equals(output)); - - } - - /** - * Test what happens when toJSONString() returns a well-formed JSON value. - * This is the usual case. - */ - @Test - public void testJSONStringValue() throws Exception { - JSONStringValue jsonString = new JSONStringValue(); - JSONArray jsonArray = new JSONArray(); - - jsonArray.put(jsonString); - - StringWriter writer = new StringWriter(); - String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"the JSON string value\"]".equals(output)); - - output = JSONObject.valueToString(jsonString); - assertTrue("String values should be equal", "\"the JSON string value\"".equals(output)); - } - - /** - * Test what happens when toJSONString() returns null. In one case, - * use the object's toString() method. In the other, throw a JSONException. - */ - @Test - public void testJSONNullStringValue() throws Exception { - JSONNullStringValue jsonString = new JSONNullStringValue(); - JSONArray jsonArray = new JSONArray(); - - jsonArray.put(jsonString); - - StringWriter writer = new StringWriter(); - String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"the toString value\"]".equals(output)); - - // The only different between writeValue() and valueToString(): - // in this case, valueToString throws a JSONException - try { - output = JSONObject.valueToString(jsonString); - fail("Expected an exception, got a String value"); - } catch (Exception e) { - assertTrue("Expected JSONException", e instanceof JSONException); - assertTrue("Exception message does not match", "Bad value from toJSONString: null".equals(e.getMessage())); - } - } - - /** - * Test what happens when toJSONString() returns an exception. In both - * cases, a JSONException is thrown, with the cause and message set from - * the original exception. - */ - @Test - public void testJSONStringExceptionValue() throws Exception { - JSONStringExceptionValue jsonString = new JSONStringExceptionValue(); - JSONArray jsonArray = new JSONArray(); - - jsonArray.put(jsonString); - - StringWriter writer = new StringWriter(); - String output = null; - try { - output = jsonArray.write(writer).toString(); - fail("Expected an exception, got a String value"); - } catch (Exception e) { - assertTrue("Expected JSONException", e instanceof JSONException); - assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); - } - - try { - output = JSONObject.valueToString(jsonString); - fail("Expected an exception, got a String value"); - } catch (Exception e) { - assertTrue("Expected JSONException", e instanceof JSONException); - assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); - } - } - - /** - * Test what happens when a Java object's toString() returns a String value. - * This is the usual case. - */ - @Test - public void testStringValue() throws Exception { - StringValue nonJsonString = new StringValue(); - JSONArray jsonArray = new JSONArray(); - - jsonArray.put(nonJsonString); - - StringWriter writer = new StringWriter(); - String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"the toString value for StringValue\"]".equals(output)); - - output = JSONObject.valueToString(nonJsonString); - assertTrue("String values should be equal", "\"the toString value for StringValue\"".equals(output)); - } - - /** - * Test what happens when a Java object's toString() returns null. - * Defaults to empty string. - */ - @Test - public void testNullStringValue() throws Exception { - NullStringValue nonJsonString = new NullStringValue(); - JSONArray jsonArray = new JSONArray(); - - jsonArray.put(nonJsonString); - - StringWriter writer = new StringWriter(); - String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"\"]".equals(output)); - - output = JSONObject.valueToString(nonJsonString); - assertTrue("String values should be equal", "\"\"".equals(output)); - } - - /** - * A JSONString that returns a valid JSON string value. - */ - private static final class JSONStringValue implements JSONString { - - @Override - public String toJSONString() { - return "\"the JSON string value\""; - } - - @Override - public String toString() { - return "the toString value for JSONStringValue"; - } - } - - /** - * A JSONString that returns null when calling toJSONString(). - */ - private static final class JSONNullStringValue implements JSONString { - - @Override - public String toJSONString() { - return null; - } - - @Override - public String toString() { - return "the toString value"; - } - } - - /** - * A JSONString that throw an exception when calling toJSONString(). - */ - private static final class JSONStringExceptionValue implements JSONString { - - @Override - public String toJSONString() { - throw new IllegalStateException("the exception value"); - } - - @Override - public String toString() { - return "the toString value for JSONStringExceptionValue"; - } - } - - public static final class StringValue { - - @Override - public String toString() { - return "the toString value for StringValue"; - } - } - - public static final class NullStringValue { - - @Override - public String toString() { - return null; - } - } -} +package org.json.junit; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.*; + +import org.json.*; +import org.junit.Test; + +/** + * Tests for JSONString implementations, and the difference between + * {@link JSONObject#valueToString} and {@link JSONObject#writeValue}. + */ +public class JSONStringTest { + + /** + * This tests the JSONObject.writeValue() method. We can't test directly + * due to it being a package-protected method. Instead, we can call + * JSONArray.write(), which delegates the writing of each entry to + * writeValue(). + */ + @Test + public void writeValues() throws Exception { + JSONArray jsonArray = new JSONArray(); + jsonArray.put((Object)null); + + StringWriter writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[null]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(JSONObject.NULL); + } finally { + writer.close(); + } + writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[null]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(new JSONObject()); + } finally { + writer.close(); + } + writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[{}]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(new JSONArray()); + } finally { + writer.close(); + } + writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[[]]".equals(output)); + + jsonArray = new JSONArray(); + Map singleMap = Collections.singletonMap("key1", "value1"); + jsonArray.put((Object)singleMap); + } finally { + writer.close(); + } + writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[{\"key1\":\"value1\"}]".equals(output)); + + jsonArray = new JSONArray(); + List singleList = Collections.singletonList("entry1"); + jsonArray.put((Object)singleList); + } finally { + writer.close(); + } + writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[[\"entry1\"]]".equals(output)); + + jsonArray = new JSONArray(); + int[] intArray = new int[] { 1, 2, 3 }; + jsonArray.put(intArray); + } finally { + writer.close(); + } + writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[[1,2,3]]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(24); + } finally { + writer.close(); + } + writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[24]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put("string value"); + } finally { + writer.close(); + } + writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"string value\"]".equals(output)); + + jsonArray = new JSONArray(); + jsonArray.put(true); + } finally { + writer.close(); + } + writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[true]".equals(output)); + } finally { + writer.close(); + } + + } + + /** + * This tests the JSONObject.valueToString() method. These should be + * identical to the values above, except for the enclosing [ and ]. + */ + @SuppressWarnings("boxing") + @Test + public void valuesToString() throws Exception { + + String output = JSONObject.valueToString(null); + assertTrue("String values should be equal", "null".equals(output)); + + output = JSONObject.valueToString(JSONObject.NULL); + assertTrue("String values should be equal", "null".equals(output)); + + output = JSONObject.valueToString(new JSONObject()); + assertTrue("String values should be equal", "{}".equals(output)); + + output = JSONObject.valueToString(new JSONArray()); + assertTrue("String values should be equal", "[]".equals(output)); + + Map singleMap = Collections.singletonMap("key1", "value1"); + output = JSONObject.valueToString(singleMap); + assertTrue("String values should be equal", "{\"key1\":\"value1\"}".equals(output)); + + List singleList = Collections.singletonList("entry1"); + output = JSONObject.valueToString(singleList); + assertTrue("String values should be equal", "[\"entry1\"]".equals(output)); + + int[] intArray = new int[] { 1, 2, 3 }; + output = JSONObject.valueToString(intArray); + assertTrue("String values should be equal", "[1,2,3]".equals(output)); + + output = JSONObject.valueToString(24); + assertTrue("String values should be equal", "24".equals(output)); + + output = JSONObject.valueToString("string value"); + assertTrue("String values should be equal", "\"string value\"".equals(output)); + + output = JSONObject.valueToString(true); + assertTrue("String values should be equal", "true".equals(output)); + + } + + /** + * Test what happens when toJSONString() returns a well-formed JSON value. + * This is the usual case. + */ + @Test + public void testJSONStringValue() throws Exception { + JSONStringValue jsonString = new JSONStringValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(jsonString); + + StringWriter writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"the JSON string value\"]".equals(output)); + + output = JSONObject.valueToString(jsonString); + assertTrue("String values should be equal", "\"the JSON string value\"".equals(output)); + } finally { + writer.close(); + } + } + + /** + * Test what happens when toJSONString() returns null. In one case, + * use the object's toString() method. In the other, throw a JSONException. + */ + @Test + public void testJSONNullStringValue() throws Exception { + JSONNullStringValue jsonString = new JSONNullStringValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(jsonString); + + StringWriter writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"the toString value\"]".equals(output)); + + // The only different between writeValue() and valueToString(): + // in this case, valueToString throws a JSONException + try { + output = JSONObject.valueToString(jsonString); + fail("Expected an exception, got a String value"); + } catch (Exception e) { + assertTrue("Expected JSONException", e instanceof JSONException); + assertTrue("Exception message does not match", "Bad value from toJSONString: null".equals(e.getMessage())); + } + } finally { + writer.close(); + } + } + + /** + * Test what happens when toJSONString() returns an exception. In both + * cases, a JSONException is thrown, with the cause and message set from + * the original exception. + */ + @Test + public void testJSONStringExceptionValue() throws IOException { + JSONStringExceptionValue jsonString = new JSONStringExceptionValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(jsonString); + + StringWriter writer = new StringWriter(); + try { + jsonArray.write(writer).toString(); + fail("Expected an exception, got a String value"); + } catch (JSONException e) { + assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); + } catch(Exception e) { + fail("Expected JSONException"); + } finally { + writer.close(); + } + + try { + JSONObject.valueToString(jsonString); + fail("Expected an exception, got a String value"); + } catch (JSONException e) { + assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); + } catch(Exception e) { + fail("Expected JSONException"); + } + } + + /** + * Test what happens when a Java object's toString() returns a String value. + * This is the usual case. + */ + @Test + public void testStringValue() throws Exception { + StringValue nonJsonString = new StringValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(nonJsonString); + + StringWriter writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"the toString value for StringValue\"]".equals(output)); + + output = JSONObject.valueToString(nonJsonString); + assertTrue("String values should be equal", "\"the toString value for StringValue\"".equals(output)); + } finally { + writer.close(); + } + } + + /** + * Test what happens when a Java object's toString() returns null. + * Defaults to empty string. + */ + @Test + public void testNullStringValue() throws Exception { + NullStringValue nonJsonString = new NullStringValue(); + JSONArray jsonArray = new JSONArray(); + + jsonArray.put(nonJsonString); + + StringWriter writer = new StringWriter(); + try { + String output = jsonArray.write(writer).toString(); + assertTrue("String values should be equal", "[\"\"]".equals(output)); + + output = JSONObject.valueToString(nonJsonString); + assertTrue("String values should be equal", "\"\"".equals(output)); + } finally { + writer.close(); + } + } + + /** + * A JSONString that returns a valid JSON string value. + */ + private static final class JSONStringValue implements JSONString { + + @Override + public String toJSONString() { + return "\"the JSON string value\""; + } + + @Override + public String toString() { + return "the toString value for JSONStringValue"; + } + } + + /** + * A JSONString that returns null when calling toJSONString(). + */ + private static final class JSONNullStringValue implements JSONString { + + @Override + public String toJSONString() { + return null; + } + + @Override + public String toString() { + return "the toString value"; + } + } + + /** + * A JSONString that throw an exception when calling toJSONString(). + */ + private static final class JSONStringExceptionValue implements JSONString { + + @Override + public String toJSONString() { + throw new IllegalStateException("the exception value"); + } + + @Override + public String toString() { + return "the toString value for JSONStringExceptionValue"; + } + } + + public static final class StringValue { + + @Override + public String toString() { + return "the toString value for StringValue"; + } + } + + public static final class NullStringValue { + + @Override + public String toString() { + return null; + } + } +} diff --git a/src/test/java/org/json/junit/MyEnumField.java b/src/test/java/org/json/junit/MyEnumField.java index 8f2c633..f0833ef 100644 --- a/src/test/java/org/json/junit/MyEnumField.java +++ b/src/test/java/org/json/junit/MyEnumField.java @@ -3,6 +3,7 @@ package org.json.junit; /** * An enum that contains getters and some internal fields */ +@SuppressWarnings("boxing") public enum MyEnumField { VAL1(1, "val 1"), VAL2(2, "val 2"), @@ -15,12 +16,13 @@ public enum MyEnumField { this.intVal = intVal; } public String getValue() { - return value; + return this.value; } public Integer getIntVal() { - return intVal; + return this.intVal; } + @Override public String toString(){ - return value; + return this.value; } } diff --git a/src/test/java/org/json/junit/MyPublicClass.java b/src/test/java/org/json/junit/MyPublicClass.java index 1f55e3e..e483d4c 100644 --- a/src/test/java/org/json/junit/MyPublicClass.java +++ b/src/test/java/org/json/junit/MyPublicClass.java @@ -3,6 +3,7 @@ package org.json.junit; /** * Need a class with some public data members for testing */ +@SuppressWarnings("boxing") public class MyPublicClass { public Integer publicInt = 42; public String publicString = "abc"; diff --git a/src/test/java/org/json/junit/StringsResourceBundle.java b/src/test/java/org/json/junit/StringsResourceBundle.java index 83d9322..d04aeaf 100644 --- a/src/test/java/org/json/junit/StringsResourceBundle.java +++ b/src/test/java/org/json/junit/StringsResourceBundle.java @@ -6,6 +6,7 @@ import java.util.*; * A resource bundle class */ public class StringsResourceBundle extends ListResourceBundle { + @Override public Object[][] getContents() { return contents; } diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 2f3fea7..dd827bd 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -4,11 +4,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -import java.io.IOException; - import org.json.JSONArray; import org.json.JSONException; -import org.json.JSONML; import org.json.JSONObject; import org.json.XML; import org.junit.Rule; From 95da4246a279d19db770f27dbb8e3d7eb5befdce Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 27 Apr 2017 12:48:43 -0400 Subject: [PATCH 275/451] fix spelling in comment --- src/test/java/org/json/junit/JSONMLTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 1ad2cb4..df5244d 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -782,7 +782,7 @@ public class JSONMLTest { // this test does not pass for the following reasons: // 1. Our XML parser does not handle generic HTML entities, only valid XML entities. Hence   -// or other HTML specific entites would fail on reversability +// or other HTML specific entities would fail on reversability // 2. Our JSON implementation for storing the XML attributes uses the standard unordered map. // This means that can not be reversed reliably. // /** From c233ae709e6d4c6da2296fc366e37de290935090 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 27 Apr 2017 12:52:02 -0400 Subject: [PATCH 276/451] comment out second unreliable test --- src/test/java/org/json/junit/JSONMLTest.java | 43 ++++++++++---------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index df5244d..8ece8e5 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -762,29 +762,30 @@ public class JSONMLTest { assertEquals("original JSON does not equal the new JSON",originalJson, newJson); } - /** - * Test texts taken from jsonml.org. Currently our implementation FAILS this conversion but shouldn't. - * Technically JsonML should be able to transform any valid xhtml document, but ours only supports - * standard XML entities, not HTML entities. - */ - @Test - public void testAttributeConversionReversabilityHTML() { - final String originalXml = "
#5D28D1Example text here
#AF44EF127310656
#AAD034 © 
"; - final String expectedJsonString = "[\"table\",{\"class\" : \"MyTable\",\"style\" : \"background-color:yellow\"},[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#550758\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:red\"},\"Example text here\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#993101\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:green\"},\"127624015\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#E33D87\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:blue\"},\"\u00A0\",[\"span\",{ \"style\" : \"background-color:maroon\" },\"\u00A9\"],\"\u00A0\"]]]"; - final JSONArray json = JSONML.toJSONArray(originalXml,true); - final String actualJsonString = json.toString(); - - final String reverseXml = JSONML.toString(json); - assertNotEquals(originalXml, reverseXml); - - assertNotEquals(expectedJsonString, actualJsonString); - } - -// this test does not pass for the following reasons: +// these tests do not pass for the following reasons: // 1. Our XML parser does not handle generic HTML entities, only valid XML entities. Hence   -// or other HTML specific entities would fail on reversability +// or other HTML specific entities would fail on reversability // 2. Our JSON implementation for storing the XML attributes uses the standard unordered map. -// This means that can not be reversed reliably. +// This means that can not be reversed reliably. +// +// /** +// * Test texts taken from jsonml.org. Currently our implementation FAILS this conversion but shouldn't. +// * Technically JsonML should be able to transform any valid xhtml document, but ours only supports +// * standard XML entities, not HTML entities. +// */ +// @Test +// public void testAttributeConversionReversabilityHTML() { +// final String originalXml = "
#5D28D1Example text here
#AF44EF127310656
#AAD034 © 
"; +// final String expectedJsonString = "[\"table\",{\"class\" : \"MyTable\",\"style\" : \"background-color:yellow\"},[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#550758\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:red\"},\"Example text here\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#993101\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:green\"},\"127624015\"]],[\"tr\",[\"td\",{\"class\" : \"MyTD\",\"style\" : \"border:1px solid black\"},\"#E33D87\"],[\"td\",{\"class\" : \"MyTD\",\"style\" : \"background-color:blue\"},\"\u00A0\",[\"span\",{ \"style\" : \"background-color:maroon\" },\"\u00A9\"],\"\u00A0\"]]]"; +// final JSONArray json = JSONML.toJSONArray(originalXml,true); +// final String actualJsonString = json.toString(); +// +// final String reverseXml = JSONML.toString(json); +// assertNotEquals(originalXml, reverseXml); +// +// assertNotEquals(expectedJsonString, actualJsonString); +// } +// // /** // * Test texts taken from jsonml.org but modified to have XML entities only. // */ From cbd8b18c4a52e9f17e5f463d62b2d6bf22c253dd Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 16 May 2017 00:29:00 -0500 Subject: [PATCH 277/451] Update README --- README | 1 + 1 file changed, 1 insertion(+) diff --git a/README b/README index e5be06b..2fbae18 100644 --- a/README +++ b/README @@ -89,6 +89,7 @@ invalid number formats (1.2e6.3) will cause errors as such documents can not be reliably. Release history: +20170516 Roll up recent commits. 20160810 Revert code that was breaking opt*() methods. From c870094f691e7b9e690111ed780a6e5d73a6fa68 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 16 May 2017 15:35:05 -0400 Subject: [PATCH 278/451] Fixes spelling in comments and removes compile time warnings --- CookieList.java | 2 +- JSONArray.java | 7 ++++--- JSONObject.java | 52 +++++++++++++++++++++++++++++++++++------------ JSONPointer.java | 34 ++++++++++++++++--------------- JSONStringer.java | 1 + JSONWriter.java | 10 ++++----- XML.java | 30 +++++++++++++-------------- 7 files changed, 82 insertions(+), 54 deletions(-) diff --git a/CookieList.java b/CookieList.java index 7a5628e..d69e457 100644 --- a/CookieList.java +++ b/CookieList.java @@ -39,7 +39,7 @@ public class CookieList { * The pairs are separated by ';'. The names and the values * will be unescaped, possibly converting '+' and '%' sequences. * - * To add a cookie to a cooklist, + * To add a cookie to a cookie list, * cookielistJSONObject.put(cookieJSONObject.getString("name"), * cookieJSONObject.getString("value")); * @param string A cookie list string diff --git a/JSONArray.java b/JSONArray.java index 132d46d..36e7cad 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -183,7 +183,7 @@ public class JSONArray implements Iterable { @Override public Iterator iterator() { - return myArrayList.iterator(); + return this.myArrayList.iterator(); } /** @@ -1115,6 +1115,7 @@ public class JSONArray implements Iterable { * @return a printable, displayable, transmittable representation of the * array. */ + @Override public String toString() { try { return this.toString(0); @@ -1124,7 +1125,7 @@ public class JSONArray implements Iterable { } /** - * Make a prettyprinted JSON text of this JSONArray. Warning: This method + * Make a pretty-printed JSON text of this JSONArray. Warning: This method * assumes that the data structure is acyclical. * * @param indentFactor @@ -1166,7 +1167,7 @@ public class JSONArray implements Iterable { * @param indentFactor * The number of spaces to add to each level of indentation. * @param indent - * The indention of the top level. + * The indentation of the top level. * @return The writer. * @throws JSONException */ diff --git a/JSONObject.java b/JSONObject.java index b71b3b6..f58f2dc 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -126,6 +126,15 @@ public class JSONObject { public boolean equals(Object object) { return object == null || object == this; } + /** + * A Null object is equal to the null value and to itself. + * + * @return always returns 0. + */ + @Override + public int hashCode() { + return 0; + } /** * Get the "null" string value. @@ -754,13 +763,13 @@ public class JSONObject { } else if (value instanceof BigDecimal) { this.put(key, ((BigDecimal)value).add(BigDecimal.ONE)); } else if (value instanceof Integer) { - this.put(key, (Integer) value + 1); + this.put(key, ((Integer) value).intValue() + 1); } else if (value instanceof Long) { - this.put(key, (Long) value + 1); + this.put(key, ((Long) value).longValue() + 1L); } else if (value instanceof Double) { - this.put(key, (Double) value + 1); + this.put(key, ((Double) value).doubleValue() + 1D); } else if (value instanceof Float) { - this.put(key, (Float) value + 1); + this.put(key, ((Float) value).floatValue() + 1F); } else { throw new JSONException("Unable to increment [" + quote(key) + "]."); } @@ -887,7 +896,7 @@ public class JSONObject { * @param defaultValue * The default in case the value is not found * @return The enum value associated with the key or defaultValue - * if the value is not found or cannot be assigned to clazz + * if the value is not found or cannot be assigned to clazz */ public > E optEnum(Class clazz, String key, E defaultValue) { try { @@ -1218,7 +1227,23 @@ public class JSONObject { * If the key is null or if the number is invalid. */ public JSONObject put(String key, double value) throws JSONException { - this.put(key, new Double(value)); + this.put(key, Double.valueOf(value)); + return this; + } + + /** + * Put a key/float pair in the JSONObject. + * + * @param key + * A key string. + * @param value + * A float which is the value. + * @return this. + * @throws JSONException + * If the key is null or if the number is invalid. + */ + public JSONObject put(String key, float value) throws JSONException { + this.put(key, Float.valueOf(value)); return this; } @@ -1234,7 +1259,7 @@ public class JSONObject { * If the key is null. */ public JSONObject put(String key, int value) throws JSONException { - this.put(key, new Integer(value)); + this.put(key, Integer.valueOf(value)); return this; } @@ -1250,7 +1275,7 @@ public class JSONObject { * If the key is null. */ public JSONObject put(String key, long value) throws JSONException { - this.put(key, new Long(value)); + this.put(key, Long.valueOf(value)); return this; } @@ -1340,7 +1365,7 @@ public class JSONObject { } /** - * Creates a JSONPointer using an intialization string and tries to + * Creates a JSONPointer using an initialization string and tries to * match it to an item within this JSONObject. For example, given a * JSONObject initialized with this document: *
@@ -1362,7 +1387,7 @@ public class JSONObject {
         return query(new JSONPointer(jsonPointer));
     }
     /**
-     * Uses a uaer initialized JSONPointer  and tries to 
+     * Uses a user initialized JSONPointer  and tries to 
      * match it to an item within this JSONObject. For example, given a
      * JSONObject initialized with this document:
      * 
@@ -1665,7 +1690,7 @@ public class JSONObject {
     }
 
     /**
-     * Make a prettyprinted JSON text of this JSONObject.
+     * Make a pretty-printed JSON text of this JSONObject.
      * 

* Warning: This method assumes that the data structure is acyclical. * @@ -1730,7 +1755,8 @@ public class JSONObject { final String numberAsString = numberToString((Number) value); try { // Use the BigDecimal constructor for it's parser to validate the format. - new BigDecimal(numberAsString); + @SuppressWarnings("unused") + BigDecimal unused = new BigDecimal(numberAsString); // Close enough to a JSON number that we will return it unquoted return numberAsString; } catch (NumberFormatException ex){ @@ -1891,7 +1917,7 @@ public class JSONObject { * @param indentFactor * The number of spaces to add to each level of indentation. * @param indent - * The indention of the top level. + * The indentation of the top level. * @return The writer. * @throws JSONException */ diff --git a/JSONPointer.java b/JSONPointer.java index 82de7f9..8142f9a 100644 --- a/JSONPointer.java +++ b/JSONPointer.java @@ -68,11 +68,11 @@ public class JSONPointer { * {@link #append(String)} method calls. */ public JSONPointer build() { - return new JSONPointer(refTokens); + return new JSONPointer(this.refTokens); } /** - * Adds an arbitary token to the list of reference tokens. It can be any non-null value. + * Adds an arbitrary token to the list of reference tokens. It can be any non-null value. * * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the * argument of this method MUST NOT be escaped. If you want to query the property called @@ -87,7 +87,7 @@ public class JSONPointer { if (token == null) { throw new NullPointerException("token cannot be null"); } - refTokens.add(token); + this.refTokens.add(token); return this; } @@ -99,7 +99,7 @@ public class JSONPointer { * @return {@code this} */ public Builder append(int arrayIndex) { - refTokens.add(String.valueOf(arrayIndex)); + this.refTokens.add(String.valueOf(arrayIndex)); return this; } } @@ -134,29 +134,30 @@ public class JSONPointer { * @param pointer the JSON String or URI Fragment representation of the JSON pointer. * @throws IllegalArgumentException if {@code pointer} is not a valid JSON pointer */ - public JSONPointer(String pointer) { + public JSONPointer(final String pointer) { if (pointer == null) { throw new NullPointerException("pointer cannot be null"); } if (pointer.isEmpty() || pointer.equals("#")) { - refTokens = Collections.emptyList(); + this.refTokens = Collections.emptyList(); return; } + String refs; if (pointer.startsWith("#/")) { - pointer = pointer.substring(2); + refs = pointer.substring(2); try { - pointer = URLDecoder.decode(pointer, ENCODING); + refs = URLDecoder.decode(refs, ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } else if (pointer.startsWith("/")) { - pointer = pointer.substring(1); + refs = pointer.substring(1); } else { throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'"); } - refTokens = new ArrayList(); - for (String token : pointer.split("/")) { - refTokens.add(unescape(token)); + this.refTokens = new ArrayList(); + for (String token : refs.split("/")) { + this.refTokens.add(unescape(token)); } } @@ -181,11 +182,11 @@ public class JSONPointer { * @throws JSONPointerException if an error occurs during evaluation */ public Object queryFrom(Object document) { - if (refTokens.isEmpty()) { + if (this.refTokens.isEmpty()) { return document; } Object current = document; - for (String token : refTokens) { + for (String token : this.refTokens) { if (current instanceof JSONObject) { current = ((JSONObject) current).opt(unescape(token)); } else if (current instanceof JSONArray) { @@ -206,6 +207,7 @@ public class JSONPointer { * @return the matched object. If no matching item is found a * JSONPointerException is thrown */ + @SuppressWarnings("boxing") private Object readByIndexToken(Object current, String indexToken) { try { int index = Integer.parseInt(indexToken); @@ -227,7 +229,7 @@ public class JSONPointer { @Override public String toString() { StringBuilder rval = new StringBuilder(""); - for (String token: refTokens) { + for (String token: this.refTokens) { rval.append('/').append(escape(token)); } return rval.toString(); @@ -255,7 +257,7 @@ public class JSONPointer { public String toURIFragment() { try { StringBuilder rval = new StringBuilder("#"); - for (String token : refTokens) { + for (String token : this.refTokens) { rval.append('/').append(URLEncoder.encode(token, ENCODING)); } return rval.toString(); diff --git a/JSONStringer.java b/JSONStringer.java index 5fbc96a..6e05d22 100644 --- a/JSONStringer.java +++ b/JSONStringer.java @@ -72,6 +72,7 @@ public class JSONStringer extends JSONWriter { * endArray). * @return The JSON text. */ + @Override public String toString() { return this.mode == 'd' ? this.writer.toString() : null; } diff --git a/JSONWriter.java b/JSONWriter.java index 696ee23..549f93e 100644 --- a/JSONWriter.java +++ b/JSONWriter.java @@ -149,18 +149,18 @@ public class JSONWriter { /** * End something. - * @param mode Mode + * @param m Mode * @param c Closing character * @return this * @throws JSONException If unbalanced. */ - private JSONWriter end(char mode, char c) throws JSONException { - if (this.mode != mode) { - throw new JSONException(mode == 'a' + private JSONWriter end(char m, char c) throws JSONException { + if (this.mode != m) { + throw new JSONException(m == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } - this.pop(mode); + this.pop(m); try { this.writer.append(c); } catch (IOException e) { diff --git a/XML.java b/XML.java index 78dd6a0..a438078 100644 --- a/XML.java +++ b/XML.java @@ -211,7 +211,7 @@ public class XML { sb.append('<'); } else if ("gt".equalsIgnoreCase(entity)) { sb.append('>'); - } else { + } else {// unsupported xml entity. leave encoded sb.append('&').append(entity).append(';'); } } @@ -219,7 +219,7 @@ public class XML { i += entity.length() + 1; } else { // this shouldn't happen in most cases since the parser - // errors on unclosed enties. + // errors on unclosed entries. sb.append(c); } } else { @@ -508,7 +508,7 @@ public class XML { * @return A string. * @throws JSONException Thrown if there is an error parsing the string */ - public static String toString(Object object, String tagName) + public static String toString(final Object object, final String tagName) throws JSONException { StringBuilder sb = new StringBuilder(); JSONArray ja; @@ -595,21 +595,19 @@ public class XML { } - if (object != null) { - if (object.getClass().isArray()) { - object = new JSONArray(object); - } - - if (object instanceof JSONArray) { + if (object != null && (object instanceof JSONArray || object.getClass().isArray())) { + if(object.getClass().isArray()) { + ja = new JSONArray(object); + } else { ja = (JSONArray) object; - for (Object val : ja) { - // XML does not have good support for arrays. If an array - // appears in a place where XML is lacking, synthesize an - // element. - sb.append(toString(val, tagName == null ? "array" : tagName)); - } - return sb.toString(); } + for (Object val : ja) { + // XML does not have good support for arrays. If an array + // appears in a place where XML is lacking, synthesize an + // element. + sb.append(toString(val, tagName == null ? "array" : tagName)); + } + return sb.toString(); } string = (object == null) ? "null" : escape(object.toString()); From 4865f51dd517e4ef78051fce2c5c24bdaa7cc3e6 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 16 May 2017 15:38:54 -0400 Subject: [PATCH 279/451] change float double literals to be more standard as 1.0f and 1.0d respectively --- JSONObject.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index f58f2dc..512e4ae 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -767,9 +767,9 @@ public class JSONObject { } else if (value instanceof Long) { this.put(key, ((Long) value).longValue() + 1L); } else if (value instanceof Double) { - this.put(key, ((Double) value).doubleValue() + 1D); + this.put(key, ((Double) value).doubleValue() + 1.0d); } else if (value instanceof Float) { - this.put(key, ((Float) value).floatValue() + 1F); + this.put(key, ((Float) value).floatValue() + 1.0f); } else { throw new JSONException("Unable to increment [" + quote(key) + "]."); } From 1d040ec407bd5d6e2b8339af0769ad1047415ad8 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 16 May 2017 18:16:07 -0400 Subject: [PATCH 280/451] fixes errors with tests relating to https://github.com/stleary/JSON-java/pull/336 --- src/test/java/org/json/junit/JSONObjectTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index fb32cda..4af66bf 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1276,7 +1276,7 @@ public class JSONObjectTest { * JSONObject constructor won't handle these types correctly, but * adding them via put works. */ - jsonObject.put("keyFloat", new Float(1.1)); + jsonObject.put("keyFloat", 1.1f); jsonObject.put("keyBigInt", new BigInteger("123456789123456789123456789123456780")); jsonObject.put("keyBigDec", new BigDecimal("123456789123456789123456789123456780.1")); jsonObject.increment("keyFloat"); @@ -1316,7 +1316,7 @@ public class JSONObjectTest { * missing bits would not fit into the 32 bit float, i.e. the * information needed simply is not there! */ - assertTrue("expected 3.0999999046325684", Double.valueOf(3.0999999046325684).equals(jsonObject.query("/keyFloat"))); + assertEquals(Float.valueOf(3.1f), jsonObject.query("/keyFloat")); /** * float f = 3.1f; double df = (double) f; double d = 3.1d; @@ -1364,7 +1364,7 @@ public class JSONObjectTest { // 3. A float+float operation will be performed and results into a float primitive. // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa - assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Double ); + assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Float ); // correct implementation (with change of behavior) would be: // this.put(key, new Float((Float) value + 1)); // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not From a8d4e4734fe499a832527e333473daad61416f8c Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 16 May 2017 19:38:01 -0400 Subject: [PATCH 281/451] adjustments to opt methods in reference to https://github.com/stleary/JSON-java/issues/334 --- JSONObject.java | 113 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 94 insertions(+), 19 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index b71b3b6..ad08c79 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -540,7 +540,7 @@ public class JSONObject { return new BigInteger(object.toString()); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) - + "] could not be converted to BigInteger."); + + "] could not be converted to BigInteger.", e); } } @@ -556,11 +556,14 @@ public class JSONObject { */ public BigDecimal getBigDecimal(String key) throws JSONException { Object object = this.get(key); + if (object instanceof BigDecimal) { + return (BigDecimal)object; + } try { return new BigDecimal(object.toString()); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) - + "] could not be converted to BigDecimal."); + + "] could not be converted to BigDecimal.", e); } } @@ -578,10 +581,10 @@ public class JSONObject { Object object = this.get(key); try { return object instanceof Number ? ((Number) object).doubleValue() - : Double.parseDouble((String) object); + : new BigDecimal((String) object).doubleValue(); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) - + "] is not a number."); + + "] is not a number.", e); } } @@ -602,7 +605,7 @@ public class JSONObject { : Integer.parseInt((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) - + "] is not an int."); + + "] is not an int.", e); } } @@ -659,7 +662,7 @@ public class JSONObject { : Long.parseLong((String) object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) - + "] is not a long."); + + "] is not a long.", e); } } @@ -678,7 +681,7 @@ public class JSONObject { int i = 0; while (iterator.hasNext()) { names[i] = iterator.next(); - i += 1; + i++; } return names; } @@ -933,7 +936,15 @@ public class JSONObject { * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Boolean){ + return ((Boolean) val).booleanValue(); + } try { + // we'll use the get anyway because it does string conversion. return this.getBoolean(key); } catch (Exception e) { return defaultValue; @@ -965,8 +976,23 @@ public class JSONObject { * @return An object which is the value. */ public BigInteger optBigInteger(String key, BigInteger defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof BigInteger){ + return (BigInteger) val; + } + if (val instanceof BigDecimal){ + return ((BigDecimal) val).toBigInteger(); + } try { - return this.getBigInteger(key); + // the other opt functions handle implicit conversions, i.e. + // jo.put("double",1.1d); + // jo.optInt("double"); -- will return 1, not an error + // this conversion to BigDecimal then to BigInteger is to maintain + // that type cast support that may truncate the decimal. + return new BigDecimal(val.toString()).toBigInteger(); } catch (Exception e) { return defaultValue; } @@ -984,8 +1010,25 @@ public class JSONObject { * @return An object which is the value. */ public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof BigDecimal){ + return (BigDecimal) val; + } + if (val instanceof BigInteger){ + return new BigDecimal((BigInteger) val); + } + if (val instanceof Double){ + return new BigDecimal(((Double) val).doubleValue()); + } + if (val instanceof Long || val instanceof Integer + || val instanceof Short || val instanceof Byte){ + return new BigDecimal(((Number) val).longValue()); + } try { - return this.getBigDecimal(key); + return new BigDecimal(val.toString()); } catch (Exception e) { return defaultValue; } @@ -1003,11 +1046,21 @@ public class JSONObject { * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { - try { - return this.getDouble(key); - } catch (Exception e) { + Object val = this.opt(key); + if (NULL.equals(val)) { return defaultValue; } + if (val instanceof Number){ + return ((Number) val).doubleValue(); + } + if (val instanceof String) { + try { + return new BigDecimal((String) val).doubleValue(); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; } /** @@ -1035,11 +1088,22 @@ public class JSONObject { * @return An object which is the value. */ public int optInt(String key, int defaultValue) { - try { - return this.getInt(key); - } catch (Exception e) { + Object val = this.opt(key); + if (NULL.equals(val)) { return defaultValue; } + if (val instanceof Number){ + return ((Number) val).intValue(); + } + + if (val instanceof String) { + try { + return new BigDecimal(val.toString()).intValue(); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; } /** @@ -1093,11 +1157,22 @@ public class JSONObject { * @return An object which is the value. */ public long optLong(String key, long defaultValue) { - try { - return this.getLong(key); - } catch (Exception e) { + Object val = this.opt(key); + if (NULL.equals(val)) { return defaultValue; } + if (val instanceof Number){ + return ((Number) val).longValue(); + } + + if (val instanceof String) { + try { + return new BigDecimal(val.toString()).longValue(); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; } /** @@ -1583,7 +1658,7 @@ public class JSONObject { return d; } } else { - Long myLong = new Long(string); + Long myLong = Long.valueOf(string); if (string.equals(myLong.toString())) { if (myLong.longValue() == myLong.intValue()) { return Integer.valueOf(myLong.intValue()); From 49d47e3ff281a5fecc9889e2d8d37ca76e355cbd Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 16 May 2017 19:42:46 -0400 Subject: [PATCH 282/451] Adjustments to tests for https://github.com/stleary/JSON-java/pull/337/ --- src/test/java/org/json/junit/JSONObjectTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index fb32cda..f6a562d 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1001,7 +1001,8 @@ public class JSONObjectTest { assertTrue("expected an exeption", false); } catch (JSONException ignored) {} obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); - assertTrue("expected BigInteger", obj.equals(BigInteger.ONE)); + assertTrue("expected BigInteger", obj instanceof BigInteger); + assertEquals(bigDecimal.toBigInteger(), obj); /** * JSONObject.numberToString() works correctly, nothing to change. From bd4b180f4e6aae77dc2e49742dc699683edc93c3 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 17 May 2017 10:51:06 -0400 Subject: [PATCH 283/451] Support for float to BigDecimal in optBigDecimal --- JSONObject.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index ad08c79..0557882 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1020,8 +1020,8 @@ public class JSONObject { if (val instanceof BigInteger){ return new BigDecimal((BigInteger) val); } - if (val instanceof Double){ - return new BigDecimal(((Double) val).doubleValue()); + if (val instanceof Double || val instanceof Float){ + return new BigDecimal(((Number) val).doubleValue()); } if (val instanceof Long || val instanceof Integer || val instanceof Short || val instanceof Byte){ From c46774cf1314a0a1e640374b20006594e014e9a9 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 17 May 2017 11:29:26 -0400 Subject: [PATCH 284/451] * Update opt* methods for JSONArray * Add support to JSONArray and JSONObject to optionally get raw number values * Add support to JSONArray and JSONObject to optionally get float values --- JSONArray.java | 161 +++++++++++++++++++++++++++++++++++++--- JSONObject.java | 190 ++++++++++++++++++++++++++++++++++++------------ 2 files changed, 293 insertions(+), 58 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 132d46d..18d43ce 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -518,11 +518,63 @@ public class JSONArray implements Iterable { * @return The value. */ public double optDouble(int index, double defaultValue) { - try { - return this.getDouble(index); - } catch (Exception e) { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { return defaultValue; } + if (val instanceof Number){ + return ((Number) val).doubleValue(); + } + if (val instanceof String) { + try { + return new BigDecimal((String) val).doubleValue(); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; + } + + /** + * Get the optional double value associated with an index. NaN is returned + * if there is no value for the index, or if the value is not a number and + * cannot be converted to a number. + * + * @param index + * The index must be between 0 and length() - 1. + * @return The value. + */ + public float optFloat(int index) { + return this.optFloat(index, Float.NaN); + } + + /** + * Get the optional double value associated with an index. The defaultValue + * is returned if there is no value for the index, or if the value is not a + * number and cannot be converted to a number. + * + * @param index + * subscript + * @param defaultValue + * The default value. + * @return The value. + */ + public float optFloat(int index, float defaultValue) { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Number){ + return ((Number) val).floatValue(); + } + if (val instanceof String) { + try { + return new BigDecimal((String) val).floatValue(); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; } /** @@ -550,11 +602,22 @@ public class JSONArray implements Iterable { * @return The value. */ public int optInt(int index, int defaultValue) { - try { - return this.getInt(index); - } catch (Exception e) { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { return defaultValue; } + if (val instanceof Number){ + return ((Number) val).intValue(); + } + + if (val instanceof String) { + try { + return new BigDecimal(val.toString()).intValue(); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; } /** @@ -615,8 +678,25 @@ public class JSONArray implements Iterable { * @return The value. */ public BigInteger optBigInteger(int index, BigInteger defaultValue) { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { + return defaultValue; + } + if (val instanceof BigInteger){ + return (BigInteger) val; + } + if (val instanceof BigDecimal){ + return ((BigDecimal) val).toBigInteger(); + } + if (val instanceof Double || val instanceof Float){ + return new BigDecimal(((Number) val).doubleValue()).toBigInteger(); + } + if (val instanceof Long || val instanceof Integer + || val instanceof Short || val instanceof Byte){ + return BigInteger.valueOf(((Number) val).longValue()); + } try { - return this.getBigInteger(index); + return new BigDecimal(val.toString()).toBigInteger(); } catch (Exception e) { return defaultValue; } @@ -634,8 +714,25 @@ public class JSONArray implements Iterable { * @return The value. */ public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { + return defaultValue; + } + if (val instanceof BigDecimal){ + return (BigDecimal) val; + } + if (val instanceof BigInteger){ + return new BigDecimal((BigInteger) val); + } + if (val instanceof Double || val instanceof Float){ + return new BigDecimal(((Number) val).doubleValue()); + } + if (val instanceof Long || val instanceof Integer + || val instanceof Short || val instanceof Byte){ + return new BigDecimal(((Number) val).longValue()); + } try { - return this.getBigDecimal(index); + return new BigDecimal(val.toString()); } catch (Exception e) { return defaultValue; } @@ -693,11 +790,53 @@ public class JSONArray implements Iterable { * @return The value. */ public long optLong(int index, long defaultValue) { - try { - return this.getLong(index); - } catch (Exception e) { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { return defaultValue; } + if (val instanceof Number){ + return ((Number) val).longValue(); + } + + if (val instanceof String) { + try { + return new BigDecimal(val.toString()).longValue(); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; + } + + /** + * Get an optional {@link Number} value associated with a key, or the default if there + * is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method + * would be used in cases where type coercion of the number value is unwanted. + * + * @param index + * The index must be between 0 and length() - 1. + * @param defaultValue + * The default. + * @return An object which is the value. + */ + public Number optNumber(int index, Number defaultValue) { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Number){ + return (Number) val; + } + + if (val instanceof String) { + try { + return new BigDecimal(val.toString()); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; } /** diff --git a/JSONObject.java b/JSONObject.java index 0557882..13ba48e 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -951,53 +951,6 @@ public class JSONObject { } } - /** - * Get an optional double associated with a key, or NaN if there is no such - * key or if its value is not a number. If the value is a string, an attempt - * will be made to evaluate it as a number. - * - * @param key - * A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) { - return this.optDouble(key, Double.NaN); - } - - /** - * Get an optional BigInteger associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public BigInteger optBigInteger(String key, BigInteger defaultValue) { - Object val = this.opt(key); - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof BigInteger){ - return (BigInteger) val; - } - if (val instanceof BigDecimal){ - return ((BigDecimal) val).toBigInteger(); - } - try { - // the other opt functions handle implicit conversions, i.e. - // jo.put("double",1.1d); - // jo.optInt("double"); -- will return 1, not an error - // this conversion to BigDecimal then to BigInteger is to maintain - // that type cast support that may truncate the decimal. - return new BigDecimal(val.toString()).toBigInteger(); - } catch (Exception e) { - return defaultValue; - } - } - /** * Get an optional BigDecimal associated with a key, or the defaultValue if * there is no such key or if its value is not a number. If the value is a @@ -1034,6 +987,60 @@ public class JSONObject { } } + /** + * Get an optional BigInteger associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. + * + * @param key + * A key string. + * @param defaultValue + * The default. + * @return An object which is the value. + */ + public BigInteger optBigInteger(String key, BigInteger defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof BigInteger){ + return (BigInteger) val; + } + if (val instanceof BigDecimal){ + return ((BigDecimal) val).toBigInteger(); + } + if (val instanceof Double || val instanceof Float){ + return new BigDecimal(((Number) val).doubleValue()).toBigInteger(); + } + if (val instanceof Long || val instanceof Integer + || val instanceof Short || val instanceof Byte){ + return BigInteger.valueOf(((Number) val).longValue()); + } + try { + // the other opt functions handle implicit conversions, i.e. + // jo.put("double",1.1d); + // jo.optInt("double"); -- will return 1, not an error + // this conversion to BigDecimal then to BigInteger is to maintain + // that type cast support that may truncate the decimal. + return new BigDecimal(val.toString()).toBigInteger(); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional double associated with a key, or NaN if there is no such + * key or if its value is not a number. If the value is a string, an attempt + * will be made to evaluate it as a number. + * + * @param key + * A string which is the key. + * @return An object which is the value. + */ + public double optDouble(String key) { + return this.optDouble(key, Double.NaN); + } + /** * Get an optional double associated with a key, or the defaultValue if * there is no such key or if its value is not a number. If the value is a @@ -1063,6 +1070,48 @@ public class JSONObject { return defaultValue; } + /** + * Get the optional double value associated with an index. NaN is returned + * if there is no value for the index, or if the value is not a number and + * cannot be converted to a number. + * + * @param index + * The index must be between 0 and length() - 1. + * @return The value. + */ + public float optFloat(String key) { + return this.optFloat(key, Float.NaN); + } + + /** + * Get the optional double value associated with an index. The defaultValue + * is returned if there is no value for the index, or if the value is not a + * number and cannot be converted to a number. + * + * @param index + * subscript + * @param defaultValue + * The default value. + * @return The value. + */ + public float optFloat(String key, float defaultValue) { + Object val = this.opt(key); + if (JSONObject.NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Number){ + return ((Number) val).floatValue(); + } + if (val instanceof String) { + try { + return new BigDecimal((String) val).floatValue(); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; + } + /** * Get an optional int value associated with a key, or zero if there is no * such key or if the value is not a number. If the value is a string, an @@ -1174,6 +1223,53 @@ public class JSONObject { } return defaultValue; } + + /** + * Get an optional {@link Number} value associated with a key, or null + * if there is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method + * would be used in cases where type coercion of the number value is unwanted. + * + * @param key + * A key string. + * @param defaultValue + * The default. + * @return An object which is the value. + */ + public Number optNumber(String key) { + return this.optNumber(key, null); + } + + /** + * Get an optional {@link Number} value associated with a key, or the default if there + * is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method + * would be used in cases where type coercion of the number value is unwanted. + * + * @param key + * A key string. + * @param defaultValue + * The default. + * @return An object which is the value. + */ + public Number optNumber(String key, Number defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Number){ + return (Number) val; + } + + if (val instanceof String) { + try { + return new BigDecimal(val.toString()); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; + } /** * Get an optional string associated with a key. It returns an empty string From fcdb8671b28eb74964d86ee53a9f96a81cd5423e Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 17 May 2017 11:32:44 -0400 Subject: [PATCH 285/451] grr, forgot to save changes on last commit --- JSONArray.java | 20 ++++++++++++++++++-- JSONObject.java | 8 ++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 18d43ce..bfab701 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -536,7 +536,7 @@ public class JSONArray implements Iterable { } /** - * Get the optional double value associated with an index. NaN is returned + * Get the optional float value associated with an index. NaN is returned * if there is no value for the index, or if the value is not a number and * cannot be converted to a number. * @@ -549,7 +549,7 @@ public class JSONArray implements Iterable { } /** - * Get the optional double value associated with an index. The defaultValue + * Get the optional float value associated with an index. The defaultValue * is returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * @@ -808,6 +808,22 @@ public class JSONArray implements Iterable { return defaultValue; } + /** + * Get an optional {@link Number} value associated with a key, or null + * if there is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method + * would be used in cases where type coercion of the number value is unwanted. + * + * @param index + * The index must be between 0 and length() - 1. + * @param defaultValue + * The default. + * @return An object which is the value. + */ + public Number optNumber(int index) { + return this.optNumber(index, null); + } + /** * Get an optional {@link Number} value associated with a key, or the default if there * is no such key or if the value is not a number. If the value is a string, diff --git a/JSONObject.java b/JSONObject.java index 13ba48e..3ca47d0 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1075,8 +1075,8 @@ public class JSONObject { * if there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. + * @param key + * A key string. * @return The value. */ public float optFloat(String key) { @@ -1088,8 +1088,8 @@ public class JSONObject { * is returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * - * @param index - * subscript + * @param key + * A key string. * @param defaultValue * The default value. * @return The value. From 0c7bd725a684764ac162c061fc66129461b503b2 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 17 May 2017 11:34:13 -0400 Subject: [PATCH 286/451] fixes for javadoc --- JSONArray.java | 4 +--- JSONObject.java | 2 -- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index bfab701..a692ba4 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -816,8 +816,6 @@ public class JSONArray implements Iterable { * * @param index * The index must be between 0 and length() - 1. - * @param defaultValue - * The default. * @return An object which is the value. */ public Number optNumber(int index) { @@ -858,7 +856,7 @@ public class JSONArray implements Iterable { /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value is not a - * string and is not null, then it is coverted to a string. + * string and is not null, then it is converted to a string. * * @param index * The index must be between 0 and length() - 1. diff --git a/JSONObject.java b/JSONObject.java index 3ca47d0..09b4317 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1232,8 +1232,6 @@ public class JSONObject { * * @param key * A key string. - * @param defaultValue - * The default. * @return An object which is the value. */ public Number optNumber(String key) { From 2867aaa8c8c219b2eddb755df4dfda667f955f4b Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 17 May 2017 12:33:59 -0400 Subject: [PATCH 287/451] Updates test cases to support new optFloat and optNumber --- .../java/org/json/junit/JSONArrayTest.java | 14 +++++++ .../java/org/json/junit/JSONObjectTest.java | 40 +++++++++++++++---- 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 80b78a5..666c03b 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -393,6 +393,20 @@ public class JSONArrayTest { assertTrue("Array opt double default implicit", new Double(jsonArray.optDouble(99)).isNaN()); + assertTrue("Array opt float", + new Float(23.45e-4).equals(jsonArray.optFloat(5))); + assertTrue("Array opt float default", + new Float(1).equals(jsonArray.optFloat(0, 1))); + assertTrue("Array opt float default implicit", + new Float(jsonArray.optFloat(99)).isNaN()); + + assertTrue("Array opt Number", + new Double(23.45e-4).equals(jsonArray.optNumber(5))); + assertTrue("Array opt Number default", + new Double(1).equals(jsonArray.optNumber(0, 1d))); + assertTrue("Array opt Number default implicit", + new Double(jsonArray.optNumber(99,Double.NaN).doubleValue()).isNaN()); + assertTrue("Array opt int", new Integer(42).equals(jsonArray.optInt(7))); assertTrue("Array opt int default", diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index f6a562d..2718edf 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -614,6 +614,10 @@ public class JSONObjectTest { jsonObject.optDouble("doubleKey") == -23.45e7); assertTrue("opt doubleKey with Default should be double", jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); + assertTrue("optFloat doubleKey should be float", + jsonObject.optFloat("doubleKey") == -23.45e7f); + assertTrue("optFloat doubleKey with Default should be float", + jsonObject.optFloat("doubleStrKey", Float.NaN) == 1f); assertTrue("intKey should be int", jsonObject.optInt("intKey") == 42); assertTrue("opt intKey should be int", @@ -630,6 +634,18 @@ public class JSONObjectTest { jsonObject.optLong("longKey", 0) == 1234567890123456789L); assertTrue("longStrKey should be long", jsonObject.getLong("longStrKey") == 987654321098765432L); + assertTrue("optNumber int should return Integer", + jsonObject.optNumber("intKey") instanceof Integer); + assertTrue("optNumber long should return Long", + jsonObject.optNumber("longKey") instanceof Long); + assertTrue("optNumber double should return Double", + jsonObject.optNumber("doubleKey") instanceof Double); + assertTrue("optNumber Str int should return BigDecimal", + jsonObject.optNumber("intStrKey") instanceof BigDecimal); + assertTrue("optNumber Str long should return BigDecimal", + jsonObject.optNumber("longStrKey") instanceof BigDecimal); + assertTrue("optNumber Str double should return BigDecimal", + jsonObject.optNumber("doubleStrKey") instanceof BigDecimal); assertTrue("xKey should not exist", jsonObject.isNull("xKey")); assertTrue("stringKey should exist", @@ -1937,9 +1953,13 @@ public class JSONObjectTest { assertTrue("optJSONObject() should return null ", null==jsonObject.optJSONObject("myKey")); assertTrue("optLong() should return default long", - 42 == jsonObject.optLong("myKey", 42)); + 42l == jsonObject.optLong("myKey", 42l)); assertTrue("optDouble() should return default double", - 42.3 == jsonObject.optDouble("myKey", 42.3)); + 42.3d == jsonObject.optDouble("myKey", 42.3d)); + assertTrue("optFloat() should return default float", + 42.3f == jsonObject.optFloat("myKey", 42.3f)); + assertTrue("optNumber() should return default Number", + 42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue()); assertTrue("optString() should return default string", "hi".equals(jsonObject.optString("hiKey", "hi"))); } @@ -1967,9 +1987,13 @@ public class JSONObjectTest { assertTrue("optJSONObject() should return null ", null==jsonObject.optJSONObject("myKey")); assertTrue("optLong() should return default long", - 42 == jsonObject.optLong("myKey", 42)); + 42l == jsonObject.optLong("myKey", 42l)); assertTrue("optDouble() should return default double", - 42.3 == jsonObject.optDouble("myKey", 42.3)); + 42.3d == jsonObject.optDouble("myKey", 42.3d)); + assertTrue("optFloat() should return default float", + 42.3f == jsonObject.optFloat("myKey", 42.3f)); + assertTrue("optNumber() should return default Number", + 42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue()); assertTrue("optString() should return default string", "hi".equals(jsonObject.optString("hiKey", "hi"))); } @@ -1983,11 +2007,13 @@ public class JSONObjectTest { assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true); assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false); assertTrue("unexpected optInt value",jo.optInt("int",0)==123); - assertTrue("unexpected optLong value",jo.optLong("int",0)==123); - assertTrue("unexpected optDouble value",jo.optDouble("int",0.0)==123.0); + assertTrue("unexpected optLong value",jo.optLong("int",0)==123l); + assertTrue("unexpected optDouble value",jo.optDouble("int",0.0d)==123.0d); + assertTrue("unexpected optFloat value",jo.optFloat("int",0.0f)==123.0f); assertTrue("unexpected optBigInteger value",jo.optBigInteger("int",BigInteger.ZERO).compareTo(new BigInteger("123"))==0); assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); - + assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); + assertTrue("unexpected optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l); } /** From bdb11634459de86e67390a3519770c814c23631b Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 11:38:42 -0400 Subject: [PATCH 288/451] Adds conversion tests to ensure downward type coercions are handled sanely --- src/test/java/org/json/junit/JSONObjectTest.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 2718edf..13e4f5f 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -2003,7 +2003,7 @@ public class JSONObjectTest { */ @Test public void jsonObjectOptStringConversion() { - JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\"}"); + JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\",\"largeNumber\":\"19007199254740993.35481234487103587486413587843213584\"}"); assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true); assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false); assertTrue("unexpected optInt value",jo.optInt("int",0)==123); @@ -2014,6 +2014,15 @@ public class JSONObjectTest { assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); assertTrue("unexpected optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l); + + // Test type coercion from larger to smaller + final BigDecimal largeValue = new BigDecimal("19007199254740993.35481234487103587486413587843213584"); + assertEquals(largeValue,jo.optBigDecimal("largeNumber", null)); + assertEquals(largeValue.toBigInteger(),jo.optBigInteger("largeNumber", null)); + assertEquals(largeValue.doubleValue(), jo.optDouble("largeNumber"), 0.0d); + assertEquals(largeValue.floatValue(), jo.optFloat("largeNumber"), 0.0f); + assertEquals(largeValue.longValue(), jo.optLong("largeNumber")); + assertEquals(largeValue.intValue(), jo.optInt("largeNumber")); } /** From 382f62e78158b869169a7646e8b2e3ff05a7cf3d Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 11:41:51 -0400 Subject: [PATCH 289/451] * Prevent exceptions in cases where the value is not a string. * Don't call toString when we know it's a string, just cast --- JSONObject.java | 38 ++++++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index 09b4317..9765df4 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -980,11 +980,14 @@ public class JSONObject { || val instanceof Short || val instanceof Byte){ return new BigDecimal(((Number) val).longValue()); } - try { - return new BigDecimal(val.toString()); - } catch (Exception e) { - return defaultValue; + if (val instanceof String) { + try { + return new BigDecimal((String) val); + } catch (Exception e) { + return defaultValue; + } } + return defaultValue; } /** @@ -1016,16 +1019,19 @@ public class JSONObject { || val instanceof Short || val instanceof Byte){ return BigInteger.valueOf(((Number) val).longValue()); } - try { - // the other opt functions handle implicit conversions, i.e. - // jo.put("double",1.1d); - // jo.optInt("double"); -- will return 1, not an error - // this conversion to BigDecimal then to BigInteger is to maintain - // that type cast support that may truncate the decimal. - return new BigDecimal(val.toString()).toBigInteger(); - } catch (Exception e) { - return defaultValue; + if (val instanceof String) { + try { + // the other opt functions handle implicit conversions, i.e. + // jo.put("double",1.1d); + // jo.optInt("double"); -- will return 1, not an error + // this conversion to BigDecimal then to BigInteger is to maintain + // that type cast support that may truncate the decimal. + return new BigDecimal((String) val).toBigInteger(); + } catch (Exception e) { + return defaultValue; + } } + return defaultValue; } /** @@ -1147,7 +1153,7 @@ public class JSONObject { if (val instanceof String) { try { - return new BigDecimal(val.toString()).intValue(); + return new BigDecimal((String) val).intValue(); } catch (Exception e) { return defaultValue; } @@ -1216,7 +1222,7 @@ public class JSONObject { if (val instanceof String) { try { - return new BigDecimal(val.toString()).longValue(); + return new BigDecimal((String) val).longValue(); } catch (Exception e) { return defaultValue; } @@ -1261,7 +1267,7 @@ public class JSONObject { if (val instanceof String) { try { - return new BigDecimal(val.toString()); + return new BigDecimal((String) val); } catch (Exception e) { return defaultValue; } From 0150639119b76c2fc2b44d2be5ffa64976286262 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 11:58:28 -0400 Subject: [PATCH 290/451] update the new coercion test to use actual values and show the parseDouble method is not robust enough for large numbers --- src/test/java/org/json/junit/JSONObjectTest.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 13e4f5f..83e0276 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -2,6 +2,7 @@ package org.json.junit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @@ -2016,13 +2017,14 @@ public class JSONObjectTest { assertTrue("unexpected optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l); // Test type coercion from larger to smaller - final BigDecimal largeValue = new BigDecimal("19007199254740993.35481234487103587486413587843213584"); - assertEquals(largeValue,jo.optBigDecimal("largeNumber", null)); - assertEquals(largeValue.toBigInteger(),jo.optBigInteger("largeNumber", null)); - assertEquals(largeValue.doubleValue(), jo.optDouble("largeNumber"), 0.0d); - assertEquals(largeValue.floatValue(), jo.optFloat("largeNumber"), 0.0f); - assertEquals(largeValue.longValue(), jo.optLong("largeNumber")); - assertEquals(largeValue.intValue(), jo.optInt("largeNumber")); + assertEquals(new BigInteger("19007199254740993"), jo.optBigInteger("largeNumber",null)); + assertEquals(1.9007199254740992E16, jo.optDouble("largeNumber"),0.0); + assertEquals(1.90071995E16f, jo.optFloat("largeNumber"),0.0f); + assertEquals(19007199254740993l, jo.optLong("largeNumber")); + assertEquals(1874919425, jo.optInt("largeNumber")); + + // the integer portion of the actual value is larger than a double can hold. + assertNotEquals((long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optLong("largeNumber")); } /** From 1967bee23690ee48a8b8d2f2dccdff52cb771308 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 12:11:43 -0400 Subject: [PATCH 291/451] expands the coercion tests a little more --- src/test/java/org/json/junit/JSONObjectTest.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 83e0276..1417e6b 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -2025,6 +2025,9 @@ public class JSONObjectTest { // the integer portion of the actual value is larger than a double can hold. assertNotEquals((long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optLong("largeNumber")); + assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumber")); + assertEquals(19007199254740992l, (long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); + assertEquals(2147483647, (int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); } /** From c28a2bdf394a0a950aea82607d539749a9bb9c7e Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 13:07:32 -0400 Subject: [PATCH 292/451] * reverts changes to getDouble and related optDouble and optFloat * Updates optNumber to be smarter about which object it uses to parse strings --- JSONObject.java | 47 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index 9765df4..be547a7 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -581,7 +581,7 @@ public class JSONObject { Object object = this.get(key); try { return object instanceof Number ? ((Number) object).doubleValue() - : new BigDecimal((String) object).doubleValue(); + : Double.parseDouble(object.toString()); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number.", e); @@ -1068,7 +1068,7 @@ public class JSONObject { } if (val instanceof String) { try { - return new BigDecimal((String) val).doubleValue(); + return Double.parseDouble((String) val); } catch (Exception e) { return defaultValue; } @@ -1110,7 +1110,7 @@ public class JSONObject { } if (val instanceof String) { try { - return new BigDecimal((String) val).floatValue(); + return Float.parseFloat((String) val); } catch (Exception e) { return defaultValue; } @@ -1247,7 +1247,7 @@ public class JSONObject { /** * Get an optional {@link Number} value associated with a key, or the default if there * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method + * an attempt will be made to evaluate it as a number. This method * would be used in cases where type coercion of the number value is unwanted. * * @param key @@ -1267,7 +1267,44 @@ public class JSONObject { if (val instanceof String) { try { - return new BigDecimal((String) val); + // decimal representation + if (((String)val).indexOf('.')>=0 || ((String)val).indexOf('e')>=0 || ((String)val).indexOf('E')>=0) { + // quick dirty way to see if we need a BigDecimal instead of a Double + if (((String)val).length()>14) { + return new BigDecimal((String)val); + } + return Double.valueOf((String)val); + } + // integer representation. + // This will narrow any values to the smallest reasonable Object representation + // (Integer, Long, or BigInteger) + // The compare string length method reduces GC, + // but leads to smaller integers being placed in larger wrappers even though not + // needed. i.e. 1,000,000,000 -> Long even though it's an Integer + // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long + + // string version + if(((String)val).length()<=9){ + return Integer.valueOf((String)val); + } + if(((String)val).length()<=18){ + return Long.valueOf((String)val); + } + return new BigInteger((String)val); + + // BigInteger version: We use a similar bitLenth compare as + // BigInteger#intValueExact uses. Increases GC, but objects hold + // only what they need. i.e. Less runtime overhead if the value is + // long lived. Which is the better tradeoff? + + //BigInteger bi = new BigInteger((String)val); + //if(bi.bitLength()<=31){ + // return Integer.valueOf(bi.intValue()); + //} + //if(bi.bitLength()<=63){ + // return Long.valueOf(bi.longValue()); + //} + //return bi; } catch (Exception e) { return defaultValue; } From 1ab5260a7a1041c56f1aafec56768184bcc1dd70 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 14:24:34 -0400 Subject: [PATCH 293/451] * Adds methods getNUmber and getFloat to JSONArray and JSONObject * Extracts the stringToNumber logic that the optNumber method uses to reuse it between classes * Fixes -0 issue with optNumber/getNumber --- JSONArray.java | 50 +++++++++++++++-- JSONObject.java | 144 +++++++++++++++++++++++++++++++++++------------- 2 files changed, 151 insertions(+), 43 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index a692ba4..6f7439a 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -248,6 +248,49 @@ public class JSONArray implements Iterable { } } + /** + * Get the float value associated with a key. + * + * @param index + * The index must be between 0 and length() - 1. + * @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 float getFloat(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number ? ((Number) object).floatValue() + : Float.parseFloat(object.toString()); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + + "] is not a number.", e); + } + } + + /** + * Get the Number value associated with a key. + * + * @param index + * The index must be between 0 and length() - 1. + * @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 Number getNumber(int index) throws JSONException { + Object object = this.get(index); + try { + if (object instanceof Number) { + return (Number)object; + } + return JSONObject.stringToNumber(object.toString()); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + /** * Get the enum value associated with an index. * @@ -266,9 +309,8 @@ public class JSONArray implements Iterable { // JSONException should really take a throwable argument. // If it did, I would re-implement this with the Enum.valueOf // method and place any thrown exception in the JSONException - throw new JSONException("JSONObject[" + JSONObject.quote(Integer.toString(index)) - + "] is not an enum of type " + JSONObject.quote(clazz.getSimpleName()) - + "."); + throw new JSONException("JSONArray[" + index + "] is not an enum of type " + + JSONObject.quote(clazz.getSimpleName()) + "."); } return val; } @@ -845,7 +887,7 @@ public class JSONArray implements Iterable { if (val instanceof String) { try { - return new BigDecimal(val.toString()); + return JSONObject.stringToNumber((String) val); } catch (Exception e) { return defaultValue; } diff --git a/JSONObject.java b/JSONObject.java index be547a7..bba5779 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -588,6 +588,50 @@ public class JSONObject { } } + /** + * Get the float 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 float getFloat(String key) throws JSONException { + Object object = this.get(key); + try { + return object instanceof Number ? ((Number) object).floatValue() + : Float.parseFloat(object.toString()); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + + "] is not a number.", e); + } + } + + /** + * Get the Number 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 Number getNumber(String key) throws JSONException { + Object object = this.get(key); + try { + if (object instanceof Number) { + return (Number)object; + } + return stringToNumber(object.toString()); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + + "] is not a number.", e); + } + } + /** * Get the int value associated with a key. * @@ -1267,51 +1311,14 @@ public class JSONObject { if (val instanceof String) { try { - // decimal representation - if (((String)val).indexOf('.')>=0 || ((String)val).indexOf('e')>=0 || ((String)val).indexOf('E')>=0) { - // quick dirty way to see if we need a BigDecimal instead of a Double - if (((String)val).length()>14) { - return new BigDecimal((String)val); - } - return Double.valueOf((String)val); - } - // integer representation. - // This will narrow any values to the smallest reasonable Object representation - // (Integer, Long, or BigInteger) - // The compare string length method reduces GC, - // but leads to smaller integers being placed in larger wrappers even though not - // needed. i.e. 1,000,000,000 -> Long even though it's an Integer - // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long - - // string version - if(((String)val).length()<=9){ - return Integer.valueOf((String)val); - } - if(((String)val).length()<=18){ - return Long.valueOf((String)val); - } - return new BigInteger((String)val); - - // BigInteger version: We use a similar bitLenth compare as - // BigInteger#intValueExact uses. Increases GC, but objects hold - // only what they need. i.e. Less runtime overhead if the value is - // long lived. Which is the better tradeoff? - - //BigInteger bi = new BigInteger((String)val); - //if(bi.bitLength()<=31){ - // return Integer.valueOf(bi.intValue()); - //} - //if(bi.bitLength()<=63){ - // return Long.valueOf(bi.longValue()); - //} - //return bi; + return stringToNumber((String) val); } catch (Exception e) { return defaultValue; } } return defaultValue; } - + /** * Get an optional string associated with a key. It returns an empty string * if there is no such key. If the value is not a string and is not null, @@ -1757,6 +1764,65 @@ public class JSONObject { } } + /** + * Converts a string to a number using the narrowest possible type. Possible + * returns for this function are BigDecimal, Double, BigInteger, Long, and Integer. + * + * An Exception is thrown if + * + * @param val value to convert + * @return Number representation of the value. + * @throws NumberFormatException thrown if the value is not a valid number. A public + * caller should catch this and wrap it in a {@link JSONException} if applicable. + */ + protected static Number stringToNumber(final String val) throws NumberFormatException { + char initial = val.charAt(0); + if ((initial >= '0' && initial <= '9') || initial == '-') { + // decimal representation + if (val.indexOf('.') > -1 || val.indexOf('e') > -1 + || val.indexOf('E') > -1 + || "-0".equals(val)) { + // quick dirty way to see if we need a BigDecimal instead of a Double + if (val.length()>14) { + return new BigDecimal(val); + } + return Double.valueOf(val); + } + // integer representation. + // This will narrow any values to the smallest reasonable Object representation + // (Integer, Long, or BigInteger) + // The compare string length method reduces GC, + // but leads to smaller integers being placed in larger wrappers even though not + // needed. i.e. 1,000,000,000 -> Long even though it's an Integer + // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long + + // string version + if(val.length()<=9){ + return Integer.valueOf(val); + } + if(val.length()<=18){ + return Long.valueOf(val); + } + return new BigInteger(val); + + // BigInteger version: We use a similar bitLenth compare as + // BigInteger#intValueExact uses. Increases GC, but objects hold + // only what they need. i.e. Less runtime overhead if the value is + // long lived. Which is the better tradeoff? This is closer to what's + // in stringToValue. + + //BigInteger bi = new BigInteger((String)val); + //if(bi.bitLength()<=31){ + // return Integer.valueOf(bi.intValue()); + //} + //if(bi.bitLength()<=63){ + // return Long.valueOf(bi.longValue()); + //} + //return bi; + } + throw new NumberFormatException("val ["+val+"] is not a valid number."); + } + /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. From cfe6851d8c9c1ff70eb7d3c98d5ffe94a40d2a11 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 14:25:42 -0400 Subject: [PATCH 294/451] Adds testing for -0 with optNumber --- .../java/org/json/junit/JSONObjectTest.java | 110 ++++++++++++------ 1 file changed, 74 insertions(+), 36 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 1417e6b..1f7a5c9 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -514,7 +515,7 @@ public class JSONObjectTest { // include an unsupported object for coverage try { jsonObject.accumulate("myArray", Double.NaN); - assertTrue("Expected exception", false); + fail("Expected exception"); } catch (JSONException ignored) {} // validate JSON @@ -545,7 +546,7 @@ public class JSONObjectTest { // include an unsupported object for coverage try { jsonObject.append("myArray", Double.NaN); - assertTrue("Expected exception", false); + fail("Expected exception"); } catch (JSONException ignored) {} // validate JSON @@ -595,6 +596,9 @@ public class JSONObjectTest { "\"longStrKey\":\"987654321098765432\","+ "\"doubleKey\":-23.45e7,"+ "\"doubleStrKey\":\"00001.000\","+ + "\"BigDecimalStrKey\":\"19007199254740993.35481234487103587486413587843213584\","+ + "\"negZeroKey\":-0.0,"+ + "\"negZeroStrKey\":\"-0.0\","+ "\"arrayKey\":[0,1,2],"+ "\"objectKey\":{\"myKey\":\"myVal\"}"+ "}"; @@ -611,10 +615,26 @@ public class JSONObjectTest { jsonObject.getDouble("doubleKey") == -23.45e7); assertTrue("doubleStrKey should be double", jsonObject.getDouble("doubleStrKey") == 1); + assertTrue("doubleKey can be float", + jsonObject.getFloat("doubleKey") == -23.45e7f); + assertTrue("doubleStrKey can be float", + jsonObject.getFloat("doubleStrKey") == 1f); assertTrue("opt doubleKey should be double", jsonObject.optDouble("doubleKey") == -23.45e7); assertTrue("opt doubleKey with Default should be double", jsonObject.optDouble("doubleStrKey", Double.NaN) == 1); + assertTrue("opt negZeroKey should be double", + Double.compare(jsonObject.optDouble("negZeroKey"), -0.0d) == 0); + assertTrue("opt negZeroStrKey with Default should be double", + Double.compare(jsonObject.optDouble("negZeroStrKey"), -0.0d) == 0); + assertTrue("optNumber negZeroKey should return Double", + jsonObject.optNumber("negZeroKey") instanceof Double); + assertTrue("optNumber negZeroStrKey should return Double", + jsonObject.optNumber("negZeroStrKey") instanceof Double); + assertTrue("optNumber negZeroKey should be -0.0", + Double.compare(jsonObject.optNumber("negZeroKey").doubleValue(), -0.0d) == 0); + assertTrue("optNumber negZeroStrKey should be -0.0", + Double.compare(jsonObject.optNumber("negZeroStrKey").doubleValue(), -0.0d) == 0); assertTrue("optFloat doubleKey should be float", jsonObject.optFloat("doubleKey") == -23.45e7f); assertTrue("optFloat doubleKey with Default should be float", @@ -641,12 +661,14 @@ public class JSONObjectTest { jsonObject.optNumber("longKey") instanceof Long); assertTrue("optNumber double should return Double", jsonObject.optNumber("doubleKey") instanceof Double); - assertTrue("optNumber Str int should return BigDecimal", - jsonObject.optNumber("intStrKey") instanceof BigDecimal); - assertTrue("optNumber Str long should return BigDecimal", - jsonObject.optNumber("longStrKey") instanceof BigDecimal); - assertTrue("optNumber Str double should return BigDecimal", - jsonObject.optNumber("doubleStrKey") instanceof BigDecimal); + assertTrue("optNumber Str int should return Integer", + jsonObject.optNumber("intStrKey") instanceof Integer); + assertTrue("optNumber Str long should return Long", + jsonObject.optNumber("longStrKey") instanceof Long); + assertTrue("optNumber Str double should return Double", + jsonObject.optNumber("doubleStrKey") instanceof Double); + assertTrue("optNumber BigDecimalStrKey should return BigDecimal", + jsonObject.optNumber("BigDecimalStrKey") instanceof BigDecimal); assertTrue("xKey should not exist", jsonObject.isNull("xKey")); assertTrue("stringKey should exist", @@ -804,14 +826,14 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(str); try { jsonObject.getBoolean("nonKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("expecting an exception message", "JSONObject[\"nonKey\"] not found.".equals(e.getMessage())); } try { jsonObject.getBoolean("stringKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a Boolean.". @@ -819,7 +841,7 @@ public class JSONObjectTest { } try { jsonObject.getString("nonKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". @@ -827,7 +849,7 @@ public class JSONObjectTest { } try { jsonObject.getString("trueKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"trueKey\"] not a string.". @@ -835,7 +857,7 @@ public class JSONObjectTest { } try { jsonObject.getDouble("nonKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". @@ -843,7 +865,23 @@ public class JSONObjectTest { } try { jsonObject.getDouble("stringKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"stringKey\"] is not a number.". + equals(e.getMessage())); + } + try { + jsonObject.getFloat("nonKey"); + fail("Expected an exception"); + } catch (JSONException e) { + assertTrue("Expecting an exception message", + "JSONObject[\"nonKey\"] not found.". + equals(e.getMessage())); + } + try { + jsonObject.getFloat("stringKey"); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a number.". @@ -851,7 +889,7 @@ public class JSONObjectTest { } try { jsonObject.getInt("nonKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". @@ -859,7 +897,7 @@ public class JSONObjectTest { } try { jsonObject.getInt("stringKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not an int.". @@ -867,7 +905,7 @@ public class JSONObjectTest { } try { jsonObject.getLong("nonKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". @@ -875,7 +913,7 @@ public class JSONObjectTest { } try { jsonObject.getLong("stringKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a long.". @@ -883,7 +921,7 @@ public class JSONObjectTest { } try { jsonObject.getJSONArray("nonKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". @@ -891,7 +929,7 @@ public class JSONObjectTest { } try { jsonObject.getJSONArray("stringKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a JSONArray.". @@ -899,7 +937,7 @@ public class JSONObjectTest { } try { jsonObject.getJSONObject("nonKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"nonKey\"] not found.". @@ -907,7 +945,7 @@ public class JSONObjectTest { } try { jsonObject.getJSONObject("stringKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[\"stringKey\"] is not a JSONObject.". @@ -1004,18 +1042,18 @@ public class JSONObjectTest { */ try { jsonObject.getBigDecimal("bigInt"); - assertTrue("expected an exeption", false); + fail("expected an exeption"); } catch (JSONException ignored) {} obj = jsonObject.optBigDecimal("bigInt", BigDecimal.ONE); assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); try { jsonObject.getBigInteger("bigDec"); - assertTrue("expected an exeption", false); + fail("expected an exeption"); } catch (JSONException ignored) {} jsonObject.put("stringKey", "abc"); try { jsonObject.getBigDecimal("stringKey"); - assertTrue("expected an exeption", false); + fail("expected an exeption"); } catch (JSONException ignored) {} obj = jsonObject.optBigInteger("bigDec", BigInteger.ONE); assertTrue("expected BigInteger", obj instanceof BigInteger); @@ -1092,11 +1130,11 @@ public class JSONObjectTest { jsonArray.put(Boolean.TRUE); try { jsonArray.getBigInteger(2); - assertTrue("should not be able to get big int", false); + fail("should not be able to get big int"); } catch (Exception ignored) {} try { jsonArray.getBigDecimal(2); - assertTrue("should not be able to get big dec", false); + fail("should not be able to get big dec"); } catch (Exception ignored) {} assertTrue("optBigInt is default", jsonArray.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); assertTrue("optBigDec is default", jsonArray.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); @@ -1851,7 +1889,7 @@ public class JSONObjectTest { String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.append("myKey", "hello"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "JSONObject[myKey] is not a JSONArray.". @@ -1862,7 +1900,7 @@ public class JSONObjectTest { String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.increment("myKey"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "Unable to increment [\"myKey\"].". @@ -1873,7 +1911,7 @@ public class JSONObjectTest { String str = "{\"myKey\":true, \"myOtherKey\":false}"; JSONObject jsonObject = new JSONObject(str); jsonObject.get(null); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "Null key.". @@ -1882,7 +1920,7 @@ public class JSONObjectTest { try { // invalid numberToString() JSONObject.numberToString((Number)null); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("Expecting an exception message", "Null pointer". @@ -1892,7 +1930,7 @@ public class JSONObjectTest { // null put key JSONObject jsonObject = new JSONObject("{}"); jsonObject.put(null, 0); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (NullPointerException ignored) { } try { @@ -1900,21 +1938,21 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject("{}"); jsonObject.putOnce("hello", "world"); jsonObject.putOnce("hello", "world!"); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("", true); } try { // test validity of invalid double JSONObject.testValidity(Double.NaN); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("", true); } try { // test validity of invalid float JSONObject.testValidity(Float.NEGATIVE_INFINITY); - assertTrue("Expected an exception", false); + fail("Expected an exception"); } catch (JSONException e) { assertTrue("", true); } @@ -2294,7 +2332,7 @@ public class JSONObjectTest { // assertTrue("should convert null to empty string", "".equals(string)); try { value = jsonObjectNull.get("key"); - assertTrue("get() null should throw exception", false); + fail("get() null should throw exception"); } catch (Exception ignored) {} /** From a7f8ff24df65578ae966d4d12d92218bb3909984 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 14:41:42 -0400 Subject: [PATCH 295/451] correct string check for JSONObject optBigDecimal and optBigInteger --- JSONObject.java | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index bba5779..d835438 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1024,14 +1024,12 @@ public class JSONObject { || val instanceof Short || val instanceof Byte){ return new BigDecimal(((Number) val).longValue()); } - if (val instanceof String) { - try { - return new BigDecimal((String) val); - } catch (Exception e) { - return defaultValue; - } + // don't check if it's a string in case of unchecked Number subclasses + try { + return new BigDecimal(val.toString()); + } catch (Exception e) { + return defaultValue; } - return defaultValue; } /** @@ -1063,19 +1061,17 @@ public class JSONObject { || val instanceof Short || val instanceof Byte){ return BigInteger.valueOf(((Number) val).longValue()); } - if (val instanceof String) { - try { - // the other opt functions handle implicit conversions, i.e. - // jo.put("double",1.1d); - // jo.optInt("double"); -- will return 1, not an error - // this conversion to BigDecimal then to BigInteger is to maintain - // that type cast support that may truncate the decimal. - return new BigDecimal((String) val).toBigInteger(); - } catch (Exception e) { - return defaultValue; - } + // don't check if it's a string in case of unchecked Number subclasses + try { + // the other opt functions handle implicit conversions, i.e. + // jo.put("double",1.1d); + // jo.optInt("double"); -- will return 1, not an error + // this conversion to BigDecimal then to BigInteger is to maintain + // that type cast support that may truncate the decimal. + return new BigDecimal(val.toString()).toBigInteger(); + } catch (Exception e) { + return defaultValue; } - return defaultValue; } /** From 849b392c01f60306d63909e0e5cb9e1ccd0e14af Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 19:49:50 -0400 Subject: [PATCH 296/451] updates the getNumber/optNumber to not return invalid Doubles --- JSONArray.java | 6 +++- JSONObject.java | 78 +++++++++++++++++++++++++++++++------------------ 2 files changed, 54 insertions(+), 30 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 6f7439a..2783bf7 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -738,7 +738,11 @@ public class JSONArray implements Iterable { return BigInteger.valueOf(((Number) val).longValue()); } try { - return new BigDecimal(val.toString()).toBigInteger(); + final String valStr = val.toString(); + if(JSONObject.isDecimalNotation(valStr)) { + return new BigDecimal(valStr).toBigInteger(); + } + return new BigInteger(valStr); } catch (Exception e) { return defaultValue; } diff --git a/JSONObject.java b/JSONObject.java index d835438..05e4f40 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1068,7 +1068,11 @@ public class JSONObject { // jo.optInt("double"); -- will return 1, not an error // this conversion to BigDecimal then to BigInteger is to maintain // that type cast support that may truncate the decimal. - return new BigDecimal(val.toString()).toBigInteger(); + final String valStr = val.toString(); + if(isDecimalNotation(valStr)) { + return new BigDecimal(valStr).toBigInteger(); + } + return new BigInteger(valStr); } catch (Exception e) { return defaultValue; } @@ -1759,12 +1763,22 @@ public class JSONObject { return false; } } - + + /** + * Tests if the value should be tried as a decimal. It makes no test if there are actual digits. + * + * @param val value to test + * @return true if the string is "-0" or if it contains '.', 'e', or 'E', false otherwise. + */ + protected static boolean isDecimalNotation(final String val) { + return val.indexOf('.') > -1 || val.indexOf('e') > -1 + || val.indexOf('E') > -1 || "-0".equals(val); + } + /** * Converts a string to a number using the narrowest possible type. Possible * returns for this function are BigDecimal, Double, BigInteger, Long, and Integer. - * - * An Exception is thrown if + * When a Double is returned, it should always be a valid Double and not NaN or +-infinity. * * @param val value to convert * @return Number representation of the value. @@ -1775,46 +1789,52 @@ public class JSONObject { char initial = val.charAt(0); if ((initial >= '0' && initial <= '9') || initial == '-') { // decimal representation - if (val.indexOf('.') > -1 || val.indexOf('e') > -1 - || val.indexOf('E') > -1 - || "-0".equals(val)) { + if (isDecimalNotation(val)) { // quick dirty way to see if we need a BigDecimal instead of a Double + // this only handles some cases of overflow or underflow if (val.length()>14) { return new BigDecimal(val); } - return Double.valueOf(val); + final Double d = Double.valueOf(val); + if (d.isInfinite() || d.isNaN()) { + // if we can't parse it as a double, go up to BigDecimal + // this is probably due to underflow like 4.32e-678 + // or overflow like 4.65e5324. The size of the string is small + // but can't be held in a Double. + return new BigDecimal(val); + } + return d; } // integer representation. // This will narrow any values to the smallest reasonable Object representation // (Integer, Long, or BigInteger) + + // string version // The compare string length method reduces GC, // but leads to smaller integers being placed in larger wrappers even though not // needed. i.e. 1,000,000,000 -> Long even though it's an Integer // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long - - // string version - if(val.length()<=9){ - return Integer.valueOf(val); - } - if(val.length()<=18){ - return Long.valueOf(val); - } - return new BigInteger(val); + //if(val.length()<=9){ + // return Integer.valueOf(val); + //} + //if(val.length()<=18){ + // return Long.valueOf(val); + //} + //return new BigInteger(val); // BigInteger version: We use a similar bitLenth compare as // BigInteger#intValueExact uses. Increases GC, but objects hold // only what they need. i.e. Less runtime overhead if the value is // long lived. Which is the better tradeoff? This is closer to what's // in stringToValue. - - //BigInteger bi = new BigInteger((String)val); - //if(bi.bitLength()<=31){ - // return Integer.valueOf(bi.intValue()); - //} - //if(bi.bitLength()<=63){ - // return Long.valueOf(bi.longValue()); - //} - //return bi; + BigInteger bi = new BigInteger(val); + if(bi.bitLength()<=31){ + return Integer.valueOf(bi.intValue()); + } + if(bi.bitLength()<=63){ + return Long.valueOf(bi.longValue()); + } + return bi; } throw new NumberFormatException("val ["+val+"] is not a valid number."); } @@ -1849,9 +1869,9 @@ public class JSONObject { char initial = string.charAt(0); if ((initial >= '0' && initial <= '9') || initial == '-') { try { - if (string.indexOf('.') > -1 || string.indexOf('e') > -1 - || string.indexOf('E') > -1 - || "-0".equals(string)) { + // if we want full Big Number support this block can be replaced with: + // return stringToNumber(string); + if (isDecimalNotation(string)) { Double d = Double.valueOf(string); if (!d.isInfinite() && !d.isNaN()) { return d; From 04d6e83fc215001decb989a9223ac7c983383e8f Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 19 May 2017 09:49:22 -0400 Subject: [PATCH 297/451] * Missed JSONArray optFloat and optDouble for the revert * prevents erasure of stack trace for rethrown exceptions --- JSONArray.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 2783bf7..a1147e7 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -244,7 +244,7 @@ public class JSONArray implements Iterable { return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); } catch (Exception e) { - throw new JSONException("JSONArray[" + index + "] is not a number."); + throw new JSONException("JSONArray[" + index + "] is not a number.", e); } } @@ -287,7 +287,7 @@ public class JSONArray implements Iterable { } return JSONObject.stringToNumber(object.toString()); } catch (Exception e) { - throw new JSONException("JSONArray[" + index + "] is not a number."); + throw new JSONException("JSONArray[" + index + "] is not a number.", e); } } @@ -331,7 +331,7 @@ public class JSONArray implements Iterable { return new BigDecimal(object.toString()); } catch (Exception e) { throw new JSONException("JSONArray[" + index + - "] could not convert to BigDecimal."); + "] could not convert to BigDecimal.", e); } } @@ -351,7 +351,7 @@ public class JSONArray implements Iterable { return new BigInteger(object.toString()); } catch (Exception e) { throw new JSONException("JSONArray[" + index + - "] could not convert to BigInteger."); + "] could not convert to BigInteger.", e); } } @@ -370,7 +370,7 @@ public class JSONArray implements Iterable { return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); } catch (Exception e) { - throw new JSONException("JSONArray[" + index + "] is not a number."); + throw new JSONException("JSONArray[" + index + "] is not a number.", e); } } @@ -426,7 +426,7 @@ public class JSONArray implements Iterable { return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); } catch (Exception e) { - throw new JSONException("JSONArray[" + index + "] is not a number."); + throw new JSONException("JSONArray[" + index + "] is not a number.", e); } } @@ -569,7 +569,7 @@ public class JSONArray implements Iterable { } if (val instanceof String) { try { - return new BigDecimal((String) val).doubleValue(); + return Double.parseDouble((String) val); } catch (Exception e) { return defaultValue; } @@ -611,7 +611,7 @@ public class JSONArray implements Iterable { } if (val instanceof String) { try { - return new BigDecimal((String) val).floatValue(); + return Float.parseFloat((String) val); } catch (Exception e) { return defaultValue; } From 04d76b638beada214229666d10ee24ecd3670268 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 19 May 2017 15:01:37 -0400 Subject: [PATCH 298/451] split out tests for better readability --- .../java/org/json/junit/JSONObjectTest.java | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 1f7a5c9..c1ea5a1 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -708,7 +708,7 @@ public class JSONObjectTest { * This test documents a need for BigDecimal conversion. */ Object obj = JSONObject.stringToValue( "299792.457999999984" ); - assertTrue( "evaluates to 299792.458 doubld instead of 299792.457999999984 BigDecimal!", + assertTrue( "evaluates to 299792.458 double instead of 299792.457999999984 BigDecimal!", obj.equals(new Double(299792.458)) ); assertTrue( "1 should be an Integer!", JSONObject.stringToValue( "1" ) instanceof Integer ); @@ -2042,7 +2042,7 @@ public class JSONObjectTest { */ @Test public void jsonObjectOptStringConversion() { - JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\",\"largeNumber\":\"19007199254740993.35481234487103587486413587843213584\"}"); + JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\"}"); assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true); assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false); assertTrue("unexpected optInt value",jo.optInt("int",0)==123); @@ -2053,17 +2053,38 @@ public class JSONObjectTest { assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); assertTrue("unexpected optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l); + } + + /** + * Verifies that the opt methods properly convert string values to numbers and coerce them consistently. + */ + @Test + public void jsonObjectOptCoercion() { + JSONObject jo = new JSONObject("{\"largeNumberStr\":\"19007199254740993.35481234487103587486413587843213584\"}"); + // currently the parser doesn't recognize BigDecimal, to we have to put it manually + jo.put("largeNumber", new BigDecimal("19007199254740993.35481234487103587486413587843213584")); // Test type coercion from larger to smaller + assertEquals(new BigDecimal("19007199254740993.35481234487103587486413587843213584"), jo.optBigDecimal("largeNumber",null)); assertEquals(new BigInteger("19007199254740993"), jo.optBigInteger("largeNumber",null)); assertEquals(1.9007199254740992E16, jo.optDouble("largeNumber"),0.0); assertEquals(1.90071995E16f, jo.optFloat("largeNumber"),0.0f); assertEquals(19007199254740993l, jo.optLong("largeNumber")); assertEquals(1874919425, jo.optInt("largeNumber")); - + + // conversion from a string + assertEquals(new BigDecimal("19007199254740993.35481234487103587486413587843213584"), jo.optBigDecimal("largeNumberStr",null)); + assertEquals(new BigInteger("19007199254740993"), jo.optBigInteger("largeNumberStr",null)); + assertEquals(1.9007199254740992E16, jo.optDouble("largeNumberStr"),0.0); + assertEquals(1.90071995E16f, jo.optFloat("largeNumberStr"),0.0f); + assertEquals(19007199254740993l, jo.optLong("largeNumberStr")); + assertEquals(1874919425, jo.optInt("largeNumberStr")); + // the integer portion of the actual value is larger than a double can hold. assertNotEquals((long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optLong("largeNumber")); assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumber")); + assertNotEquals((long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optLong("largeNumberStr")); + assertNotEquals((int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584"), jo.optInt("largeNumberStr")); assertEquals(19007199254740992l, (long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); assertEquals(2147483647, (int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); } From 4f5bf16676ef3ca113b8145790fd486446756764 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 22 May 2017 00:50:39 -0400 Subject: [PATCH 299/451] * Adds protected entrySet accessor to JSONObject * Updates loops that request key/value pairs to use the new entrySet accessor --- CookieList.java | 17 +++++----- HTTP.java | 18 +++++------ JSONArray.java | 10 ++++-- JSONML.java | 30 +++++++---------- JSONObject.java | 85 +++++++++++++++++++++++++++++-------------------- Property.java | 11 ++++--- XML.java | 12 +++---- 7 files changed, 95 insertions(+), 88 deletions(-) diff --git a/CookieList.java b/CookieList.java index d69e457..8cb4e5e 100644 --- a/CookieList.java +++ b/CookieList.java @@ -1,5 +1,7 @@ package org.json; +import java.util.Map.Entry; + /* Copyright (c) 2002 JSON.org @@ -24,8 +26,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import java.util.Iterator; - /** * Convert a web browser cookie list string to a JSONObject and back. * @author JSON.org @@ -69,18 +69,17 @@ public class CookieList { */ public static String toString(JSONObject jo) throws JSONException { boolean b = false; - Iterator keys = jo.keys(); - String string; StringBuilder sb = new StringBuilder(); - while (keys.hasNext()) { - string = keys.next(); - if (!jo.isNull(string)) { + for (final Entry entry : jo.entrySet()) { + final String key = entry.getKey(); + final Object value = entry.getValue(); + if (!JSONObject.NULL.equals(value)) { if (b) { sb.append(';'); } - sb.append(Cookie.escape(string)); + sb.append(Cookie.escape(key)); sb.append("="); - sb.append(Cookie.escape(jo.getString(string))); + sb.append(Cookie.escape(value.toString())); b = true; } } diff --git a/HTTP.java b/HTTP.java index 9b444ce..22635ff 100644 --- a/HTTP.java +++ b/HTTP.java @@ -24,8 +24,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import java.util.Iterator; import java.util.Locale; +import java.util.Map.Entry; /** * Convert an HTTP header to a JSONObject and back. @@ -126,8 +126,6 @@ public class HTTP { * information. */ public static String toString(JSONObject jo) throws JSONException { - Iterator keys = jo.keys(); - String string; StringBuilder sb = new StringBuilder(); if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { sb.append(jo.getString("HTTP-Version")); @@ -147,14 +145,14 @@ public class HTTP { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); - while (keys.hasNext()) { - string = keys.next(); - if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && - !"Reason-Phrase".equals(string) && !"Method".equals(string) && - !"Request-URI".equals(string) && !jo.isNull(string)) { - sb.append(string); + for (final Entry entry : jo.entrySet()) { + final String key = entry.getKey(); + if (!"HTTP-Version".equals(key) && !"Status-Code".equals(key) && + !"Reason-Phrase".equals(key) && !"Method".equals(key) && + !"Request-URI".equals(key) && !JSONObject.NULL.equals(entry.getValue())) { + sb.append(key); sb.append(": "); - sb.append(jo.getString(string)); + sb.append(jo.optString(key)); sb.append(CRLF); } } diff --git a/JSONArray.java b/JSONArray.java index 7965f3c..d08586d 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1263,8 +1263,14 @@ public class JSONArray implements Iterable { return false; } for (int i = 0; i < len; i += 1) { - Object valueThis = this.get(i); - Object valueOther = ((JSONArray)other).get(i); + Object valueThis = this.myArrayList.get(i); + Object valueOther = ((JSONArray)other).myArrayList.get(i); + if(valueThis == valueOther) { + return true; + } + if(valueThis == null) { + return false; + } if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; diff --git a/JSONML.java b/JSONML.java index 9cb767f..c1d50b3 100644 --- a/JSONML.java +++ b/JSONML.java @@ -1,5 +1,7 @@ package org.json; +import java.util.Map.Entry; + /* Copyright (c) 2008 JSON.org @@ -24,9 +26,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import java.util.Iterator; - - /** * This provides static methods to convert an XML text into a JSONArray or * JSONObject, and to covert a JSONArray or JSONObject into an XML text using @@ -397,13 +396,10 @@ public class JSONML { public static String toString(JSONArray ja) throws JSONException { int i; JSONObject jo; - String key; - Iterator keys; int length; Object object; StringBuilder sb = new StringBuilder(); String tagName; - String value; // Emit entry : jo.entrySet()) { + final String key = entry.getKey(); XML.noSpace(key); - value = jo.optString(key); + final Object value = entry.getValue(); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); sb.append('='); sb.append('"'); - sb.append(XML.escape(value)); + sb.append(XML.escape(value.toString())); sb.append('"'); } } @@ -482,12 +477,10 @@ public class JSONML { StringBuilder sb = new StringBuilder(); int i; JSONArray ja; - String key; - Iterator keys; int length; Object object; String tagName; - String value; + Object value; //Emit entry : jo.entrySet()) { + final String key = entry.getKey(); if (!"tagName".equals(key) && !"childNodes".equals(key)) { XML.noSpace(key); - value = jo.optString(key); + value = entry.getValue(); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); sb.append('='); sb.append('"'); - sb.append(XML.escape(value)); + sb.append(XML.escape(value.toString())); sb.append('"'); } } diff --git a/JSONObject.java b/JSONObject.java index e7db5d1..0216567 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -245,14 +245,14 @@ public class JSONObject { /** * Construct a JSONObject from a Map. * - * @param map + * @param m * A map object that can be used to initialize the contents of * the JSONObject. */ - public JSONObject(Map map) { + public JSONObject(Map m) { this.map = new HashMap(); - if (map != null) { - for (final Entry e : map.entrySet()) { + if (m != null) { + for (final Entry e : m.entrySet()) { final Object value = e.getValue(); if (value != null) { this.map.put(String.valueOf(e.getKey()), wrap(value)); @@ -729,14 +729,7 @@ public class JSONObject { if (length == 0) { return null; } - Iterator iterator = jo.keys(); - String[] names = new String[length]; - int i = 0; - while (iterator.hasNext()) { - names[i] = iterator.next(); - i++; - } - return names; + return jo.keySet().toArray(new String[length]); } /** @@ -837,8 +830,11 @@ public class JSONObject { } /** - * Get an enumeration of the keys of the JSONObject. + * Get an enumeration of the keys of the JSONObject. Modifying this key Set will also + * modify the JSONObject. Use with caution. * + * @see Set#iterator() + * * @return An iterator of the keys. */ public Iterator keys() { @@ -846,7 +842,10 @@ public class JSONObject { } /** - * Get a set of keys of the JSONObject. + * Get a set of keys of the JSONObject. Modifying this key Set will also modify the + * JSONObject. Use with caution. + * + * @see Map#keySet() * * @return A keySet. */ @@ -854,6 +853,22 @@ public class JSONObject { return this.map.keySet(); } + /** + * Get a set of entries of the JSONObject. These are raw values and may not + * match what is returned by the JSONObject get* and opt* functions. Modifying + * the returned EntrySet or the Entry objects contained therein will modify the + * backing JSONObject. This does not return a clone or a read-only view. + * + * Use with caution. + * + * @see Map#entrySet() + * + * @return A keySet. + */ + protected Set> entrySet() { + return this.map.entrySet(); + } + /** * Get the number of keys stored in the JSONObject. * @@ -871,12 +886,10 @@ public class JSONObject { * is empty. */ public JSONArray names() { - JSONArray ja = new JSONArray(); - Iterator keys = this.keys(); - while (keys.hasNext()) { - ja.put(keys.next()); - } - return ja.length() == 0 ? null : ja; + if(this.map.isEmpty()) { + return null; + } + return new JSONArray(this.map.keySet()); } /** @@ -1762,15 +1775,19 @@ public class JSONObject { if (!(other instanceof JSONObject)) { return false; } - Set set = this.keySet(); - if (!set.equals(((JSONObject)other).keySet())) { + if (!this.keySet().equals(((JSONObject)other).keySet())) { return false; } - Iterator iterator = set.iterator(); - while (iterator.hasNext()) { - String name = iterator.next(); - Object valueThis = this.get(name); + for (final Entry entry : this.entrySet()) { + String name = entry.getKey(); + Object valueThis = entry.getValue(); Object valueOther = ((JSONObject)other).get(name); + if(valueThis == valueOther) { + return true; + } + if(valueThis == null) { + return false; + } if (valueThis instanceof JSONObject) { if (!((JSONObject)valueThis).similar(valueOther)) { return false; @@ -2220,21 +2237,19 @@ public class JSONObject { try { boolean commanate = false; final int length = this.length(); - Iterator keys = this.keys(); writer.write('{'); if (length == 1) { - Object key = keys.next(); - writer.write(quote(key.toString())); + final Entry entry = this.entrySet().iterator().next(); + writer.write(quote(entry.getKey())); writer.write(':'); if (indentFactor > 0) { writer.write(' '); } - writeValue(writer, this.map.get(key), indentFactor, indent); + writeValue(writer, entry.getValue(), indentFactor, indent); } else if (length != 0) { final int newindent = indent + indentFactor; - while (keys.hasNext()) { - Object key = keys.next(); + for (final Entry entry : this.entrySet()) { if (commanate) { writer.write(','); } @@ -2242,12 +2257,12 @@ public class JSONObject { writer.write('\n'); } indent(writer, newindent); - writer.write(quote(key.toString())); + writer.write(quote(entry.getKey())); writer.write(':'); if (indentFactor > 0) { writer.write(' '); } - writeValue(writer, this.map.get(key), indentFactor, newindent); + writeValue(writer, entry.getValue(), indentFactor, newindent); commanate = true; } if (indentFactor > 0) { @@ -2273,7 +2288,7 @@ public class JSONObject { */ public Map toMap() { Map results = new HashMap(); - for (Entry entry : this.map.entrySet()) { + for (Entry entry : this.entrySet()) { Object value; if (entry.getValue() == null || NULL.equals(entry.getValue())) { value = null; diff --git a/Property.java b/Property.java index 73ddb12..4f1d7c4 100644 --- a/Property.java +++ b/Property.java @@ -25,7 +25,7 @@ SOFTWARE. */ import java.util.Enumeration; -import java.util.Iterator; +import java.util.Map.Entry; import java.util.Properties; /** @@ -61,10 +61,11 @@ public class Property { public static Properties toProperties(JSONObject jo) throws JSONException { Properties properties = new Properties(); if (jo != null) { - Iterator keys = jo.keys(); - while (keys.hasNext()) { - String name = keys.next(); - properties.put(name, jo.getString(name)); + for (final Entry entry : jo.entrySet()) { + Object value = entry.getValue(); + if (!JSONObject.NULL.equals(value)) { + properties.put(entry.getKey(), value.toString()); + } } } return properties; diff --git a/XML.java b/XML.java index a438078..4dd9a2c 100644 --- a/XML.java +++ b/XML.java @@ -25,6 +25,7 @@ SOFTWARE. */ import java.util.Iterator; +import java.util.Map.Entry; /** * This provides static methods to convert an XML text into a JSONObject, and to @@ -513,10 +514,7 @@ public class XML { StringBuilder sb = new StringBuilder(); JSONArray ja; JSONObject jo; - String key; - Iterator keys; String string; - Object value; if (object instanceof JSONObject) { @@ -529,16 +527,14 @@ public class XML { // Loop thru the keys. jo = (JSONObject) object; - keys = jo.keys(); - while (keys.hasNext()) { - key = keys.next(); - value = jo.opt(key); + for (final Entry entry : jo.entrySet()) { + final String key = entry.getKey(); + Object value = entry.getValue(); if (value == null) { value = ""; } else if (value.getClass().isArray()) { value = new JSONArray(value); } - string = value instanceof String ? (String) value : null; // Emit content in body if ("content".equals(key)) { From f76fbe700593e9be38d3a3d03cf93d11b90b8c7f Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 31 May 2017 18:13:40 -0400 Subject: [PATCH 300/451] fixes comments --- JSONObject.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index 0216567..ff4acfa 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -863,7 +863,7 @@ public class JSONObject { * * @see Map#entrySet() * - * @return A keySet. + * @return An Entry Set */ protected Set> entrySet() { return this.map.entrySet(); @@ -2218,8 +2218,7 @@ public class JSONObject { } /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. + * Write the contents of the JSONObject as JSON text to a writer. *

* Warning: This method assumes that the data structure is acyclical. * From 237bf0adb6c065850d0a474e7c07357cde0fe301 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 31 May 2017 18:31:02 -0400 Subject: [PATCH 301/451] more comments --- JSONTokener.java | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/JSONTokener.java b/JSONTokener.java index d0b197d..b244d13 100644 --- a/JSONTokener.java +++ b/JSONTokener.java @@ -39,13 +39,19 @@ SOFTWARE. * @version 2014-05-03 */ public class JSONTokener { - - private long character; + /** current read character. */ + private long character; + /** flag to indicate if the end of the input has been found. */ private boolean eof; - private long index; - private long line; - private char previous; - private Reader reader; + /** current read index of the input. */ + private long index; + /** current line of the input. */ + private long line; + /** previous index of the input. */ + private char previous; + /** Reader for the input. */ + private final Reader reader; + /** flag to indicate that a previous character was requested. */ private boolean usePrevious; From ad6bdd715de0ee3c007257a6709b3b14e193ce3f Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 5 Jun 2017 20:51:57 -0400 Subject: [PATCH 302/451] Adds JSONException for write value errors so serialization errors can be tracked easier --- JSONArray.java | 16 ++++++++++++---- JSONObject.java | 18 ++++++++++++++---- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index d08586d..54d5183 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1384,8 +1384,12 @@ public class JSONArray implements Iterable { writer.write('['); if (length == 1) { - JSONObject.writeValue(writer, this.myArrayList.get(0), - indentFactor, indent); + try { + JSONObject.writeValue(writer, this.myArrayList.get(0), + indentFactor, indent); + } catch (Exception e) { + throw new JSONException("Unable to write JSONArray value at index: 0", e); + } } else if (length != 0) { final int newindent = indent + indentFactor; @@ -1397,8 +1401,12 @@ public class JSONArray implements Iterable { writer.write('\n'); } JSONObject.indent(writer, newindent); - JSONObject.writeValue(writer, this.myArrayList.get(i), - indentFactor, newindent); + try { + JSONObject.writeValue(writer, this.myArrayList.get(i), + indentFactor, newindent); + } catch (Exception e) { + throw new JSONException("Unable to write JSONArray value at index: " + i, e); + } commanate = true; } if (indentFactor > 0) { diff --git a/JSONObject.java b/JSONObject.java index ff4acfa..f3e34db 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -2240,12 +2240,17 @@ public class JSONObject { if (length == 1) { final Entry entry = this.entrySet().iterator().next(); - writer.write(quote(entry.getKey())); + final String key = entry.getKey(); + writer.write(quote(key)); writer.write(':'); if (indentFactor > 0) { writer.write(' '); } - writeValue(writer, entry.getValue(), indentFactor, indent); + try{ + writeValue(writer, entry.getValue(), indentFactor, indent); + } catch (Exception e) { + throw new JSONException("Unable to write JSONObject value for key: " + key, e); + } } else if (length != 0) { final int newindent = indent + indentFactor; for (final Entry entry : this.entrySet()) { @@ -2256,12 +2261,17 @@ public class JSONObject { writer.write('\n'); } indent(writer, newindent); - writer.write(quote(entry.getKey())); + final String key = entry.getKey(); + writer.write(quote(key)); writer.write(':'); if (indentFactor > 0) { writer.write(' '); } - writeValue(writer, entry.getValue(), indentFactor, newindent); + try { + writeValue(writer, entry.getValue(), indentFactor, newindent); + } catch (Exception e) { + throw new JSONException("Unable to write JSONObject value for key: " + key, e); + } commanate = true; } if (indentFactor > 0) { From d0f560799820df4237c33417ce7765eafc9556d4 Mon Sep 17 00:00:00 2001 From: Tomas Tulka Date: Thu, 8 Jun 2017 08:03:14 +0200 Subject: [PATCH 303/451] a comment added to explain the use of HashMap to avoid misconception of contributors about using HashMap to implement a JSON object as a unordered collection by the definition --- JSONObject.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index ff4acfa..f974430 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -164,6 +164,7 @@ public class JSONObject { * Construct an empty JSONObject. */ public JSONObject() { + // HashMap is used on purpose to ensure that elements are unordered this.map = new HashMap(); } @@ -216,7 +217,7 @@ public class JSONObject { key = x.nextValue().toString(); } -// The key is followed by ':'. + // The key is followed by ':'. c = x.nextClean(); if (c != ':') { @@ -224,7 +225,7 @@ public class JSONObject { } this.putOnce(key, x.nextValue()); -// Pairs are separated by ','. + // Pairs are separated by ','. switch (x.nextClean()) { case ';': From c5e4b91fa410687205205032a9b903824790f733 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 8 Jun 2017 02:25:59 -0400 Subject: [PATCH 304/451] Updates tests for better error handling changes --- src/test/java/org/json/junit/EnumTest.java | 14 +- .../java/org/json/junit/JSONObjectTest.java | 124 +++++++++++++++++- .../java/org/json/junit/JSONStringTest.java | 2 +- 3 files changed, 134 insertions(+), 6 deletions(-) diff --git a/src/test/java/org/json/junit/EnumTest.java b/src/test/java/org/json/junit/EnumTest.java index 6b97107..53ac303 100644 --- a/src/test/java/org/json/junit/EnumTest.java +++ b/src/test/java/org/json/junit/EnumTest.java @@ -1,5 +1,7 @@ package org.json.junit; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.EnumSet; @@ -325,6 +327,7 @@ public class EnumTest { JSONObject jsonObject = new JSONObject(); jsonObject.put("strKey", "value"); + jsonObject.put("strKey2", "VAL1"); jsonObject.put("enumKey", myEnumField); jsonObject.put("enumClassKey", myEnumClass); @@ -360,11 +363,18 @@ public class EnumTest { // opt with default the wrong value actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey", null); - assertTrue("opt null", actualEnum == null); + assertNull("opt null", actualEnum); + + // opt with default the string value + actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey2", null); + assertEquals(MyEnumField.VAL1, actualEnum); // opt with default an index that does not exist actualEnum = jsonObject.optEnum(MyEnumField.class, "noKey", null); - assertTrue("opt null", actualEnum == null); + assertNull("opt null", actualEnum); + + assertNull("Expected Null when the enum class is null", + jsonObject.optEnum(null, "enumKey")); /** * Exercise the proposed enum API methods on JSONArray diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index b2d1362..ebd1cd1 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -2010,6 +2010,8 @@ public class JSONObjectTest { public void jsonObjectOptNoKey() { JSONObject jsonObject = new JSONObject(); + + assertNull(jsonObject.opt(null)); assertTrue("optBigDecimal() should return default BigDecimal", BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); @@ -2088,6 +2090,46 @@ public class JSONObjectTest { assertEquals(19007199254740992l, (long)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); assertEquals(2147483647, (int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); } + + /** + * Verifies that the optBigDecimal method properly converts values to BigDecimal and coerce them consistently. + */ + @Test + public void jsonObjectOptBigDecimal() { + JSONObject jo = new JSONObject().put("int", 123).put("long", 654L) + .put("float", 1.234f).put("double", 2.345d) + .put("bigInteger", new BigInteger("1234")) + .put("bigDecimal", new BigDecimal("1234.56789")) + .put("nullVal", JSONObject.NULL); + + assertEquals(new BigDecimal("123"),jo.optBigDecimal("int", null)); + assertEquals(new BigDecimal("654"),jo.optBigDecimal("long", null)); + assertEquals(new BigDecimal(1.234f),jo.optBigDecimal("float", null)); + assertEquals(new BigDecimal(2.345d),jo.optBigDecimal("double", null)); + assertEquals(new BigDecimal("1234"),jo.optBigDecimal("bigInteger", null)); + assertEquals(new BigDecimal("1234.56789"),jo.optBigDecimal("bigDecimal", null)); + assertNull(jo.optBigDecimal("nullVal", null)); + } + + /** + * Verifies that the optBigDecimal method properly converts values to BigDecimal and coerce them consistently. + */ + @Test + public void jsonObjectOptBigInteger() { + JSONObject jo = new JSONObject().put("int", 123).put("long", 654L) + .put("float", 1.234f).put("double", 2.345d) + .put("bigInteger", new BigInteger("1234")) + .put("bigDecimal", new BigDecimal("1234.56789")) + .put("nullVal", JSONObject.NULL); + + assertEquals(new BigInteger("123"),jo.optBigInteger("int", null)); + assertEquals(new BigInteger("654"),jo.optBigInteger("long", null)); + assertEquals(new BigInteger("1"),jo.optBigInteger("float", null)); + assertEquals(new BigInteger("2"),jo.optBigInteger("double", null)); + assertEquals(new BigInteger("1234"),jo.optBigInteger("bigInteger", null)); + assertEquals(new BigInteger("1234"),jo.optBigInteger("bigDecimal", null)); + assertNull(jo.optBigDecimal("nullVal", null)); + } /** * Confirm behavior when JSONObject put(key, null object) is called @@ -2099,13 +2141,13 @@ public class JSONObjectTest { String str = "{\"myKey\": \"myval\"}"; JSONObject jsonObjectRemove = new JSONObject(str); jsonObjectRemove.remove("myKey"); + assertEquals("jsonObject should be empty",0 ,jsonObjectRemove.length()); JSONObject jsonObjectPutNull = new JSONObject(str); jsonObjectPutNull.put("myKey", (Object) null); + assertEquals("jsonObject should be empty",0 ,jsonObjectPutNull.length()); + - // validate JSON - assertTrue("jsonObject should be empty", jsonObjectRemove.length() == 0 - && jsonObjectPutNull.length() == 0); } /** @@ -2190,6 +2232,70 @@ public class JSONObjectTest { stringWriter.close(); } } + + /** + * Confirms that exceptions thrown when writing values are wrapped properly. + */ + @Test + public void testJSONWriterException() throws IOException { + final JSONObject jsonObject = new JSONObject(); + + jsonObject.put("someKey",new BrokenToString()); + + // test single element JSONObject + try(StringWriter writer = new StringWriter();) { + jsonObject.write(writer).toString(); + fail("Expected an exception, got a String value"); + } catch (JSONException e) { + assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage()); + } catch(Exception e) { + fail("Expected JSONException"); + } + + //test multiElement + jsonObject.put("somethingElse", "a value"); + + try (StringWriter writer = new StringWriter()) { + jsonObject.write(writer).toString(); + fail("Expected an exception, got a String value"); + } catch (JSONException e) { + assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage()); + } catch(Exception e) { + fail("Expected JSONException"); + } + + // test a more complex object + try (StringWriter writer = new StringWriter()) { + new JSONObject() + .put("somethingElse", "a value") + .put("someKey", new JSONArray() + .put(new JSONObject().put("key1", new BrokenToString()))) + .write(writer).toString(); + fail("Expected an exception, got a String value"); + } catch (JSONException e) { + assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage()); + } catch(Exception e) { + fail("Expected JSONException"); + } + + // test a more slightly complex object + try (StringWriter writer = new StringWriter()) { + new JSONObject() + .put("somethingElse", "a value") + .put("someKey", new JSONArray() + .put(new JSONObject().put("key1", new BrokenToString())) + .put(12345) + ) + .write(writer).toString(); + fail("Expected an exception, got a String value"); + } catch (JSONException e) { + assertEquals("Unable to write JSONObject value for key: someKey", e.getMessage()); + } catch(Exception e) { + fail("Expected JSONException"); + } + + } + /** * Exercise the JSONObject write() method @@ -2468,4 +2574,16 @@ public class JSONObjectTest { assertTrue("Map should have 2 elements", map.size() == 2); } + + /** + * test class for verifying write errors. + * @author John Aylward + * + */ + private static class BrokenToString { + @Override + public String toString() { + throw new IllegalStateException("Something went horribly wrong!"); + } + } } diff --git a/src/test/java/org/json/junit/JSONStringTest.java b/src/test/java/org/json/junit/JSONStringTest.java index 617b9e3..ec40dbb 100644 --- a/src/test/java/org/json/junit/JSONStringTest.java +++ b/src/test/java/org/json/junit/JSONStringTest.java @@ -242,7 +242,7 @@ public class JSONStringTest { jsonArray.write(writer).toString(); fail("Expected an exception, got a String value"); } catch (JSONException e) { - assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); + assertEquals("Unable to write JSONArray value at index: 0", e.getMessage()); } catch(Exception e) { fail("Expected JSONException"); } finally { From 9c092753b0dce6ee96a9bd21060c3544d42191e4 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 8 Jun 2017 11:22:23 -0400 Subject: [PATCH 305/451] * Updates array constructor and bulk operations to best guess capacity information * Update JSONObject to allow best guess for initial capacity. --- JSONArray.java | 13 ++++++++++--- JSONObject.java | 17 ++++++++++++++--- Property.java | 2 +- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index d08586d..0853d00 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -154,7 +154,7 @@ public class JSONArray implements Iterable { * A Collection. */ public JSONArray(Collection collection) { - this.myArrayList = new ArrayList(); + this.myArrayList = new ArrayList(collection == null ? 0 : collection.size()); if (collection != null) { for (Object o: collection){ this.myArrayList.add(JSONObject.wrap(o)); @@ -172,6 +172,7 @@ public class JSONArray implements Iterable { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); + this.myArrayList.ensureCapacity(length); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } @@ -495,7 +496,7 @@ public class JSONArray implements Iterable { * Get the optional object value associated with an index. * * @param index - * The index must be between 0 and length() - 1. + * The index must be between 0 and length() - 1. If not, null is returned. * @return An object value, or null if there is no object at that index. */ public Object opt(int index) { @@ -1150,7 +1151,13 @@ public class JSONArray implements Iterable { } if (index < this.length()) { this.myArrayList.set(index, value); + } else if(index == this.length()){ + // simple append + this.put(value); } else { + // if we are inserting past the length, we want to grow the array all at once + // instead of incrementally. + this.myArrayList.ensureCapacity(index + 1); while (index != this.length()) { this.put(JSONObject.NULL); } @@ -1302,7 +1309,7 @@ public class JSONArray implements Iterable { if (names == null || names.length() == 0 || this.length() == 0) { return null; } - JSONObject jo = new JSONObject(); + JSONObject jo = new JSONObject(names.length()); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } diff --git a/JSONObject.java b/JSONObject.java index ff4acfa..7795fbe 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -178,7 +178,7 @@ public class JSONObject { * An array of strings. */ public JSONObject(JSONObject jo, String[] names) { - this(); + this(names.length); for (int i = 0; i < names.length; i += 1) { try { this.putOnce(names[i], jo.opt(names[i])); @@ -250,7 +250,7 @@ public class JSONObject { * the JSONObject. */ public JSONObject(Map m) { - this.map = new HashMap(); + this.map = new HashMap(m == null ? 0 : m.size()); if (m != null) { for (final Entry e : m.entrySet()) { final Object value = e.getValue(); @@ -302,7 +302,7 @@ public class JSONObject { * from the object. */ public JSONObject(Object object, String names[]) { - this(); + this(names.length); Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { String name = names[i]; @@ -371,6 +371,17 @@ public class JSONObject { } } } + + /** + * Constructor to specify an initial capacity of the internal map. Useful for library + * internal calls where we know, or at least can best guess, how big this JSONObject + * will be. + * + * @param initialCapacity initial capacity of the internal map. + */ + protected JSONObject(int initialCapacity){ + this.map = new HashMap(initialCapacity); + } /** * Accumulate values under a key. It is similar to the put method except diff --git a/Property.java b/Property.java index 4f1d7c4..51b97ed 100644 --- a/Property.java +++ b/Property.java @@ -41,7 +41,7 @@ public class Property { * @throws JSONException */ public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException { - JSONObject jo = new JSONObject(); + JSONObject jo = new JSONObject(properties == null ? 0 : properties.size()); if (properties != null && !properties.isEmpty()) { Enumeration enumProperties = properties.propertyNames(); while(enumProperties.hasMoreElements()) { From 3645f91b551e2806e007e5f0dbeb0cca8f493e42 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 8 Jun 2017 12:15:03 -0400 Subject: [PATCH 306/451] change JSONArray(Collection) constructor to use the default capacity when a null collection is passed --- JSONArray.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 0853d00..531b89d 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -154,8 +154,10 @@ public class JSONArray implements Iterable { * A Collection. */ public JSONArray(Collection collection) { - this.myArrayList = new ArrayList(collection == null ? 0 : collection.size()); - if (collection != null) { + if (collection == null) { + this.myArrayList = new ArrayList(); + } else { + this.myArrayList = new ArrayList(collection.size()); for (Object o: collection){ this.myArrayList.add(JSONObject.wrap(o)); } From 2fbe4d96cf8baec65da1518331eeee409ad80de9 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 8 Jun 2017 12:18:04 -0400 Subject: [PATCH 307/451] change JSONObject(Map) constructor to use the default capacity when a null map is passed --- JSONObject.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index 7795fbe..6580251 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -250,8 +250,10 @@ public class JSONObject { * the JSONObject. */ public JSONObject(Map m) { - this.map = new HashMap(m == null ? 0 : m.size()); - if (m != null) { + if (m == null) { + this.map = new HashMap(); + } else { + this.map = new HashMap(m.size()); for (final Entry e : m.entrySet()) { final Object value = e.getValue(); if (value != null) { From 246350bbcdf88e6f473bdaaed2f30e50932c931d Mon Sep 17 00:00:00 2001 From: Tomas Tulka Date: Fri, 9 Jun 2017 09:00:17 +0200 Subject: [PATCH 308/451] comment added to explain the reason that JSON object is unordered to avoid implementators' misconceptions and tries to reimplement the JSON object to keep the elements order --- JSONObject.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/JSONObject.java b/JSONObject.java index f974430..e4b0bfa 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -164,7 +164,12 @@ public class JSONObject { * Construct an empty JSONObject. */ public JSONObject() { - // HashMap is used on purpose to ensure that elements are unordered + // HashMap is used on purpose to ensure that elements are unordered by + // the specification. + // JSON tends to be a portable transfer format to allows the container + // implementations to rearrange their items for a faster element + // retrieval based on associative access. + // Therefore, an implementation mustn't rely on the order of the item. this.map = new HashMap(); } From 3081b4bd960886b1d3f81103ddc9d741869df51a Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 21 Jun 2017 14:59:42 -0400 Subject: [PATCH 309/451] Fixes for failing tests due to android integration --- src/test/java/org/json/junit/JSONMLTest.java | 64 ++++++++++---------- src/test/java/org/json/junit/XMLTest.java | 57 ++++++++--------- 2 files changed, 61 insertions(+), 60 deletions(-) diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 8ece8e5..833e934 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -42,11 +42,11 @@ public class JSONMLTest { String xmlStr = ""; try { JSONML.toJSONArray(xmlStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Bad XML at 1 [character 2 line 1]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Bad XML at 0 [character 1 line 1]", + e.getMessage()); } } @@ -95,11 +95,11 @@ public class JSONMLTest { String xmlStr = "{ \"this is\": \"not xml\"}"; try { JSONML.toJSONArray(xmlStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Bad XML at 25 [character 26 line 1]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Bad XML at 23 [character 24 line 1]", + e.getMessage()); } } @@ -198,11 +198,11 @@ public class JSONMLTest { ""; try { JSONML.toJSONArray(xmlStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Misshaped tag at 176 [character 14 line 7]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Misshaped tag at 176 [character 14 line 4]", + e.getMessage()); } } @@ -223,11 +223,11 @@ public class JSONMLTest { ""; try { JSONML.toJSONArray(xmlStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Misshaped meta tag at 216 [character 13 line 11]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Misshaped meta tag at 216 [character 13 line 7]", + e.getMessage()); } } @@ -253,11 +253,11 @@ public class JSONMLTest { ""; try { JSONML.toJSONArray(xmlStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Misshaped meta tag at 215 [character 13 line 11]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Misshaped meta tag at 215 [character 13 line 7]", + e.getMessage()); } } @@ -283,11 +283,11 @@ public class JSONMLTest { ""; try { JSONML.toJSONArray(xmlStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Misplaced '<' at 194 [character 5 line 10]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Misplaced '<' at 194 [character 5 line 6]", + e.getMessage()); } } @@ -343,11 +343,11 @@ public class JSONMLTest { ""; try { JSONML.toJSONArray(xmlStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Misplaced '<' at 206 [character 1 line 12]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Misplaced '<' at 206 [character 1 line 7]", + e.getMessage()); } } @@ -373,11 +373,11 @@ public class JSONMLTest { ""; try { JSONML.toJSONArray(xmlStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Expected 'CDATA[' at 204 [character 11 line 9]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Expected 'CDATA[' at 204 [character 11 line 5]", + e.getMessage()); } } diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index dd827bd..11566c6 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -3,6 +3,7 @@ package org.json.junit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import org.json.JSONArray; import org.json.JSONException; @@ -74,11 +75,11 @@ public class XMLTest { ""; try { XML.toJSONObject(xmlStr); - assertTrue("Expecting a JSONException", false); + fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Misshaped tag at 176 [character 14 line 5]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Misshaped tag at 176 [character 14 line 4]", + e.getMessage()); } } @@ -99,11 +100,11 @@ public class XMLTest { ""; try { XML.toJSONObject(xmlStr); - assertTrue("Expecting a JSONException", false); + fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Misshaped meta tag at 215 [character 13 line 8]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Misshaped meta tag at 215 [character 13 line 7]", + e.getMessage()); } } @@ -124,11 +125,11 @@ public class XMLTest { ""; try { XML.toJSONObject(xmlStr); - assertTrue("Expecting a JSONException", false); + fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Misshaped meta tag at 214 [character 13 line 8]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Misshaped meta tag at 214 [character 13 line 7]", + e.getMessage()); } } @@ -149,11 +150,11 @@ public class XMLTest { ""; try { XML.toJSONObject(xmlStr); - assertTrue("Expecting a JSONException", false); + fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Misplaced '<' at 193 [character 4 line 7]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Misplaced '<' at 193 [character 4 line 6]", + e.getMessage()); } } @@ -174,11 +175,11 @@ public class XMLTest { ""; try { XML.toJSONObject(xmlStr); - assertTrue("Expecting a JSONException", false); + fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Expected 'CDATA[' at 204 [character 11 line 6]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Expected 'CDATA[' at 204 [character 11 line 5]", + e.getMessage()); } } @@ -397,9 +398,9 @@ public class XMLTest { final String expected = ""; String output1 = XML.toString(jo1,"jo"); - assertTrue("Expected an empty root tag", expected.equals(output1)); + assertEquals("Expected an empty root tag", expected, output1); String output2 = XML.toString(jo2,"jo"); - assertTrue("Expected an empty root tag", expected.equals(output2)); + assertEquals("Expected an empty root tag", expected, output2); } /** @@ -414,9 +415,9 @@ public class XMLTest { final String expected = "OneFour"; String output1 = XML.toString(jo1,"jo"); - assertTrue("Expected a matching array", expected.equals(output1)); + assertEquals("Expected a matching array", expected, output1); String output2 = XML.toString(jo2,"jo"); - assertTrue("Expected a matching array", expected.equals(output2)); + assertEquals("Expected a matching array", expected, output2); } /** @@ -431,9 +432,9 @@ public class XMLTest { final String expected = "OneTwoThree"; String output1 = XML.toString(jo1,"jo"); - assertTrue("Expected a non empty root tag", expected.equals(output1)); + assertEquals("Expected a non empty root tag", expected, output1); String output2 = XML.toString(jo2,"jo"); - assertTrue("Expected a non empty root tag", expected.equals(output2)); + assertEquals("Expected a non empty root tag", expected, output2); } /** @@ -448,9 +449,9 @@ public class XMLTest { final String expected = "OneTwoThreeFour"; String output1 = XML.toString(jo1,"jo"); - assertTrue("Expected a matching array", expected.equals(output1)); + assertEquals("Expected a matching array", expected, output1); String output2 = XML.toString(jo2,"jo"); - assertTrue("Expected a matching array", expected.equals(output2)); + assertEquals("Expected a matching array", expected, output2); } /** From 971614ac8b28b40e14ab27615b098ccebcb80eb0 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 21 Jun 2017 18:28:04 -0400 Subject: [PATCH 310/451] fix expected exception message --- src/test/java/org/json/junit/JSONMLTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 833e934..518c949 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -98,7 +98,7 @@ public class JSONMLTest { fail("Expecting an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "Bad XML at 23 [character 24 line 1]", + "Bad XML at 24 [character 25 line 1]", e.getMessage()); } } From 0e612ba8a4767cf9e5b6cae399133c234dd5a9f9 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 21 Jun 2017 19:56:00 -0400 Subject: [PATCH 311/451] More test corrections for correct position reports in error messages --- src/test/java/org/json/junit/CDLTest.java | 73 +++++++++++-------- .../java/org/json/junit/CookieListTest.java | 8 +- src/test/java/org/json/junit/CookieTest.java | 24 +++--- .../java/org/json/junit/JSONArrayTest.java | 6 +- src/test/java/org/json/junit/JSONMLTest.java | 6 +- .../java/org/json/junit/JSONObjectTest.java | 48 ++++++------ src/test/java/org/json/junit/XMLTest.java | 4 +- 7 files changed, 92 insertions(+), 77 deletions(-) diff --git a/src/test/java/org/json/junit/CDLTest.java b/src/test/java/org/json/junit/CDLTest.java index a40b014..b99e17c 100644 --- a/src/test/java/org/json/junit/CDLTest.java +++ b/src/test/java/org/json/junit/CDLTest.java @@ -61,11 +61,11 @@ public class CDLTest { String badLine = "Col1, \"Col2\nVal1, Val2"; try { CDL.toJSONArray(badLine); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Missing close quote '\"'. at 12 [character 0 line 2]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Missing close quote '\"'. at 12 [character 0 line 2]", + e.getMessage()); } } @@ -78,11 +78,11 @@ public class CDLTest { String badLine = "Col1, Col2\n\"Val1, Val2"; try { CDL.toJSONArray(badLine); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Missing close quote '\"'. at 23 [character 12 line 3]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Missing close quote '\"'. at 22 [character 11 line 3]", + e.getMessage()); } } @@ -96,11 +96,11 @@ public class CDLTest { String badLine = "C\0ol1, Col2\nVal1, Val2"; try { CDL.toJSONArray(badLine); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Bad character 'o' (111). at 3 [character 4 line 1]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Bad character 'o' (111). at 2 [character 3 line 1]", + e.getMessage()); } } @@ -114,11 +114,11 @@ public class CDLTest { String badLine = "Col1, Col2\n\"Val1, \"\"Val2\"\""; try { CDL.toJSONArray(badLine); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Missing close quote '\"'. at 27 [character 16 line 3]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Missing close quote '\"'. at 26 [character 15 line 3]", + e.getMessage()); } } @@ -128,7 +128,7 @@ public class CDLTest { */ @Test public void singleEscapedQuote(){ - String singleEscape = "Col1, Col2\nVal1, \"\"\"Val2\""; + String singleEscape = "Col1, Col2\nVal1, \"\"\"Val2\""; JSONArray jsonArray = CDL.toJSONArray(singleEscape); String cdlStr = CDL.toString(jsonArray); @@ -136,7 +136,22 @@ public class CDLTest { assertTrue(cdlStr.contains("Col2")); assertTrue(cdlStr.contains("Val1")); assertTrue(cdlStr.contains("\"Val2")); + } + + /** + * Assert that there is no error for a single escaped quote within a properly + * embedded quote when not the last value. + */ + @Test + public void singleEscapedQuoteMiddleString(){ + String singleEscape = "Col1, Col2\nVal1, \"\"\"Val2\"\nVal 3,Val 4"; + JSONArray jsonArray = CDL.toJSONArray(singleEscape); + String cdlStr = CDL.toString(jsonArray); + assertTrue(cdlStr.contains("Col1")); + assertTrue(cdlStr.contains("Col2")); + assertTrue(cdlStr.contains("Val1")); + assertTrue(cdlStr.contains("\"Val2")); } /** @@ -149,12 +164,12 @@ public class CDLTest { try { CDL.toJSONArray(badLine); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { System.out.println("Message" + e.getMessage()); - assertTrue("Expecting an exception message", - "Bad character 'V' (86). at 20 [character 9 line 3]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Bad character 'V' (86). at 20 [character 9 line 3]", + e.getMessage()); } @@ -186,8 +201,8 @@ public class CDLTest { public void onlyColumnNames() { String columnNameStr = "col1, col2, col3"; JSONArray jsonArray = CDL.toJSONArray(columnNameStr); - assertTrue("CDL should return null when only 1 row is given", - jsonArray == null); + assertNull("CDL should return null when only 1 row is given", + jsonArray); } /** @@ -197,8 +212,8 @@ public class CDLTest { public void emptyLinesToJSONArray() { String str = " , , , \n , , , "; JSONArray jsonArray = CDL.toJSONArray(str); - assertTrue("JSONArray should be null for no content", - jsonArray == null); + assertNull("JSONArray should be null for no content", + jsonArray); } /** @@ -208,8 +223,8 @@ public class CDLTest { public void emptyJSONArrayToString() { JSONArray jsonArray = new JSONArray(); String str = CDL.toString(jsonArray); - assertTrue("CDL should return null for toString(null)", - str == null); + assertNull("CDL should return null for toString(null)", + str); } /** @@ -218,8 +233,8 @@ public class CDLTest { @Test public void nullJSONArraysToString() { String str = CDL.toString(null, null); - assertTrue("CDL should return null for toString(null)", - str == null); + assertNull("CDL should return null for toString(null)", + str); } /** diff --git a/src/test/java/org/json/junit/CookieListTest.java b/src/test/java/org/json/junit/CookieListTest.java index 7a710db..80cbaa8 100644 --- a/src/test/java/org/json/junit/CookieListTest.java +++ b/src/test/java/org/json/junit/CookieListTest.java @@ -47,14 +47,14 @@ public class CookieListTest { String cookieStr = "thisCookieHasNoEqualsChar"; try { CookieList.toJSONObject(cookieStr); - assertTrue("should throw an exception", false); + fail("should throw an exception"); } catch (JSONException e) { /** * Not sure of the missing char, but full string compare fails */ - assertTrue("Expecting an exception message", - e.getMessage().startsWith("Expected '=' and instead saw '") && - e.getMessage().endsWith("' at 27 [character 28 line 1]")); + assertEquals("Expecting an exception message", + "Expected '=' and instead saw '' at 25 [character 26 line 1]", + e.getMessage()); } } diff --git a/src/test/java/org/json/junit/CookieTest.java b/src/test/java/org/json/junit/CookieTest.java index 9104b60..4b7ca44 100644 --- a/src/test/java/org/json/junit/CookieTest.java +++ b/src/test/java/org/json/junit/CookieTest.java @@ -43,11 +43,11 @@ public class CookieTest { String cookieStr = "thisCookieHasNoEqualsChar"; try { Cookie.toJSONObject(cookieStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - e.getMessage().startsWith("Expected '=' and instead saw '") - && e.getMessage().endsWith("' at 27 [character 28 line 1]")); + assertEquals("Expecting an exception message", + "Expected '=' and instead saw '' at 25 [character 26 line 1]", + e.getMessage()); } } @@ -61,11 +61,11 @@ public class CookieTest { String cookieStr = "this=Cookie;myAttribute"; try { Cookie.toJSONObject(cookieStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Missing '=' in cookie parameter. at 25 [character 26 line 1]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Missing '=' in cookie parameter. at 23 [character 24 line 1]", + e.getMessage()); } } @@ -79,11 +79,11 @@ public class CookieTest { String cookieStr = ""; try { Cookie.toJSONObject(cookieStr); - assertTrue("Expecting an exception", false); + fail("Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - e.getMessage().startsWith("Expected '=' and instead saw '") && - e.getMessage().endsWith("' at 2 [character 3 line 1]")); + assertEquals("Expecting an exception message", + "Expected '=' and instead saw '' at 0 [character 1 line 1]", + e.getMessage()); } } diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 666c03b..0df7c5d 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -74,9 +74,9 @@ public class JSONArrayTest { try { assertNull("Should throw an exception", new JSONArray(str)); } catch (JSONException e) { - assertTrue("Expected an exception message", - "A JSONArray text must start with '[' at 1 [character 2 line 1]". - equals(e.getMessage())); + assertEquals("Expected an exception message", + "A JSONArray text must start with '[' at 0 [character 1 line 1]", + e.getMessage()); } } diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 518c949..84b33ba 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -98,7 +98,7 @@ public class JSONMLTest { fail("Expecting an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "Bad XML at 24 [character 25 line 1]", + "Bad XML at 23 [character 24 line 1]", e.getMessage()); } } @@ -226,7 +226,7 @@ public class JSONMLTest { fail("Expecting an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "Misshaped meta tag at 216 [character 13 line 7]", + "Misshaped meta tag at 215 [character 12 line 7]", e.getMessage()); } } @@ -256,7 +256,7 @@ public class JSONMLTest { fail("Expecting an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "Misshaped meta tag at 215 [character 13 line 7]", + "Misshaped meta tag at 214 [character 12 line 7]", e.getMessage()); } } diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index ebd1cd1..cabd41c 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1853,36 +1853,36 @@ public class JSONObjectTest { String str = "abc"; assertNull("Expected an exception",new JSONObject(str)); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "A JSONObject text must begin with '{' at 1 [character 2 line 1]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "A JSONObject text must begin with '{' at 1 [character 2 line 1]", + e.getMessage()); } try { // does not end with '}' String str = "{"; assertNull("Expected an exception",new JSONObject(str)); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "A JSONObject text must end with '}' at 2 [character 3 line 1]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "A JSONObject text must end with '}' at 1 [character 2 line 1]", + e.getMessage()); } try { // key with no ':' String str = "{\"myKey\" = true}"; assertNull("Expected an exception",new JSONObject(str)); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Expected a ':' after a key at 10 [character 11 line 1]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Expected a ':' after a key at 10 [character 11 line 1]", + e.getMessage()); } try { // entries with no ',' separator String str = "{\"myKey\":true \"myOtherKey\":false}"; assertNull("Expected an exception",new JSONObject(str)); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Expected a ',' or '}' at 15 [character 16 line 1]". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Expected a ',' or '}' at 15 [character 16 line 1]", + e.getMessage()); } try { // append to wrong key @@ -1891,9 +1891,9 @@ public class JSONObjectTest { jsonObject.append("myKey", "hello"); fail("Expected an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONObject[myKey] is not a JSONArray.". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "JSONObject[myKey] is not a JSONArray.", + e.getMessage()); } try { // increment wrong key @@ -1902,9 +1902,9 @@ public class JSONObjectTest { jsonObject.increment("myKey"); fail("Expected an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Unable to increment [\"myKey\"].". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Unable to increment [\"myKey\"].", + e.getMessage()); } try { // invalid key @@ -1913,18 +1913,18 @@ public class JSONObjectTest { jsonObject.get(null); fail("Expected an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Null key.". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Null key.", + e.getMessage()); } try { // invalid numberToString() JSONObject.numberToString((Number)null); fail("Expected an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Null pointer". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "Null pointer", + e.getMessage()); } try { // null put key diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 11566c6..244c9e9 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -103,7 +103,7 @@ public class XMLTest { fail("Expecting a JSONException"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "Misshaped meta tag at 215 [character 13 line 7]", + "Misshaped meta tag at 214 [character 12 line 7]", e.getMessage()); } } @@ -128,7 +128,7 @@ public class XMLTest { fail("Expecting a JSONException"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "Misshaped meta tag at 214 [character 13 line 7]", + "Misshaped meta tag at 213 [character 12 line 7]", e.getMessage()); } } From e7e6ed9205b7aa127a70d3cf4e0275e7dc3d4f8b Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 23 Jun 2017 13:40:41 -0400 Subject: [PATCH 312/451] Fixes position reports on errors --- CDL.java | 11 +++--- JSONTokener.java | 93 ++++++++++++++++++++++++++++-------------------- XMLTokener.java | 11 +++--- 3 files changed, 67 insertions(+), 48 deletions(-) diff --git a/CDL.java b/CDL.java index 6a82764..1c7df32 100644 --- a/CDL.java +++ b/CDL.java @@ -22,7 +22,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ + */ /** * This provides static methods to convert comma delimited text into a @@ -70,9 +70,12 @@ public class CDL { c = x.next(); if (c == q) { //Handle escaped double-quote - if(x.next() != '\"') - { - x.back(); + char nextC = x.next(); + if(nextC != '\"') { + // if our quote was the end of the file, don't step + if(nextC > 0) { + x.back(); + } break; } } diff --git a/JSONTokener.java b/JSONTokener.java index b244d13..956efcf 100644 --- a/JSONTokener.java +++ b/JSONTokener.java @@ -29,7 +29,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ + */ /** * A JSONTokener takes a source string and extracts characters and tokens from @@ -39,7 +39,7 @@ SOFTWARE. * @version 2014-05-03 */ public class JSONTokener { - /** current read character. */ + /** current read character position on the current line. */ private long character; /** flag to indicate if the end of the input has been found. */ private boolean eof; @@ -47,7 +47,7 @@ public class JSONTokener { private long index; /** current line of the input. */ private long line; - /** previous index of the input. */ + /** previous character read from the input. */ private char previous; /** Reader for the input. */ private final Reader reader; @@ -62,8 +62,8 @@ public class JSONTokener { */ public JSONTokener(Reader reader) { this.reader = reader.markSupported() - ? reader - : new BufferedReader(reader); + ? reader + : new BufferedReader(reader); this.eof = false; this.usePrevious = false; this.previous = 0; @@ -103,8 +103,8 @@ public class JSONTokener { if (this.usePrevious || this.index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } - this.index -= 1; - this.character -= 1; + this.index--; + this.character--; this.usePrevious = true; this.eof = false; } @@ -145,11 +145,23 @@ public class JSONTokener { * or backward while checking for more data. */ public boolean more() throws JSONException { - this.next(); - if (this.end()) { - return false; + if(this.usePrevious) { + return true; + } + try { + this.reader.mark(1); + } catch (IOException e) { + throw new JSONException("Unable to preserve stream position", e); + } + try { + if(this.reader.read()<0) { + this.eof = true; + return false; + } + this.reader.reset(); + } catch (IOException e) { + throw new JSONException("Unable to read the next character from the stream", e); } - this.back(); return true; } @@ -174,7 +186,7 @@ public class JSONTokener { if (c <= 0) { // End of stream this.eof = true; - c = 0; + return 0; } } this.index += 1; @@ -202,8 +214,11 @@ public class JSONTokener { public char next(char c) throws JSONException { char n = this.next(); if (n != c) { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + - n + "'"); + if(n > 0) { + throw this.syntaxError("Expected '" + c + "' and instead saw '" + + n + "'"); + } + throw this.syntaxError("Expected '" + c + "' and instead saw ''"); } return n; } @@ -218,23 +233,23 @@ public class JSONTokener { * Substring bounds error if there are not * n characters remaining in the source string. */ - public String next(int n) throws JSONException { - if (n == 0) { - return ""; - } + public String next(int n) throws JSONException { + if (n == 0) { + return ""; + } - char[] chars = new char[n]; - int pos = 0; + char[] chars = new char[n]; + int pos = 0; - while (pos < n) { - chars[pos] = this.next(); - if (this.end()) { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } + while (pos < n) { + chars[pos] = this.next(); + if (this.end()) { + throw this.syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } /** @@ -378,15 +393,15 @@ public class JSONTokener { String string; switch (c) { - case '"': - case '\'': - return this.nextString(c); - case '{': - this.back(); - return new JSONObject(this); - case '[': - this.back(); - return new JSONArray(this); + case '"': + case '\'': + return this.nextString(c); + case '{': + this.back(); + return new JSONObject(this); + case '[': + this.back(); + return new JSONArray(this); } /* @@ -476,6 +491,6 @@ public class JSONTokener { @Override public String toString() { return " at " + this.index + " [character " + this.character + " line " + - this.line + "]"; + this.line + "]"; } } diff --git a/XMLTokener.java b/XMLTokener.java index e45e747..1c5f2b5 100644 --- a/XMLTokener.java +++ b/XMLTokener.java @@ -64,11 +64,8 @@ public class XMLTokener extends JSONTokener { char c; int i; StringBuilder sb = new StringBuilder(); - for (;;) { + while (more()) { c = next(); - if (end()) { - throw syntaxError("Unclosed CDATA"); - } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && @@ -77,6 +74,7 @@ public class XMLTokener extends JSONTokener { return sb.toString(); } } + throw syntaxError("Unclosed CDATA"); } @@ -103,7 +101,10 @@ public class XMLTokener extends JSONTokener { } sb = new StringBuilder(); for (;;) { - if (c == '<' || c == 0) { + if (c == 0) { + return sb.toString().trim(); + } + if (c == '<') { back(); return sb.toString().trim(); } From af39376d926b8a1aaf21646e63131e9acecfd996 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 23 Jun 2017 23:25:11 -0400 Subject: [PATCH 313/451] more fixes for testing postition information --- src/test/java/org/json/junit/CDLTest.java | 6 +- .../java/org/json/junit/JSONPointerTest.java | 22 ++- .../java/org/json/junit/JSONTokenerTest.java | 158 ++++++++++++++++++ 3 files changed, 179 insertions(+), 7 deletions(-) create mode 100644 src/test/java/org/json/junit/JSONTokenerTest.java diff --git a/src/test/java/org/json/junit/CDLTest.java b/src/test/java/org/json/junit/CDLTest.java index b99e17c..b1f9561 100644 --- a/src/test/java/org/json/junit/CDLTest.java +++ b/src/test/java/org/json/junit/CDLTest.java @@ -81,7 +81,7 @@ public class CDLTest { fail("Expecting an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "Missing close quote '\"'. at 22 [character 11 line 3]", + "Missing close quote '\"'. at 22 [character 11 line 2]", e.getMessage()); } @@ -117,7 +117,7 @@ public class CDLTest { fail("Expecting an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "Missing close quote '\"'. at 26 [character 15 line 3]", + "Missing close quote '\"'. at 26 [character 15 line 2]", e.getMessage()); } @@ -168,7 +168,7 @@ public class CDLTest { } catch (JSONException e) { System.out.println("Message" + e.getMessage()); assertEquals("Expecting an exception message", - "Bad character 'V' (86). at 20 [character 9 line 3]", + "Bad character 'V' (86). at 20 [character 9 line 2]", e.getMessage()); } diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index 0904b9e..19dac47 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -1,8 +1,18 @@ package org.json.junit; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; -import org.json.*; +import java.io.IOException; +import java.io.InputStream; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.json.JSONPointer; +import org.json.JSONPointerException; +import org.json.JSONTokener; import org.junit.Test; public class JSONPointerTest { @@ -10,8 +20,12 @@ public class JSONPointerTest { private static final JSONObject document; static { - document = new JSONObject(new JSONTokener( - JSONPointerTest.class.getClassLoader().getResourceAsStream("jsonpointer-testdoc.json"))); + @SuppressWarnings("resource") + InputStream resourceAsStream = JSONPointerTest.class.getClassLoader().getResourceAsStream("jsonpointer-testdoc.json"); + if(resourceAsStream == null) { + throw new ExceptionInInitializerError("Unable to locate test file. Please check your development environment configuration"); + } + document = new JSONObject(new JSONTokener(resourceAsStream)); } private Object query(String pointer) { diff --git a/src/test/java/org/json/junit/JSONTokenerTest.java b/src/test/java/org/json/junit/JSONTokenerTest.java new file mode 100644 index 0000000..5fe2259 --- /dev/null +++ b/src/test/java/org/json/junit/JSONTokenerTest.java @@ -0,0 +1,158 @@ +package org.json.junit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; + +import org.json.JSONException; +import org.json.JSONTokener; +import org.junit.Test; + +/** + * Test specific to the {@link org.json.JSONTokener} class. + * @author John Aylward + * + */ +public class JSONTokenerTest { + + /** + * verify that back() fails as expected. + * @throws IOException thrown if something unexpected happens. + */ + @Test + public void verifyBackFailureZeroIndex() throws IOException { + try(Reader reader = new StringReader("some test string")) { + final JSONTokener tokener = new JSONTokener(reader); + try { + // this should fail since the index is 0; + tokener.back(); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Stepping back two steps is not supported", e.getMessage()); + } catch (Exception e) { + fail("Unknown Exception type " + e.getClass().getCanonicalName()+" with message "+e.getMessage()); + } + + } + } + /** + * verify that back() fails as expected. + * @throws IOException thrown if something unexpected happens. + */ + @Test + public void verifyBackFailureDoubleBack() throws IOException { + try(Reader reader = new StringReader("some test string")) { + final JSONTokener tokener = new JSONTokener(reader); + tokener.next(); + tokener.back(); + try { + // this should fail since the index is 0; + tokener.back(); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Stepping back two steps is not supported", e.getMessage()); + } catch (Exception e) { + fail("Unknown Exception type " + e.getClass().getCanonicalName()+" with message "+e.getMessage()); + } + } + } + + /** + * Tests the failure of the skipTo method with a buffered reader. Preferably + * we'd like this not to fail but at this time we don't have a good recovery. + * + * @throws IOException thrown if something unexpected happens. + */ + @Test + public void testSkipToFailureWithBufferedReader() throws IOException { + final byte[] superLongBuffer = new byte[1000001]; + // fill our buffer + for(int i=0;i Date: Fri, 23 Jun 2017 23:55:22 -0400 Subject: [PATCH 314/451] Updates test coverage table --- README.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 0772d3b..79f8724 100644 --- a/README.md +++ b/README.md @@ -101,24 +101,26 @@ A unit test has the following stages: | CDL.java | 98.8% | Reasonable test cases. | | Cookie.java | 98.9% | Reasonable test cases. | | CookieList.java |96.5% | Reasonable test cases. | -| EnumTest.java | n/a | Just documenting how enums are handled. | -| HTTP.java | 98.7%| Coverage > 90% | +| HTTP.java | 98.8%| Coverage > 90% | | HTTPTokener.java |93.2% | No test | -| JSONArray.java |95.9% | Reasonable test cases | -| JSONException.java | 26.7% | No test | -| JSONML.java | 86.8%| In progress | -| JSONObject | 94.0% | Reasonable test cases | -| JSONObject.Null | 87.5% | No test | +| JSONArray.java |88.3% | Reasonable test cases. Need new tests for newer API functions | +| JSONException.java | 100% | No test | +| JSONML.java | 84.4%| In progress | +| JSONObject | 96.7% | Reasonable test cases | +| JSONObject.Null | 77.8% | No test | +| JSONPointer | 96.3% | Reasonable test cases | +| JSONPointerException | 100% | No test | | JSONString.java | | No test | | JSONStringer.java | 93.8%| Coverage > 90% | -| JSONTokener.java | 72.1% | In progress | -| JSONWriter.java | 87.5% | No test | -| Property.java | 94.8% | Coverage > 90% | -| XML.java | 87.4% | In progress | -| XMLTokener.java| 82.7%| No test | +| JSONTokener.java | 87.5% | In progress | +| JSONWriter.java | 89.15% | No test | +| Property.java | 95.8% | Coverage > 90% | +| XML.java | 77.3% | In progress | +| XMLTokener.java| 82.4%| No test | | Files used in test | | ------------- | +| EnumTest.java | | MyBean.java | | MyBigNumberBean.java | | MyEnum.java | From 899cf528df591420ba107af445bed46d80cd316f Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sat, 24 Jun 2017 13:10:14 -0400 Subject: [PATCH 315/451] More test cases for position information --- .../java/org/json/junit/JSONTokenerTest.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/test/java/org/json/junit/JSONTokenerTest.java b/src/test/java/org/json/junit/JSONTokenerTest.java index 5fe2259..dced89f 100644 --- a/src/test/java/org/json/junit/JSONTokenerTest.java +++ b/src/test/java/org/json/junit/JSONTokenerTest.java @@ -1,6 +1,8 @@ package org.json.junit; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.BufferedReader; @@ -121,7 +123,12 @@ public class JSONTokenerTest { @Test public void testNextBackComboWithNewLines() { final String testString = "this is\nA test\r\nWith some different\rNew Lines"; + // ^ ^ ^ ^ + // index positions 0 8 16 36 final JSONTokener tokener = new JSONTokener(testString); + assertEquals(" at 0 [character 1 line 1]", tokener.toString()); + assertEquals('t',tokener.next()); + assertEquals(" at 1 [character 2 line 1]", tokener.toString()); tokener.skipTo('\n'); assertEquals("skipTo() improperly modifying indexes"," at 7 [character 8 line 1]", tokener.toString()); assertEquals('\n',tokener.next()); @@ -132,10 +139,12 @@ public class JSONTokenerTest { assertEquals(" at 8 [character 0 line 2]", tokener.toString()); tokener.skipTo('\r'); assertEquals("skipTo() improperly modifying indexes"," at 14 [character 6 line 2]", tokener.toString()); + // verify \r\n combo doesn't increment the line twice assertEquals('\r', tokener.next()); assertEquals(" at 15 [character 0 line 3]", tokener.toString()); assertEquals('\n', tokener.next()); assertEquals(" at 16 [character 0 line 3]", tokener.toString()); + // verify stepping back after reading the \n of an \r\n combo doesn't increment the line incorrectly tokener.back(); assertEquals(" at 15 [character 6 line 2]", tokener.toString()); assertEquals('\n', tokener.next()); @@ -154,5 +163,39 @@ public class JSONTokenerTest { assertEquals(" at 36 [character 0 line 4]", tokener.toString()); assertEquals('N', tokener.next()); assertEquals(" at 37 [character 1 line 4]", tokener.toString()); + + // verify we get the same data just walking though, no calls to back + final JSONTokener t2 = new JSONTokener(testString); + for(int i=0; i<7; i++) { + assertTrue(t2.toString().startsWith(" at " + i + " ")); + assertEquals(testString.charAt(i), t2.next()); + } + assertEquals(" at 7 [character 8 line 1]", t2.toString()); + assertEquals(testString.charAt(7), t2.next()); + assertEquals(" at 8 [character 0 line 2]", t2.toString()); + for(int i=8; i<14; i++) { + assertTrue(t2.toString().startsWith(" at " + i + " ")); + assertEquals(testString.charAt(i), t2.next()); + } + assertEquals(" at 14 [character 6 line 2]", t2.toString()); + assertEquals('\r', t2.next()); + assertEquals(" at 15 [character 0 line 3]", t2.toString()); + assertEquals('\n', t2.next()); + assertEquals(" at 16 [character 0 line 3]", t2.toString()); + assertEquals('W', t2.next()); + assertEquals(" at 17 [character 1 line 3]", t2.toString()); + for(int i=17; i<37; i++) { + assertTrue(t2.toString().startsWith(" at " + i + " ")); + assertEquals(testString.charAt(i), t2.next()); + } + assertEquals(" at 37 [character 1 line 4]", t2.toString()); + for(int i=37; i Date: Fri, 23 Jun 2017 23:27:28 -0400 Subject: [PATCH 316/451] Fixes more position errors from stepping to new lines and then back. --- JSONTokener.java | 70 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 50 insertions(+), 20 deletions(-) diff --git a/JSONTokener.java b/JSONTokener.java index 956efcf..741e78b 100644 --- a/JSONTokener.java +++ b/JSONTokener.java @@ -53,10 +53,12 @@ public class JSONTokener { private final Reader reader; /** flag to indicate that a previous character was requested. */ private boolean usePrevious; + /** the number of characters read in the previous line. */ + private long characterPreviousLine; /** - * Construct a JSONTokener from a Reader. + * Construct a JSONTokener from a Reader. The caller must close the Reader. * * @param reader A reader. */ @@ -69,12 +71,13 @@ public class JSONTokener { this.previous = 0; this.index = 0; this.character = 1; + this.characterPreviousLine = 0; this.line = 1; } /** - * Construct a JSONTokener from an InputStream. + * Construct a JSONTokener from an InputStream. The caller must close the input stream. * @param inputStream The source. */ public JSONTokener(InputStream inputStream) { @@ -103,12 +106,23 @@ public class JSONTokener { if (this.usePrevious || this.index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } - this.index--; - this.character--; + this.decrementIndexes(); this.usePrevious = true; this.eof = false; } + /** + * Decrements the indexes for the {@link #back()} method based on the previous character read. + */ + private void decrementIndexes() { + this.index--; + if(this.previous=='\r' || this.previous == '\n') { + this.line--; + this.character=this.characterPreviousLine ; + } else if(this.character > 0){ + this.character--; + } + } /** * Get the hex value of a character (base16). @@ -183,26 +197,39 @@ public class JSONTokener { } catch (IOException exception) { throw new JSONException(exception); } - - if (c <= 0) { // End of stream - this.eof = true; - return 0; - } } - this.index += 1; - if (this.previous == '\r') { - this.line += 1; - this.character = c == '\n' ? 0 : 1; - } else if (c == '\n') { - this.line += 1; - this.character = 0; - } else { - this.character += 1; + if (c <= 0) { // End of stream + this.eof = true; + return 0; } + this.incrementIndexes(c); this.previous = (char) c; return this.previous; } + /** + * Increments the internal indexes according to the previous character + * read and the character passed as the current character. + * @param c the current character read. + */ + private void incrementIndexes(int c) { + if(c > 0) { + this.index++; + if(c=='\r') { + this.line++; + this.characterPreviousLine = this.character; + this.character=0; + }else if (c=='\n') { + if(this.previous != '\r') { + this.line++; + this.characterPreviousLine = this.character; + } + this.character=0; + } else { + this.character++; + } + } + } /** * Consume the next character, and check that it matches a specified @@ -447,13 +474,17 @@ public class JSONTokener { do { c = this.next(); if (c == 0) { + // in some readers, reset() may throw an exception if + // the remaining portion of the input is greater than + // the mark size (1,000,000 above). this.reader.reset(); this.index = startIndex; this.character = startCharacter; this.line = startLine; - return c; + return 0; } } while (c != to); + this.reader.mark(1); } catch (IOException exception) { throw new JSONException(exception); } @@ -461,7 +492,6 @@ public class JSONTokener { return c; } - /** * Make a JSONException to signal a syntax error. * From 16baa323cff49ff9000bc7aa0a90791be84d5627 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 26 Jun 2017 10:32:02 -0400 Subject: [PATCH 317/451] adds comments --- JSONTokener.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/JSONTokener.java b/JSONTokener.java index 741e78b..36bce45 100644 --- a/JSONTokener.java +++ b/JSONTokener.java @@ -144,6 +144,8 @@ public class JSONTokener { } /** + * Checks if the end of the input has been reached. + * * @return true if at the end of the file and we didn't step back */ public boolean end() { @@ -168,7 +170,8 @@ public class JSONTokener { throw new JSONException("Unable to preserve stream position", e); } try { - if(this.reader.read()<0) { + // -1 is EOF, but next() can not consume the null character '\0' + if(this.reader.read() <= 0) { this.eof = true; return false; } From e8b1b66888f95341b629aa6667b2820823a1ca2f Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 21 Jun 2017 11:52:15 -0400 Subject: [PATCH 318/451] Updates for supporting the Android API --- CookieList.java | 14 +++---- HTTP.java | 8 ++-- JSONML.java | 14 +++---- JSONObject.java | 56 ++++------------------------ JSONPointer.java | 17 ++++++--- JSONWriter.java | 96 +++++++++++++++++++++++++++++++++++++++++++++++- Property.java | 8 ++-- XML.java | 77 ++++++++++++++++++++++++++++++-------- XMLTokener.java | 9 ++--- 9 files changed, 198 insertions(+), 101 deletions(-) diff --git a/CookieList.java b/CookieList.java index 8cb4e5e..c67ee3a 100644 --- a/CookieList.java +++ b/CookieList.java @@ -1,7 +1,5 @@ package org.json; -import java.util.Map.Entry; - /* Copyright (c) 2002 JSON.org @@ -24,7 +22,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ + */ /** * Convert a web browser cookie list string to a JSONObject and back. @@ -69,17 +67,17 @@ public class CookieList { */ public static String toString(JSONObject jo) throws JSONException { boolean b = false; - StringBuilder sb = new StringBuilder(); - for (final Entry entry : jo.entrySet()) { - final String key = entry.getKey(); - final Object value = entry.getValue(); + final StringBuilder sb = new StringBuilder(); + // Don't use the new entrySet API to maintain Android support + for (final String key : jo.keySet()) { + final Object value = jo.opt(key); if (!JSONObject.NULL.equals(value)) { if (b) { sb.append(';'); } sb.append(Cookie.escape(key)); sb.append("="); - sb.append(Cookie.escape(value.toString())); + sb.append(Cookie.escape(value.toString())); b = true; } } diff --git a/HTTP.java b/HTTP.java index 22635ff..70b88ee 100644 --- a/HTTP.java +++ b/HTTP.java @@ -25,7 +25,6 @@ SOFTWARE. */ import java.util.Locale; -import java.util.Map.Entry; /** * Convert an HTTP header to a JSONObject and back. @@ -145,11 +144,12 @@ public class HTTP { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); - for (final Entry entry : jo.entrySet()) { - final String key = entry.getKey(); + // Don't use the new entrySet API to maintain Android support + for (final String key : jo.keySet()) { + String value = jo.optString(key); if (!"HTTP-Version".equals(key) && !"Status-Code".equals(key) && !"Reason-Phrase".equals(key) && !"Method".equals(key) && - !"Request-URI".equals(key) && !JSONObject.NULL.equals(entry.getValue())) { + !"Request-URI".equals(key) && !JSONObject.NULL.equals(value)) { sb.append(key); sb.append(": "); sb.append(jo.optString(key)); diff --git a/JSONML.java b/JSONML.java index c1d50b3..2dcbd25 100644 --- a/JSONML.java +++ b/JSONML.java @@ -1,7 +1,5 @@ package org.json; -import java.util.Map.Entry; - /* Copyright (c) 2008 JSON.org @@ -416,10 +414,10 @@ public class JSONML { // Emit the attributes - for (final Entry entry : jo.entrySet()) { - final String key = entry.getKey(); + // Don't use the new entrySet API to maintain Android support + for (final String key : jo.keySet()) { + final Object value = jo.opt(key); XML.noSpace(key); - final Object value = entry.getValue(); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); @@ -495,11 +493,11 @@ public class JSONML { //Emit the attributes - for (final Entry entry : jo.entrySet()) { - final String key = entry.getKey(); + // Don't use the new entrySet API to maintain Android support + for (final String key : jo.keySet()) { if (!"tagName".equals(key) && !"childNodes".equals(key)) { XML.noSpace(key); - value = entry.getValue(); + value = jo.opt(key); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); diff --git a/JSONObject.java b/JSONObject.java index 8ad7864..89c94f4 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1908,6 +1908,8 @@ public class JSONObject { * A String. * @return A simple JSON value. */ + // Changes to this method must be copied to the corresponding method in + // the XML class to keep full support for Android public static Object stringToValue(String string) { if (string.equals("")) { return string; @@ -2065,55 +2067,11 @@ public class JSONObject { * If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { - if (value == null || value.equals(null)) { - return "null"; - } - if (value instanceof JSONString) { - Object object; - try { - object = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - if (object instanceof String) { - return (String) object; - } - throw new JSONException("Bad value from toJSONString: " + object); - } - if (value instanceof Number) { - // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex - final String numberAsString = numberToString((Number) value); - try { - // Use the BigDecimal constructor for it's parser to validate the format. - @SuppressWarnings("unused") - BigDecimal unused = new BigDecimal(numberAsString); - // Close enough to a JSON number that we will return it unquoted - return numberAsString; - } catch (NumberFormatException ex){ - // The Number value is not a valid JSON number. - // Instead we will quote it as a string - return quote(numberAsString); - } - } - if (value instanceof Boolean || value instanceof JSONObject - || value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - Map map = (Map) value; - return new JSONObject(map).toString(); - } - if (value instanceof Collection) { - Collection coll = (Collection) value; - return new JSONArray(coll).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - if(value instanceof Enum){ - return quote(((Enum)value).name()); - } - return quote(value.toString()); + // moves the implementation to JSONWriter as: + // 1. It makes more sense to be part of the writer class + // 2. For Android support this method is not available. By implementing it in the Writer + // Android users can use the writer with the built in Android JSONObject implementation. + return JSONWriter.valueToString(value); } /** diff --git a/JSONPointer.java b/JSONPointer.java index 8142f9a..0040e17 100644 --- a/JSONPointer.java +++ b/JSONPointer.java @@ -5,7 +5,9 @@ import static java.lang.String.format; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; /* Copyright (c) 2002 JSON.org @@ -181,7 +183,7 @@ public class JSONPointer { * @return the result of the evaluation * @throws JSONPointerException if an error occurs during evaluation */ - public Object queryFrom(Object document) { + public Object queryFrom(Object document) throws JSONPointerException { if (this.refTokens.isEmpty()) { return document; } @@ -205,10 +207,9 @@ public class JSONPointer { * @param current the JSONArray to be evaluated * @param indexToken the array index in string form * @return the matched object. If no matching item is found a - * JSONPointerException is thrown + * @throws JSONPointerException is thrown if the index is out of bounds */ - @SuppressWarnings("boxing") - private Object readByIndexToken(Object current, String indexToken) { + private Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { try { int index = Integer.parseInt(indexToken); JSONArray currentArr = (JSONArray) current; @@ -216,7 +217,11 @@ public class JSONPointer { throw new JSONPointerException(format("index %d is out of bounds - the array has %d elements", index, currentArr.length())); } - return currentArr.get(index); + try { + return currentArr.get(index); + } catch (JSONException e) { + throw new JSONPointerException("Error reading value at index position " + index, e); + } } catch (NumberFormatException e) { throw new JSONPointerException(format("%s is not an array index", indexToken), e); } diff --git a/JSONWriter.java b/JSONWriter.java index 549f93e..ac5a805 100644 --- a/JSONWriter.java +++ b/JSONWriter.java @@ -1,6 +1,9 @@ package org.json; import java.io.IOException; +import java.math.BigDecimal; +import java.util.Collection; +import java.util.Map; /* Copyright (c) 2006 JSON.org @@ -117,6 +120,9 @@ public class JSONWriter { } this.writer.append(string); } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. throw new JSONException(e); } if (this.mode == 'o') { @@ -164,6 +170,9 @@ public class JSONWriter { try { this.writer.append(c); } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. throw new JSONException(e); } this.comma = true; @@ -204,7 +213,12 @@ public class JSONWriter { } if (this.mode == 'k') { try { - this.stack[this.top - 1].putOnce(string, Boolean.TRUE); + JSONObject topObject = this.stack[this.top - 1]; + // don't use the built in putOnce method to maintain Android support + if(topObject.has(string)) { + throw new JSONException("Duplicate key \"" + string + "\""); + } + topObject.put(string, true); if (this.comma) { this.writer.append(','); } @@ -214,6 +228,9 @@ public class JSONWriter { this.mode = 'o'; return this; } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. throw new JSONException(e); } } @@ -280,6 +297,81 @@ public class JSONWriter { this.top += 1; } + /** + * 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. + * + *

+ * 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 { (left + * brace) and ending with } (right + * brace). + * @throws JSONException + * If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof JSONString) { + Object object; + try { + object = ((JSONString) value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + if (object instanceof String) { + return (String) object; + } + throw new JSONException("Bad value from toJSONString: " + object); + } + if (value instanceof Number) { + // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex + final String numberAsString = JSONObject.numberToString((Number) value); + try { + // Use the BigDecimal constructor for it's parser to validate the format. + @SuppressWarnings("unused") + BigDecimal unused = new BigDecimal(numberAsString); + // Close enough to a JSON number that we will return it unquoted + return numberAsString; + } catch (NumberFormatException ex){ + // The Number value is not a valid JSON number. + // Instead we will quote it as a string + return JSONObject.quote(numberAsString); + } + } + if (value instanceof Boolean || value instanceof JSONObject + || value instanceof JSONArray) { + return value.toString(); + } + if (value instanceof Map) { + Map map = (Map) value; + return new JSONObject(map).toString(); + } + if (value instanceof Collection) { + Collection coll = (Collection) value; + return new JSONArray(coll).toString(); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(); + } + if(value instanceof Enum){ + return JSONObject.quote(((Enum)value).name()); + } + return JSONObject.quote(value.toString()); + } /** * Append either the value true or the value @@ -321,6 +413,6 @@ public class JSONWriter { * @throws JSONException If the value is out of sequence. */ public JSONWriter value(Object object) throws JSONException { - return this.append(JSONObject.valueToString(object)); + return this.append(valueToString(object)); } } diff --git a/Property.java b/Property.java index 51b97ed..de3e5dd 100644 --- a/Property.java +++ b/Property.java @@ -25,7 +25,6 @@ SOFTWARE. */ import java.util.Enumeration; -import java.util.Map.Entry; import java.util.Properties; /** @@ -61,10 +60,11 @@ public class Property { public static Properties toProperties(JSONObject jo) throws JSONException { Properties properties = new Properties(); if (jo != null) { - for (final Entry entry : jo.entrySet()) { - Object value = entry.getValue(); + // Don't use the new entrySet API to maintain Android support + for (final String key : jo.keySet()) { + Object value = jo.opt(key); if (!JSONObject.NULL.equals(value)) { - properties.put(entry.getKey(), value.toString()); + properties.put(key, value.toString()); } } } diff --git a/XML.java b/XML.java index 4dd9a2c..b2cff20 100644 --- a/XML.java +++ b/XML.java @@ -25,7 +25,6 @@ SOFTWARE. */ import java.util.Iterator; -import java.util.Map.Entry; /** * This provides static methods to convert an XML text into a JSONObject, and to @@ -430,11 +429,49 @@ public class XML { * @return JSON value of this string or the string */ public static Object stringToValue(String string) { - Object ret = JSONObject.stringToValue(string); - if(ret instanceof String){ - return unescape((String)ret); + if (string.equals("")) { + return string; } - return ret; + if (string.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (string.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (string.equalsIgnoreCase("null")) { + return JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. If a number cannot be + * produced, then the value will just be a string. + */ + + char initial = string.charAt(0); + if ((initial >= '0' && initial <= '9') || initial == '-') { + try { + // if we want full Big Number support this block can be replaced with: + // return stringToNumber(string); + if (string.indexOf('.') > -1 || string.indexOf('e') > -1 + || string.indexOf('E') > -1 || "-0".equals(string)) { + Double d = Double.valueOf(string); + if (!d.isInfinite() && !d.isNaN()) { + return d; + } + } else { + Long myLong = Long.valueOf(string); + if (string.equals(myLong.toString())) { + if (myLong.longValue() == myLong.intValue()) { + return Integer.valueOf(myLong.intValue()); + } + return myLong; + } + } + } catch (Exception ignore) { + } + } + + return unescape(string); } /** @@ -482,8 +519,11 @@ public class XML { public static JSONObject toJSONObject(String string, boolean keepStrings) throws JSONException { JSONObject jo = new JSONObject(); XMLTokener x = new XMLTokener(string); - while (x.more() && x.skipPast("<")) { - parse(x, jo, null, keepStrings); + while (x.more()) { + x.skipPast("<"); + if(x.more()) { + parse(x, jo, null, keepStrings); + } } return jo; } @@ -526,10 +566,10 @@ public class XML { } // Loop thru the keys. + // don't use the new entrySet accessor to maintain Android Support jo = (JSONObject) object; - for (final Entry entry : jo.entrySet()) { - final String key = entry.getKey(); - Object value = entry.getValue(); + for (final String key : jo.keySet()) { + Object value = jo.opt(key); if (value == null) { value = ""; } else if (value.getClass().isArray()) { @@ -540,13 +580,14 @@ public class XML { if ("content".equals(key)) { if (value instanceof JSONArray) { ja = (JSONArray) value; - int i = 0; - for (Object val : ja) { + int jaLength = ja.length(); + // don't use the new iterator API to maintain support for Android + for (int i = 0; i < jaLength; i++) { if (i > 0) { sb.append('\n'); } + Object val = ja.opt(i); sb.append(escape(val.toString())); - i++; } } else { sb.append(escape(value.toString())); @@ -556,7 +597,10 @@ public class XML { } else if (value instanceof JSONArray) { ja = (JSONArray) value; - for (Object val : ja) { + int jaLength = ja.length(); + // don't use the new iterator API to maintain support for Android + for (int i = 0; i < jaLength; i++) { + Object val = ja.opt(i); if (val instanceof JSONArray) { sb.append('<'); sb.append(key); @@ -597,7 +641,10 @@ public class XML { } else { ja = (JSONArray) object; } - for (Object val : ja) { + int jaLength = ja.length(); + // don't use the new iterator API to maintain support for Android + for (int i = 0; i < jaLength; i++) { + Object val = ja.opt(i); // XML does not have good support for arrays. If an array // appears in a place where XML is lacking, synthesize an // element. diff --git a/XMLTokener.java b/XMLTokener.java index 1c5f2b5..5bed89e 100644 --- a/XMLTokener.java +++ b/XMLTokener.java @@ -297,9 +297,8 @@ public class XMLTokener extends JSONTokener { * Skip characters until past the requested string. * If it is not found, we are left at the end of the source with a result of false. * @param to A string to skip past. - * @throws JSONException */ - public boolean skipPast(String to) throws JSONException { + public void skipPast(String to) { boolean b; char c; int i; @@ -316,7 +315,7 @@ public class XMLTokener extends JSONTokener { for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { - return false; + return; } circle[i] = c; } @@ -343,14 +342,14 @@ public class XMLTokener extends JSONTokener { /* If we exit the loop with b intact, then victory is ours. */ if (b) { - return true; + return; } /* Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { - return false; + return; } /* * Shove the character in the circle buffer and advance the From 1736a60ffe00b1e529cc43a7ba6df0a2b72472de Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 21 Jun 2017 12:22:23 -0400 Subject: [PATCH 319/451] adds comment for the API change --- XMLTokener.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/XMLTokener.java b/XMLTokener.java index 5bed89e..2ff3aff 100644 --- a/XMLTokener.java +++ b/XMLTokener.java @@ -298,6 +298,9 @@ public class XMLTokener extends JSONTokener { * If it is not found, we are left at the end of the source with a result of false. * @param to A string to skip past. */ + // The Android implementation of JSONTokener has a public method of public void skipPast(String to) + // even though ours does not have that method, to have API compatibility, our method in the subclass + // should match. public void skipPast(String to) { boolean b; char c; From 3997a90d584e2f2cd0fea9e514b2b8984b835c0f Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 7 Jul 2017 12:24:27 -0400 Subject: [PATCH 320/451] update constructor call to match Android implementation --- Property.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Property.java b/Property.java index de3e5dd..ff33a04 100644 --- a/Property.java +++ b/Property.java @@ -40,7 +40,9 @@ public class Property { * @throws JSONException */ public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException { - JSONObject jo = new JSONObject(properties == null ? 0 : properties.size()); + // can't use the new constructor for Android support + // JSONObject jo = new JSONObject(properties == null ? 0 : properties.size()); + JSONObject jo = new JSONObject(); if (properties != null && !properties.isEmpty()) { Enumeration enumProperties = properties.propertyNames(); while(enumProperties.hasMoreElements()) { From 643b25140f84231667683b8c8179eb1809b710cb Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 7 Jul 2017 20:48:42 -0400 Subject: [PATCH 321/451] Updates for populateMap based on discussion in #279 and #264 --- JSONObject.java | 55 ++++++++++++++++++++++++++----------------------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index 8ad7864..69c6993 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -28,6 +28,7 @@ import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; @@ -1397,39 +1398,41 @@ public class JSONObject { Method[] methods = includeSuperClass ? klass.getMethods() : klass .getDeclaredMethods(); - for (int i = 0; i < methods.length; i += 1) { - try { - Method method = methods[i]; - if (Modifier.isPublic(method.getModifiers())) { - String name = method.getName(); - String key = ""; - if (name.startsWith("get")) { - if ("getClass".equals(name) - || "getDeclaringClass".equals(name)) { - key = ""; - } else { - key = name.substring(3); - } - } else if (name.startsWith("is")) { - key = name.substring(2); + for (final Method method : methods) { + final int modifiers = method.getModifiers(); + if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) + && method.getParameterTypes().length == 0 && !method.isBridge() + && method.getReturnType() != Void.TYPE ) { + final String name = method.getName(); + String key; + if (name.startsWith("get")) { + if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { + continue; + } + key = name.substring(3); + } else if (name.startsWith("is")) { + key = name.substring(2); + } else { + continue; + } + if (key.length() > 0 && Character.isUpperCase(key.charAt(0))) { + if (key.length() == 1) { + key = key.toLowerCase(Locale.ROOT); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase(Locale.ROOT) + + key.substring(1); } - if (key.length() > 0 - && Character.isUpperCase(key.charAt(0)) - && method.getParameterTypes().length == 0) { - if (key.length() == 1) { - key = key.toLowerCase(Locale.ROOT); - } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase(Locale.ROOT) - + key.substring(1); - } - Object result = method.invoke(bean, (Object[]) null); + try { + final Object result = method.invoke(bean); if (result != null) { this.map.put(key, wrap(result)); } + } catch (IllegalAccessException ignore) { + } catch (IllegalArgumentException ignore) { + } catch (InvocationTargetException ignore) { } } - } catch (Exception ignore) { } } } From 641b68dd55c0682c3ca32034347fd1972131b123 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 7 Jul 2017 21:15:11 -0400 Subject: [PATCH 322/451] updates javadoc. --- JSONObject.java | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index 69c6993..ef2413a 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -277,16 +277,19 @@ public class JSONObject { * "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. - * + *

* The key is formed by removing the "get" or "is" * prefix. If the second remaining character is not upper case, then the * first character is converted to lower case. - * + *

* For example, if an object has a method named "getName", and * if the result of calling object.getName() is * "Larry Fine", then the JSONObject will contain * "name": "Larry Fine". - * + *

+ * Methods that return void as well as static + * methods are ignored. + * * @param bean * An object that has getter methods that should be used to make * a JSONObject. @@ -1389,6 +1392,15 @@ public class JSONObject { return NULL.equals(object) ? defaultValue : object.toString(); } + /** + * Populates the internal map of the JSONObject with the bean properties. + * The bean can not be recursive. + * + * @see JSONObject#JSONObject(Object) + * + * @param bean + * the bean + */ private void populateMap(Object bean) { Class klass = bean.getClass(); From 0e3f23d7a1e70cb3ee95bc834be526cc5fd51882 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sun, 9 Jul 2017 16:33:39 -0400 Subject: [PATCH 323/451] reorganize classes so test data is separate from test cases --- src/test/java/org/json/junit/EnumTest.java | 5 +++- .../org/json/junit/JSONObjectLocaleTest.java | 1 + .../java/org/json/junit/JSONObjectTest.java | 25 ++++++++----------- .../org/json/junit/data/BrokenToString.java | 13 ++++++++++ .../org/json/junit/{ => data}/Fraction.java | 2 +- .../org/json/junit/{ => data}/MyBean.java | 4 +-- .../junit/{ => data}/MyBigNumberBean.java | 4 +-- .../org/json/junit/{ => data}/MyEnum.java | 2 +- .../json/junit/{ => data}/MyEnumClass.java | 2 +- .../json/junit/{ => data}/MyEnumField.java | 2 +- .../json/junit/{ => data}/MyJsonString.java | 4 +-- .../json/junit/{ => data}/MyLocaleBean.java | 2 +- .../org/json/junit/{ => data}/MyNumber.java | 2 +- .../junit/{ => data}/MyNumberContainer.java | 2 +- .../json/junit/{ => data}/MyPublicClass.java | 2 +- .../{ => data}/StringsResourceBundle.java | 2 +- 16 files changed, 44 insertions(+), 30 deletions(-) create mode 100644 src/test/java/org/json/junit/data/BrokenToString.java rename src/test/java/org/json/junit/{ => data}/Fraction.java (99%) rename src/test/java/org/json/junit/{ => data}/MyBean.java (85%) rename src/test/java/org/json/junit/{ => data}/MyBigNumberBean.java (72%) rename src/test/java/org/json/junit/{ => data}/MyEnum.java (76%) rename src/test/java/org/json/junit/{ => data}/MyEnumClass.java (94%) rename src/test/java/org/json/junit/{ => data}/MyEnumField.java (95%) rename src/test/java/org/json/junit/{ => data}/MyJsonString.java (67%) rename src/test/java/org/json/junit/{ => data}/MyLocaleBean.java (88%) rename src/test/java/org/json/junit/{ => data}/MyNumber.java (98%) rename src/test/java/org/json/junit/{ => data}/MyNumberContainer.java (90%) rename src/test/java/org/json/junit/{ => data}/MyPublicClass.java (87%) rename src/test/java/org/json/junit/{ => data}/StringsResourceBundle.java (93%) diff --git a/src/test/java/org/json/junit/EnumTest.java b/src/test/java/org/json/junit/EnumTest.java index 53ac303..cd0d8c0 100644 --- a/src/test/java/org/json/junit/EnumTest.java +++ b/src/test/java/org/json/junit/EnumTest.java @@ -10,6 +10,9 @@ import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; +import org.json.junit.data.MyEnum; +import org.json.junit.data.MyEnumClass; +import org.json.junit.data.MyEnumField; import org.junit.Test; import com.jayway.jsonpath.Configuration; @@ -195,7 +198,7 @@ public class EnumTest { * However, an enum within another class will not be rendered * unless that class overrides default toString() */ - String expectedStr3 = "\"org.json.junit.MyEnumClass@"; + String expectedStr3 = "\"org.json.junit.data.MyEnumClass@"; myEnumClass.setMyEnum(MyEnum.VAL1); myEnumClass.setMyEnumField(MyEnumField.VAL1); String str3 = JSONObject.valueToString(myEnumClass); diff --git a/src/test/java/org/json/junit/JSONObjectLocaleTest.java b/src/test/java/org/json/junit/JSONObjectLocaleTest.java index 9c80ab6..52ef7d5 100755 --- a/src/test/java/org/json/junit/JSONObjectLocaleTest.java +++ b/src/test/java/org/json/junit/JSONObjectLocaleTest.java @@ -5,6 +5,7 @@ import static org.junit.Assert.*; import java.util.*; import org.json.*; +import org.json.junit.data.MyLocaleBean; import org.junit.*; /** diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index cabd41c..372e362 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -30,6 +30,16 @@ import org.json.JSONException; import org.json.JSONObject; import org.json.JSONPointerException; import org.json.XML; +import org.json.junit.data.BrokenToString; +import org.json.junit.data.Fraction; +import org.json.junit.data.MyBean; +import org.json.junit.data.MyBigNumberBean; +import org.json.junit.data.MyEnum; +import org.json.junit.data.MyEnumField; +import org.json.junit.data.MyJsonString; +import org.json.junit.data.MyNumber; +import org.json.junit.data.MyNumberContainer; +import org.json.junit.data.MyPublicClass; import org.junit.Test; import com.jayway.jsonpath.Configuration; @@ -484,7 +494,7 @@ public class JSONObjectTest { @Test public void jsonObjectByResourceBundle() { JSONObject jsonObject = new - JSONObject("org.json.junit.StringsResourceBundle", + JSONObject("org.json.junit.data.StringsResourceBundle", Locale.getDefault()); // validate JSON @@ -2572,18 +2582,5 @@ public class JSONObjectTest { // assert that the new map is mutable assertTrue("Removing a key should succeed", map.remove("key3") != null); assertTrue("Map should have 2 elements", map.size() == 2); - - } - - /** - * test class for verifying write errors. - * @author John Aylward - * - */ - private static class BrokenToString { - @Override - public String toString() { - throw new IllegalStateException("Something went horribly wrong!"); - } } } diff --git a/src/test/java/org/json/junit/data/BrokenToString.java b/src/test/java/org/json/junit/data/BrokenToString.java new file mode 100644 index 0000000..585d751 --- /dev/null +++ b/src/test/java/org/json/junit/data/BrokenToString.java @@ -0,0 +1,13 @@ +package org.json.junit.data; + +/** + * test class for verifying write errors. + * @author John Aylward + * + */ +public class BrokenToString { + @Override + public String toString() { + throw new IllegalStateException("Something went horribly wrong!"); + } +} \ No newline at end of file diff --git a/src/test/java/org/json/junit/Fraction.java b/src/test/java/org/json/junit/data/Fraction.java similarity index 99% rename from src/test/java/org/json/junit/Fraction.java rename to src/test/java/org/json/junit/data/Fraction.java index d5d9eb6..c418179 100644 --- a/src/test/java/org/json/junit/Fraction.java +++ b/src/test/java/org/json/junit/data/Fraction.java @@ -1,4 +1,4 @@ -package org.json.junit; +package org.json.junit.data; import java.math.BigDecimal; import java.math.BigInteger; diff --git a/src/test/java/org/json/junit/MyBean.java b/src/test/java/org/json/junit/data/MyBean.java similarity index 85% rename from src/test/java/org/json/junit/MyBean.java rename to src/test/java/org/json/junit/data/MyBean.java index 53d150a..3190981 100644 --- a/src/test/java/org/json/junit/MyBean.java +++ b/src/test/java/org/json/junit/data/MyBean.java @@ -1,11 +1,11 @@ -package org.json.junit; +package org.json.junit.data; import java.io.*; /** * Used in testing when Bean behavior is needed */ -interface MyBean { +public interface MyBean { public Integer getIntKey(); public Double getDoubleKey(); public String getStringKey(); diff --git a/src/test/java/org/json/junit/MyBigNumberBean.java b/src/test/java/org/json/junit/data/MyBigNumberBean.java similarity index 72% rename from src/test/java/org/json/junit/MyBigNumberBean.java rename to src/test/java/org/json/junit/data/MyBigNumberBean.java index 0ca1870..934dfee 100644 --- a/src/test/java/org/json/junit/MyBigNumberBean.java +++ b/src/test/java/org/json/junit/data/MyBigNumberBean.java @@ -1,11 +1,11 @@ -package org.json.junit; +package org.json.junit.data; import java.math.*; /** * Used in testing when a Bean containing big numbers is needed */ -interface MyBigNumberBean { +public interface MyBigNumberBean { public BigInteger getBigInteger(); public BigDecimal getBigDecimal(); } \ No newline at end of file diff --git a/src/test/java/org/json/junit/MyEnum.java b/src/test/java/org/json/junit/data/MyEnum.java similarity index 76% rename from src/test/java/org/json/junit/MyEnum.java rename to src/test/java/org/json/junit/data/MyEnum.java index 0952bc2..50d9a4f 100644 --- a/src/test/java/org/json/junit/MyEnum.java +++ b/src/test/java/org/json/junit/data/MyEnum.java @@ -1,4 +1,4 @@ -package org.json.junit; +package org.json.junit.data; /** * An enum with no methods or data diff --git a/src/test/java/org/json/junit/MyEnumClass.java b/src/test/java/org/json/junit/data/MyEnumClass.java similarity index 94% rename from src/test/java/org/json/junit/MyEnumClass.java rename to src/test/java/org/json/junit/data/MyEnumClass.java index 8e71663..4d403c8 100644 --- a/src/test/java/org/json/junit/MyEnumClass.java +++ b/src/test/java/org/json/junit/data/MyEnumClass.java @@ -1,4 +1,4 @@ -package org.json.junit; +package org.json.junit.data; /** * this is simply a class that contains some enum instances diff --git a/src/test/java/org/json/junit/MyEnumField.java b/src/test/java/org/json/junit/data/MyEnumField.java similarity index 95% rename from src/test/java/org/json/junit/MyEnumField.java rename to src/test/java/org/json/junit/data/MyEnumField.java index f0833ef..60e89de 100644 --- a/src/test/java/org/json/junit/MyEnumField.java +++ b/src/test/java/org/json/junit/data/MyEnumField.java @@ -1,4 +1,4 @@ -package org.json.junit; +package org.json.junit.data; /** * An enum that contains getters and some internal fields diff --git a/src/test/java/org/json/junit/MyJsonString.java b/src/test/java/org/json/junit/data/MyJsonString.java similarity index 67% rename from src/test/java/org/json/junit/MyJsonString.java rename to src/test/java/org/json/junit/data/MyJsonString.java index 4e63693..4ddde53 100644 --- a/src/test/java/org/json/junit/MyJsonString.java +++ b/src/test/java/org/json/junit/data/MyJsonString.java @@ -1,11 +1,11 @@ -package org.json.junit; +package org.json.junit.data; import org.json.*; /** * Used in testing when a JSONString is needed */ -class MyJsonString implements JSONString { +public class MyJsonString implements JSONString { @Override public String toJSONString() { diff --git a/src/test/java/org/json/junit/MyLocaleBean.java b/src/test/java/org/json/junit/data/MyLocaleBean.java similarity index 88% rename from src/test/java/org/json/junit/MyLocaleBean.java rename to src/test/java/org/json/junit/data/MyLocaleBean.java index 0d68c39..846e1c5 100755 --- a/src/test/java/org/json/junit/MyLocaleBean.java +++ b/src/test/java/org/json/junit/data/MyLocaleBean.java @@ -1,4 +1,4 @@ -package org.json.junit; +package org.json.junit.data; public class MyLocaleBean { private final String id = "beanId"; diff --git a/src/test/java/org/json/junit/MyNumber.java b/src/test/java/org/json/junit/data/MyNumber.java similarity index 98% rename from src/test/java/org/json/junit/MyNumber.java rename to src/test/java/org/json/junit/data/MyNumber.java index 243a967..4b625af 100644 --- a/src/test/java/org/json/junit/MyNumber.java +++ b/src/test/java/org/json/junit/data/MyNumber.java @@ -1,4 +1,4 @@ -package org.json.junit; +package org.json.junit.data; import java.math.BigDecimal; diff --git a/src/test/java/org/json/junit/MyNumberContainer.java b/src/test/java/org/json/junit/data/MyNumberContainer.java similarity index 90% rename from src/test/java/org/json/junit/MyNumberContainer.java rename to src/test/java/org/json/junit/data/MyNumberContainer.java index 524f318..6527652 100644 --- a/src/test/java/org/json/junit/MyNumberContainer.java +++ b/src/test/java/org/json/junit/data/MyNumberContainer.java @@ -1,4 +1,4 @@ -package org.json.junit; +package org.json.junit.data; /** * Class that holds our MyNumber override as a property. diff --git a/src/test/java/org/json/junit/MyPublicClass.java b/src/test/java/org/json/junit/data/MyPublicClass.java similarity index 87% rename from src/test/java/org/json/junit/MyPublicClass.java rename to src/test/java/org/json/junit/data/MyPublicClass.java index e483d4c..1f30386 100644 --- a/src/test/java/org/json/junit/MyPublicClass.java +++ b/src/test/java/org/json/junit/data/MyPublicClass.java @@ -1,4 +1,4 @@ -package org.json.junit; +package org.json.junit.data; /** * Need a class with some public data members for testing diff --git a/src/test/java/org/json/junit/StringsResourceBundle.java b/src/test/java/org/json/junit/data/StringsResourceBundle.java similarity index 93% rename from src/test/java/org/json/junit/StringsResourceBundle.java rename to src/test/java/org/json/junit/data/StringsResourceBundle.java index d04aeaf..4479350 100644 --- a/src/test/java/org/json/junit/StringsResourceBundle.java +++ b/src/test/java/org/json/junit/data/StringsResourceBundle.java @@ -1,4 +1,4 @@ -package org.json.junit; +package org.json.junit.data; import java.util.*; From 49117f33dcf5ff5800a244799bc5fd4fd3f1e2ee Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sun, 9 Jul 2017 17:35:46 -0400 Subject: [PATCH 324/451] Adds new tests for testing bean->JSONObject mapping --- .../java/org/json/junit/JSONObjectTest.java | 80 ++++++++++++++++++ .../java/org/json/junit/data/GenericBean.java | 72 +++++++++++++++++ .../org/json/junit/data/GenericBeanInt.java | 29 +++++++ .../java/org/json/junit/data/Singleton.java | 81 +++++++++++++++++++ .../org/json/junit/data/SingletonEnum.java | 49 +++++++++++ .../java/org/json/junit/data/WeirdList.java | 45 +++++++++++ 6 files changed, 356 insertions(+) create mode 100644 src/test/java/org/json/junit/data/GenericBean.java create mode 100644 src/test/java/org/json/junit/data/GenericBeanInt.java create mode 100644 src/test/java/org/json/junit/data/Singleton.java create mode 100644 src/test/java/org/json/junit/data/SingletonEnum.java create mode 100644 src/test/java/org/json/junit/data/WeirdList.java diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 372e362..ae6a8b6 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -3,6 +3,7 @@ package org.json.junit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -32,6 +33,8 @@ import org.json.JSONPointerException; import org.json.XML; import org.json.junit.data.BrokenToString; import org.json.junit.data.Fraction; +import org.json.junit.data.GenericBean; +import org.json.junit.data.GenericBeanInt; import org.json.junit.data.MyBean; import org.json.junit.data.MyBigNumberBean; import org.json.junit.data.MyEnum; @@ -40,6 +43,9 @@ import org.json.junit.data.MyJsonString; import org.json.junit.data.MyNumber; import org.json.junit.data.MyNumberContainer; import org.json.junit.data.MyPublicClass; +import org.json.junit.data.Singleton; +import org.json.junit.data.SingletonEnum; +import org.json.junit.data.WeirdList; import org.junit.Test; import com.jayway.jsonpath.Configuration; @@ -2583,4 +2589,78 @@ public class JSONObjectTest { assertTrue("Removing a key should succeed", map.remove("key3") != null); assertTrue("Map should have 2 elements", map.size() == 2); } + + @Test + public void testSingletonBean() { + final JSONObject jo = new JSONObject(Singleton.getInstance()); + assertEquals(jo.keySet().toString(), 1, jo.length()); + assertEquals(0, jo.get("someInt")); + assertEquals(null, jo.opt("someString")); + + // Update the singleton values + Singleton.getInstance().setSomeInt(42); + Singleton.getInstance().setSomeString("Something"); + final JSONObject jo2 = new JSONObject(Singleton.getInstance()); + assertEquals(2, jo2.length()); + assertEquals(42, jo2.get("someInt")); + assertEquals("Something", jo2.get("someString")); + + // ensure our original jo hasn't changed. + assertEquals(0, jo.get("someInt")); + assertEquals(null, jo.opt("someString")); + } + @Test + public void testSingletonEnumBean() { + final JSONObject jo = new JSONObject(SingletonEnum.getInstance()); + assertEquals(jo.keySet().toString(), 1, jo.length()); + assertEquals(0, jo.get("someInt")); + assertEquals(null, jo.opt("someString")); + + // Update the singleton values + SingletonEnum.getInstance().setSomeInt(42); + SingletonEnum.getInstance().setSomeString("Something"); + final JSONObject jo2 = new JSONObject(SingletonEnum.getInstance()); + assertEquals(2, jo2.length()); + assertEquals(42, jo2.get("someInt")); + assertEquals("Something", jo2.get("someString")); + + // ensure our original jo hasn't changed. + assertEquals(0, jo.get("someInt")); + assertEquals(null, jo.opt("someString")); + } + + @Test + public void testGenericBean() { + GenericBean bean = new GenericBean<>(42); + final JSONObject jo = new JSONObject(bean); + assertEquals(jo.keySet().toString(), 8, jo.length()); + assertEquals(42, jo.get("genericValue")); + assertEquals("Expected the getter to only be called once", + 1, bean.genericGetCounter); + assertEquals(0, bean.genericSetCounter); + } + + @Test + public void testGenericIntBean() { + GenericBeanInt bean = new GenericBeanInt(42); + final JSONObject jo = new JSONObject(bean); + assertEquals(jo.keySet().toString(), 9, jo.length()); + assertEquals(42, jo.get("genericValue")); + assertEquals("Expected the getter to only be called once", + 1, bean.genericGetCounter); + assertEquals(0, bean.genericSetCounter); + } + + @Test + public void testWierdListBean() { + WeirdList bean = new WeirdList(42, 43, 44); + final JSONObject jo = new JSONObject(bean); + // get() should have a key of 0 length + // get(int) should be ignored base on parameter count + // getInt(int) should also be ignored based on parameter count + // add(Integer) should be ignore as it doesn't start with get/is and also has a parameter + // getALL should be mapped + assertEquals("Expected 1 key to mapped "+jo.keySet().toString(), 1, jo.length()); + assertNotNull(jo.get("ALL")); + } } diff --git a/src/test/java/org/json/junit/data/GenericBean.java b/src/test/java/org/json/junit/data/GenericBean.java new file mode 100644 index 0000000..17f6def --- /dev/null +++ b/src/test/java/org/json/junit/data/GenericBean.java @@ -0,0 +1,72 @@ +package org.json.junit.data; + +import java.io.StringReader; + +/** + * + * @author John Aylward + * + * @param + * generic number value + */ +public class GenericBean> implements MyBean { + public GenericBean(T genericValue) { + super(); + this.genericValue = genericValue; + } + + /** */ + private T genericValue; + /** to be used by the calling test to see how often the getter is called */ + public int genericGetCounter; + /** to be used by the calling test to see how often the setter is called */ + public int genericSetCounter; + + /** @return the genericValue */ + public T getGenericValue() { + this.genericGetCounter++; + return this.genericValue; + } + + /** sets the generic value */ + public void setGenericValue(T genericValue) { + this.genericSetCounter++; + this.genericValue = genericValue; + } + + @Override + public Integer getIntKey() { + return Integer.valueOf(42); + } + + @Override + public Double getDoubleKey() { + return Double.valueOf(4.2); + } + + @Override + public String getStringKey() { + return "MyString Key"; + } + + @Override + public String getEscapeStringKey() { + return "\"My String with \"s"; + } + + @Override + public Boolean isTrueKey() { + return Boolean.TRUE; + } + + @Override + public Boolean isFalseKey() { + return Boolean.FALSE; + } + + @Override + public StringReader getStringReaderKey() { + return new StringReader("Some String Value in a reader"); + } + +} diff --git a/src/test/java/org/json/junit/data/GenericBeanInt.java b/src/test/java/org/json/junit/data/GenericBeanInt.java new file mode 100644 index 0000000..70dfb28 --- /dev/null +++ b/src/test/java/org/json/junit/data/GenericBeanInt.java @@ -0,0 +1,29 @@ +/** + * + */ +package org.json.junit.data; + +/** + * @author john + * + */ +public class GenericBeanInt extends GenericBean { + /** */ + final char a = 'A'; + + /** return the a */ + public char getA() { + return a; + } + + /** return false. should not be beanable */ + public boolean getable() { + return false; + } + + /** */ + public GenericBeanInt(Integer genericValue) { + super(genericValue); + } + +} diff --git a/src/test/java/org/json/junit/data/Singleton.java b/src/test/java/org/json/junit/data/Singleton.java new file mode 100644 index 0000000..55b37f9 --- /dev/null +++ b/src/test/java/org/json/junit/data/Singleton.java @@ -0,0 +1,81 @@ +package org.json.junit.data; + +/** + * Sample singleton for use with bean testing. + * + * @author John Aylward + * + */ +public final class Singleton { + /** */ + private int someInt; + /** */ + private String someString; + /** single instance. */ + private static final Singleton INSTANCE = new Singleton(); + + /** @return the singleton instance. */ + public static final Singleton getInstance() { + return INSTANCE; + } + + /** */ + private Singleton() { + if (INSTANCE != null) { + throw new IllegalStateException("Already instantiated"); + } + } + + @Override + protected Object clone() throws CloneNotSupportedException { + return INSTANCE; + } + + /** @return someInt */ + public int getSomeInt() { + return someInt; + } + + /** sets someInt */ + public void setSomeInt(int someInt) { + this.someInt = someInt; + } + + /** @return someString */ + public String getSomeString() { + return someString; + } + + /** sets someString */ + public void setSomeString(String someString) { + this.someString = someString; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + someInt; + result = prime * result + ((someString == null) ? 0 : someString.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Singleton other = (Singleton) obj; + if (someInt != other.someInt) + return false; + if (someString == null) { + if (other.someString != null) + return false; + } else if (!someString.equals(other.someString)) + return false; + return true; + } +} diff --git a/src/test/java/org/json/junit/data/SingletonEnum.java b/src/test/java/org/json/junit/data/SingletonEnum.java new file mode 100644 index 0000000..55c0e6c --- /dev/null +++ b/src/test/java/org/json/junit/data/SingletonEnum.java @@ -0,0 +1,49 @@ +package org.json.junit.data; + +/** + * Sample singleton done as an Enum for use with bean testing. + * + * @author John Aylward + * + */ +public enum SingletonEnum { + INSTANCE; + /** */ + private int someInt; + /** */ + private String someString; + + /** single instance. */ + + /** + * @return the singleton instance. I a real application, I'd hope no one did + * this to an enum singleton. + */ + public static final SingletonEnum getInstance() { + return INSTANCE; + } + + /** */ + private SingletonEnum() { + } + + /** @return someInt */ + public int getSomeInt() { + return someInt; + } + + /** sets someInt */ + public void setSomeInt(int someInt) { + this.someInt = someInt; + } + + /** @return someString */ + public String getSomeString() { + return someString; + } + + /** sets someString */ + public void setSomeString(String someString) { + this.someString = someString; + } +} diff --git a/src/test/java/org/json/junit/data/WeirdList.java b/src/test/java/org/json/junit/data/WeirdList.java new file mode 100644 index 0000000..315c144 --- /dev/null +++ b/src/test/java/org/json/junit/data/WeirdList.java @@ -0,0 +1,45 @@ +/** + * + */ +package org.json.junit.data; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @author John Aylward + */ +public class WeirdList { + /** */ + private final List list = new ArrayList<>(); + + public WeirdList(Integer... vals) { + this.list.addAll(Arrays.asList(vals)); + } + + /** gets a copy of the list */ + public List get() { + return new ArrayList<>(this.list); + } + + /** gets a copy of the list */ + public List getALL() { + return new ArrayList<>(this.list); + } + + /** get an index */ + public Integer get(int i) { + return this.list.get(i); + } + + /** get an index */ + public int getInt(int i) { + return this.list.get(i); + } + + /** adds a new value to the end of the list */ + public void add(Integer value) { + this.list.add(value); + } +} \ No newline at end of file From a129ebe8e47df8121fdc3f37801610f682d57ae5 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sun, 9 Jul 2017 17:36:36 -0400 Subject: [PATCH 325/451] Adds check for resources opened by our bean mapping --- JSONObject.java | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index ef2413a..171f293 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1,5 +1,7 @@ package org.json; +import java.io.Closeable; + /* Copyright (c) 2002 JSON.org @@ -1412,8 +1414,10 @@ public class JSONObject { .getDeclaredMethods(); for (final Method method : methods) { final int modifiers = method.getModifiers(); - if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) - && method.getParameterTypes().length == 0 && !method.isBridge() + if (Modifier.isPublic(modifiers) + && !Modifier.isStatic(modifiers) + && method.getParameterTypes().length == 0 + && !method.isBridge() && method.getReturnType() != Void.TYPE ) { final String name = method.getName(); String key; @@ -1427,7 +1431,8 @@ public class JSONObject { } else { continue; } - if (key.length() > 0 && Character.isUpperCase(key.charAt(0))) { + if (key.length() > 0 + && Character.isUpperCase(key.charAt(0))) { if (key.length() == 1) { key = key.toLowerCase(Locale.ROOT); } else if (!Character.isUpperCase(key.charAt(1))) { @@ -1439,6 +1444,14 @@ public class JSONObject { final Object result = method.invoke(bean); if (result != null) { this.map.put(key, wrap(result)); + // we don't use the result anywhere outside of wrap + // if it's a resource we should be sure to close it after calling toString + if(result instanceof Closeable) { + try { + ((Closeable)result).close(); + } catch (IOException ignore) { + } + } } } catch (IllegalAccessException ignore) { } catch (IllegalArgumentException ignore) { From 7bc8f4102360c6d143f6ea826863c4840b3b1f07 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sun, 9 Jul 2017 18:07:11 -0400 Subject: [PATCH 326/451] Add override of the generic getter to generate a Bridge method. --- src/test/java/org/json/junit/data/GenericBeanInt.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/test/java/org/json/junit/data/GenericBeanInt.java b/src/test/java/org/json/junit/data/GenericBeanInt.java index 70dfb28..8549f19 100644 --- a/src/test/java/org/json/junit/data/GenericBeanInt.java +++ b/src/test/java/org/json/junit/data/GenericBeanInt.java @@ -26,4 +26,10 @@ public class GenericBeanInt extends GenericBean { super(genericValue); } + /** override to generate a bridge method */ + @Override + public Integer getGenericValue() { + return super.getGenericValue(); + } + } From e94783f91b5423d728a11c3323461481883bf209 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sun, 9 Jul 2017 18:19:27 -0400 Subject: [PATCH 327/451] Updates javadocs --- .../java/org/json/junit/JSONObjectTest.java | 19 ++++++++++- .../java/org/json/junit/data/GenericBean.java | 9 +++++- .../org/json/junit/data/GenericBeanInt.java | 15 ++++++--- .../java/org/json/junit/data/Singleton.java | 14 ++++++-- .../org/json/junit/data/SingletonEnum.java | 17 ++++++++-- .../java/org/json/junit/data/WeirdList.java | 32 ++++++++++++++++--- 6 files changed, 91 insertions(+), 15 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index ae6a8b6..190f32a 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -2590,6 +2590,9 @@ public class JSONObjectTest { assertTrue("Map should have 2 elements", map.size() == 2); } + /** + * test that validates a singleton can be serialized as a bean. + */ @Test public void testSingletonBean() { final JSONObject jo = new JSONObject(Singleton.getInstance()); @@ -2609,6 +2612,10 @@ public class JSONObjectTest { assertEquals(0, jo.get("someInt")); assertEquals(null, jo.opt("someString")); } + + /** + * test that validates a singleton can be serialized as a bean. + */ @Test public void testSingletonEnumBean() { final JSONObject jo = new JSONObject(SingletonEnum.getInstance()); @@ -2629,6 +2636,9 @@ public class JSONObjectTest { assertEquals(null, jo.opt("someString")); } + /** + * Test to validate that a generic class can be serialized as a bean. + */ @Test public void testGenericBean() { GenericBean bean = new GenericBean<>(42); @@ -2640,6 +2650,9 @@ public class JSONObjectTest { assertEquals(0, bean.genericSetCounter); } + /** + * Test to validate that a generic class can be serialized as a bean. + */ @Test public void testGenericIntBean() { GenericBeanInt bean = new GenericBeanInt(42); @@ -2651,6 +2664,9 @@ public class JSONObjectTest { assertEquals(0, bean.genericSetCounter); } + /** + * Test to verify key limitations in the JSONObject bean serializer. + */ @Test public void testWierdListBean() { WeirdList bean = new WeirdList(42, 43, 44); @@ -2660,7 +2676,8 @@ public class JSONObjectTest { // getInt(int) should also be ignored based on parameter count // add(Integer) should be ignore as it doesn't start with get/is and also has a parameter // getALL should be mapped - assertEquals("Expected 1 key to mapped "+jo.keySet().toString(), 1, jo.length()); + assertEquals("Expected 1 key to be mapped. Instead found: "+jo.keySet().toString(), + 1, jo.length()); assertNotNull(jo.get("ALL")); } } diff --git a/src/test/java/org/json/junit/data/GenericBean.java b/src/test/java/org/json/junit/data/GenericBean.java index 17f6def..4740030 100644 --- a/src/test/java/org/json/junit/data/GenericBean.java +++ b/src/test/java/org/json/junit/data/GenericBean.java @@ -10,6 +10,10 @@ import java.io.StringReader; * generic number value */ public class GenericBean> implements MyBean { + /** + * @param genericValue + * value to initiate with + */ public GenericBean(T genericValue) { super(); this.genericValue = genericValue; @@ -28,7 +32,10 @@ public class GenericBean> implements MyBean { return this.genericValue; } - /** sets the generic value */ + /** + * @param genericValue + * generic value to set + */ public void setGenericValue(T genericValue) { this.genericSetCounter++; this.genericValue = genericValue; diff --git a/src/test/java/org/json/junit/data/GenericBeanInt.java b/src/test/java/org/json/junit/data/GenericBeanInt.java index 8549f19..8f0248d 100644 --- a/src/test/java/org/json/junit/data/GenericBeanInt.java +++ b/src/test/java/org/json/junit/data/GenericBeanInt.java @@ -11,17 +11,24 @@ public class GenericBeanInt extends GenericBean { /** */ final char a = 'A'; - /** return the a */ + /** @return the a */ public char getA() { return a; } - - /** return false. should not be beanable */ + + /** + * Should not be beanable + * + * @return false + */ public boolean getable() { return false; } - /** */ + /** + * @param genericValue + * the value to initiate with. + */ public GenericBeanInt(Integer genericValue) { super(genericValue); } diff --git a/src/test/java/org/json/junit/data/Singleton.java b/src/test/java/org/json/junit/data/Singleton.java index 55b37f9..36a9824 100644 --- a/src/test/java/org/json/junit/data/Singleton.java +++ b/src/test/java/org/json/junit/data/Singleton.java @@ -36,7 +36,12 @@ public final class Singleton { return someInt; } - /** sets someInt */ + /** + * sets someInt. + * + * @param someInt + * the someInt to set + */ public void setSomeInt(int someInt) { this.someInt = someInt; } @@ -46,7 +51,12 @@ public final class Singleton { return someString; } - /** sets someString */ + /** + * sets someString. + * + * @param someString + * the someString to set + */ public void setSomeString(String someString) { this.someString = someString; } diff --git a/src/test/java/org/json/junit/data/SingletonEnum.java b/src/test/java/org/json/junit/data/SingletonEnum.java index 55c0e6c..8147cc6 100644 --- a/src/test/java/org/json/junit/data/SingletonEnum.java +++ b/src/test/java/org/json/junit/data/SingletonEnum.java @@ -7,6 +7,9 @@ package org.json.junit.data; * */ public enum SingletonEnum { + /** + * the singleton instance. + */ INSTANCE; /** */ private int someInt; @@ -32,7 +35,12 @@ public enum SingletonEnum { return someInt; } - /** sets someInt */ + /** + * sets someInt. + * + * @param someInt + * the someInt to set + */ public void setSomeInt(int someInt) { this.someInt = someInt; } @@ -42,7 +50,12 @@ public enum SingletonEnum { return someString; } - /** sets someString */ + /** + * sets someString. + * + * @param someString + * the someString to set + */ public void setSomeString(String someString) { this.someString = someString; } diff --git a/src/test/java/org/json/junit/data/WeirdList.java b/src/test/java/org/json/junit/data/WeirdList.java index 315c144..77cd17f 100644 --- a/src/test/java/org/json/junit/data/WeirdList.java +++ b/src/test/java/org/json/junit/data/WeirdList.java @@ -14,31 +14,53 @@ public class WeirdList { /** */ private final List list = new ArrayList<>(); + /** + * @param vals + */ public WeirdList(Integer... vals) { this.list.addAll(Arrays.asList(vals)); } - /** gets a copy of the list */ + /** + * @return a copy of the list + */ public List get() { return new ArrayList<>(this.list); } - /** gets a copy of the list */ + /** + * @return a copy of the list + */ public List getALL() { return new ArrayList<>(this.list); } - /** get an index */ + /** + * get a value at an index. + * + * @param i + * index to get + * @return the value at the index + */ public Integer get(int i) { return this.list.get(i); } - /** get an index */ + /** + * get a value at an index. + * + * @param i + * index to get + * @return the value at the index + */ public int getInt(int i) { return this.list.get(i); } - /** adds a new value to the end of the list */ + /** + * @param value + * new value to add to the end of the list + */ public void add(Integer value) { this.list.add(value); } From 5c80c9157d86b5f22bf5b905b23a4039d37de348 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sun, 9 Jul 2017 18:47:09 -0400 Subject: [PATCH 328/451] fixes malformed javadoc --- JSONArray.java | 2 +- JSONObject.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index a402d67..197ad97 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1230,7 +1230,7 @@ public class JSONArray implements Iterable { * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. * - * @param The JSON pointer + * @param jsonPointer The JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ diff --git a/JSONObject.java b/JSONObject.java index 171f293..800e589 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1704,7 +1704,7 @@ public class JSONObject { * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. * - * @param The JSON pointer + * @param jsonPointer The JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ From 4dbc5ef8036017c05c107d5e62be322213726930 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sun, 9 Jul 2017 18:48:40 -0400 Subject: [PATCH 329/451] fixes malformed javadoc --- XML.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/XML.java b/XML.java index 4dd9a2c..36f44c8 100644 --- a/XML.java +++ b/XML.java @@ -423,7 +423,7 @@ public class XML { } /** - * This method is the same as {@link JSONObject.stringToValue(String)} + * This method is the same as {@link JSONObject#stringToValue(String)} * except that this also tries to unescape String values. * * @param string String to convert From 38d11227ee5608536b78af410e50d4af293626a8 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sun, 9 Jul 2017 19:05:00 -0400 Subject: [PATCH 330/451] Adds exception tests --- .../java/org/json/junit/JSONObjectTest.java | 14 ++++ .../org/json/junit/data/ExceptionalBean.java | 69 +++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 src/test/java/org/json/junit/data/ExceptionalBean.java diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 190f32a..8e61c53 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -32,6 +32,7 @@ import org.json.JSONObject; import org.json.JSONPointerException; import org.json.XML; import org.json.junit.data.BrokenToString; +import org.json.junit.data.ExceptionalBean; import org.json.junit.data.Fraction; import org.json.junit.data.GenericBean; import org.json.junit.data.GenericBeanInt; @@ -2680,4 +2681,17 @@ public class JSONObjectTest { 1, jo.length()); assertNotNull(jo.get("ALL")); } + + /** + * Tests the exception portions of populateMap. + */ + @Test + public void testExceptionalBean() { + ExceptionalBean bean = new ExceptionalBean(); + final JSONObject jo = new JSONObject(bean); + assertEquals("Expected 1 key to be mapped. Instead found: "+jo.keySet().toString(), + 1, jo.length()); + assertTrue(jo.get("closeable") instanceof JSONObject); + assertTrue(jo.getJSONObject("closeable").has("string")); + } } diff --git a/src/test/java/org/json/junit/data/ExceptionalBean.java b/src/test/java/org/json/junit/data/ExceptionalBean.java new file mode 100644 index 0000000..74d78a7 --- /dev/null +++ b/src/test/java/org/json/junit/data/ExceptionalBean.java @@ -0,0 +1,69 @@ +/** + * + */ +package org.json.junit.data; + +import java.io.Closeable; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; + +import org.json.JSONObject; + +/** + * Object for testing the exception handling in {@link JSONObject#populateMap}. + * + * @author John Aylward + */ +public class ExceptionalBean { + /** + * @return a closeable. + */ + public Closeable getCloseable() { + // anonymous inner class did not work... + return new MyCloseable(); + } + + /** + * @return Nothing really. Just can't be void. + * @throws IllegalAccessException + * always thrown + */ + public int getIllegalAccessException() throws IllegalAccessException { + throw new IllegalAccessException("Yup, it's illegal"); + } + + /** + * @return Nothing really. Just can't be void. + * @throws IllegalArgumentException + * always thrown + */ + public int getIllegalArgumentException() throws IllegalArgumentException { + throw new IllegalArgumentException("Yup, it's illegal"); + } + + /** + * @return Nothing really. Just can't be void. + * @throws InvocationTargetException + * always thrown + */ + public int getInvocationTargetException() throws InvocationTargetException { + throw new InvocationTargetException(new Exception("Yup, it's illegal")); + } + + /** My closeable class. */ + public static final class MyCloseable implements Closeable { + + /** + * @return a string + */ + @SuppressWarnings("unused") + public String getString() { + return "Yup, it's closeable"; + } + + @Override + public void close() throws IOException { + throw new IOException("Closing is too hard!"); + } + } +} From 6f238a369812246c33e841684904f423709fff8d Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sat, 15 Jul 2017 12:17:27 -0400 Subject: [PATCH 331/451] Update javadoc according to issue #356. --- JSONArray.java | 48 +++++++++++++++++++++++++++++++++++++++--------- JSONObject.java | 40 +++++++++++++++++++++++++++++++++------- 2 files changed, 72 insertions(+), 16 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index a402d67..8775a19 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1230,7 +1230,7 @@ public class JSONArray implements Iterable { * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. * - * @param The JSON pointer + * @param jsonPointer The JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ @@ -1323,8 +1323,9 @@ public class JSONArray implements Iterable { * whitespace is added. If it is not possible to produce a syntactically * correct JSON text then null will be returned instead. This could occur if * the array contains an invalid number. - *

+ *

* Warning: This method assumes that the data structure is acyclical. + * * * @return a printable, displayable, transmittable representation of the * array. @@ -1339,9 +1340,24 @@ public class JSONArray implements Iterable { } /** - * Make a pretty-printed JSON text of this JSONArray. Warning: This method - * assumes that the data structure is acyclical. - * + * Make a pretty-printed JSON text of this JSONArray. + * + *

If indentFactor > 0 and the {@link JSONArray} has only + * one element, then the array will be output on a single line: + *

{@code [1]}
+ * + *

If an array has 2 or more elements, then it will be output across + * multiple lines:

{@code
+     * [
+     * 1,
+     * "value 2",
+     * 3
+     * ]
+     * }
+ *

+ * 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, transmittable representation of the @@ -1360,8 +1376,9 @@ public class JSONArray implements Iterable { /** * Write the contents of the JSONArray as JSON text to a writer. For * compactness, no whitespace is added. - *

+ *

* Warning: This method assumes that the data structure is acyclical. + * * * @return The writer. * @throws JSONException @@ -1371,10 +1388,23 @@ public class JSONArray implements Iterable { } /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - *

+ * Write the contents of the JSONArray as JSON text to a writer. + * + *

If indentFactor > 0 and the {@link JSONArray} has only + * one element, then the array will be output on a single line: + *

{@code [1]}
+ * + *

If an array has 2 or more elements, then it will be output across + * multiple lines:

{@code
+     * [
+     * 1,
+     * "value 2",
+     * 3
+     * ]
+     * }
+ *

* Warning: This method assumes that the data structure is acyclical. + * * * @param writer * Writes the serialized JSON diff --git a/JSONObject.java b/JSONObject.java index 8ad7864..46ed869 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1676,7 +1676,7 @@ public class JSONObject { * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. * - * @param The JSON pointer + * @param jsonPointer The JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ @@ -2002,9 +2002,10 @@ public class JSONObject { * Make a JSON text of this JSONObject. For compactness, no whitespace is * added. If this would not result in a syntactically correct JSON text, * then null will be returned instead. - *

+ *

* Warning: This method assumes that the data structure is acyclical. - * + * + * * @return a printable, displayable, portable, transmittable representation * of the object, beginning with { (left * brace) and ending with } (right @@ -2021,8 +2022,20 @@ public class JSONObject { /** * Make a pretty-printed JSON text of this JSONObject. - *

+ * + *

If indentFactor > 0 and the {@link JSONObject} + * has only one key, then the object will be output on a single line: + *

{@code {"key": 1}}
+ * + *

If an object has 2 or more keys, then it will be output across + * multiple lines:

{
+     *  "key1": 1,
+     *  "key2": "value 2",
+     *  "key3": 3
+     * }
+ *

* Warning: This method assumes that the data structure is acyclical. + * * * @param indentFactor * The number of spaces to add to each level of indentation. @@ -2172,9 +2185,10 @@ public class JSONObject { /** * Write the contents of the JSONObject as JSON text to a writer. For * compactness, no whitespace is added. - *

+ *

* Warning: This method assumes that the data structure is acyclical. - * + * + * * @return The writer. * @throws JSONException */ @@ -2238,8 +2252,20 @@ public class JSONObject { /** * Write the contents of the JSONObject as JSON text to a writer. - *

+ * + *

If indentFactor > 0 and the {@link JSONObject} + * has only one key, then the object will be output on a single line: + *

{@code {"key": 1}}
+ * + *

If an object has 2 or more keys, then it will be output across + * multiple lines:

{
+     *  "key1": 1,
+     *  "key2": "value 2",
+     *  "key3": 3
+     * }
+ *

* Warning: This method assumes that the data structure is acyclical. + * * * @param writer * Writes the serialized JSON From aa562b5ec3d87f4f4f0bff8ac9fb4552c8d271f8 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sat, 15 Jul 2017 12:19:02 -0400 Subject: [PATCH 332/451] Update test for issue https://github.com/stleary/JSON-java/issues/356 --- src/test/java/org/json/junit/JSONObjectTest.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index cabd41c..0e6a691 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1622,10 +1622,13 @@ public class JSONObjectTest { " ]\n" + "}"; JSONObject jsonObject = new JSONObject(jsonObject0Str); - assertEquals(jsonObject0Str, jsonObject.toString()); - assertEquals(jsonObject0Str, jsonObject.toString(0)); - assertEquals(jsonObject1Str, jsonObject.toString(1)); - assertEquals(jsonObject4Str, jsonObject.toString(4)); + assertEquals("toString()",jsonObject0Str, jsonObject.toString()); + assertEquals("toString(0)",jsonObject0Str, jsonObject.toString(0)); + assertEquals("toString(1)",jsonObject1Str, jsonObject.toString(1)); + assertEquals("toString(4)",jsonObject4Str, jsonObject.toString(4)); + + JSONObject jo = new JSONObject().put("TABLE", new JSONObject().put("yhoo", new JSONObject())); + assertEquals("toString(2)","{\"TABLE\": {\"yhoo\": {}}}", jo.toString(2)); } /** From f2f6ad3b1f9324439489b5454811108faa3a3fd2 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 19 Jul 2017 20:34:59 -0400 Subject: [PATCH 333/451] * Fixes Gradle config so tests are only run once * Adds missing test to the test suite --- build.gradle | 5 ++++- src/test/java/org/json/junit/JunitTestSuite.java | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 58259f9..43656ae 100644 --- a/build.gradle +++ b/build.gradle @@ -28,7 +28,10 @@ dependencies { // testCompile files('./JSON-Java.jar') } -test { finalizedBy jacocoTestReport } +test { + include "org/json/junit/JunitTestSuite.class" + finalizedBy jacocoTestReport +} jacocoTestReport{ additionalSourceDirs = files(sourceSets.main.allJava.srcDirs) reports { diff --git a/src/test/java/org/json/junit/JunitTestSuite.java b/src/test/java/org/json/junit/JunitTestSuite.java index 36bec60..9c9a325 100644 --- a/src/test/java/org/json/junit/JunitTestSuite.java +++ b/src/test/java/org/json/junit/JunitTestSuite.java @@ -17,7 +17,8 @@ import org.junit.runners.Suite; JSONArrayTest.class, EnumTest.class, JSONPointerTest.class, - JSONStringTest.class + JSONStringTest.class, + JSONTokenerTest.class }) public class JunitTestSuite { } From fefd616d73c063de3ffb4749e6b46b363eea3e93 Mon Sep 17 00:00:00 2001 From: Miguel Date: Wed, 9 Aug 2017 21:51:46 -0400 Subject: [PATCH 334/451] Unit tests for JSONTokener --- build.gradle | 1 + .../java/org/json/junit/JSONObjectTest.java | 170 ++++++++++++++++++ 2 files changed, 171 insertions(+) diff --git a/build.gradle b/build.gradle index 43656ae..53fbdb3 100644 --- a/build.gradle +++ b/build.gradle @@ -22,6 +22,7 @@ dependencies { testCompile group: 'junit', name: 'junit', version: '4.+' testCompile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.1.0' testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' + testCompile group: 'slf4j.org', name: 'slf4j', version: '1.6.1' // Uncomment if you are testing against a JSON-Java release // testCompile 'org.json:json:20160212' // Uncomment if you have copied a local JSON-Java jar file into this project diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 1231ec9..35cf493 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1976,6 +1976,176 @@ public class JSONObjectTest { } catch (JSONException e) { assertTrue("", true); } + try { + // test exception message when including a duplicate key (level 0) + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr03\":\"value-04\"\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Expecting an expection message", + "Duplicate key \"attr03\" at 90 [character 13 line 5]", + e.getMessage()); + } + try { + // test exception message when including a duplicate key (level 0) holding an object + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr03\": {" + +" \"attr04-01\":\"value-04-01\",n" + +" \"attr04-02\":\"value-04-02\",n" + +" \"attr04-03\":\"value-04-03\"n" + + " }\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Expecting an expection message", + "Duplicate key \"attr03\" at 90 [character 13 line 5]", + e.getMessage()); + } + try { + // test exception message when including a duplicate key (level 0) holding an array + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr03\": [\n" + +" {" + +" \"attr04-01\":\"value-04-01\",n" + +" \"attr04-02\":\"value-04-02\",n" + +" \"attr04-03\":\"value-04-03\"n" + +" }\n" + + " ]\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Expecting an expection message", + "Duplicate key \"attr03\" at 90 [character 13 line 5]", + e.getMessage()); + } + try { + // test exception message when including a duplicate key (level 1) + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr04\": {\n" + +" \"attr04-01\":\"value04-01\",\n" + +" \"attr04-02\":\"value04-02\",\n" + +" \"attr04-03\":\"value04-03\",\n" + +" \"attr04-03\":\"value04-04\"\n" + + " }\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Expecting an expection message", + "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + e.getMessage()); + } + try { + // test exception message when including a duplicate key (level 1) holding an object + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr04\": {\n" + +" \"attr04-01\":\"value04-01\",\n" + +" \"attr04-02\":\"value04-02\",\n" + +" \"attr04-03\":\"value04-03\",\n" + +" \"attr04-03\": {\n" + +" \"attr04-04-01\":\"value04-04-01\",\n" + +" \"attr04-04-02\":\"value04-04-02\",\n" + +" \"attr04-04-03\":\"value04-04-03\",\n" + +" }\n" + +" }\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Expecting an expection message", + "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + e.getMessage()); + } + try { + // test exception message when including a duplicate key (level 1) holding an array + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr04\": {\n" + +" \"attr04-01\":\"value04-01\",\n" + +" \"attr04-02\":\"value04-02\",\n" + +" \"attr04-03\":\"value04-03\",\n" + +" \"attr04-03\": [\n" + +" {\n" + +" \"attr04-04-01\":\"value04-04-01\",\n" + +" \"attr04-04-02\":\"value04-04-02\",\n" + +" \"attr04-04-03\":\"value04-04-03\",\n" + +" }\n" + +" ]\n" + +" }\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Expecting an expection message", + "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + e.getMessage()); + } + try { + // test exception message when including a duplicate key in object (level 0) within an array + String str = "[\n" + +" {\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\"\n" + +" },\n" + +" {\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr01\":\"value-02\"\n" + +" }\n" + + "]"; + new JSONArray(str); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Expecting an expection message", + "Duplicate key \"attr01\" at 124 [character 17 line 8]", + e.getMessage()); + } + try { + // test exception message when including a duplicate key in object (level 1) within an array + String str = "[\n" + +" {\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\": {\n" + +" \"attr02-01\":\"value-02-01\",\n" + +" \"attr02-02\":\"value-02-02\"\n" + +" }\n" + +" },\n" + +" {\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\": {\n" + +" \"attr02-01\":\"value-02-01\",\n" + +" \"attr02-01\":\"value-02-02\"\n" + +" }\n" + +" }\n" + + "]"; + System.out.println(str); + new JSONArray(str); + fail("Expected an exception"); + } catch (JSONException e) { + assertEquals("Expecting an expection message", + "Duplicate key \"attr02-01\" at 269 [character 24 line 13]", + e.getMessage()); + } } /** From 7fed0230806031033eaeda8ed1a2851103b91fee Mon Sep 17 00:00:00 2001 From: Miguel Date: Wed, 9 Aug 2017 21:52:36 -0400 Subject: [PATCH 335/451] Update to include error location when creating JSONObject from string/text --- JSONObject.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/JSONObject.java b/JSONObject.java index fcc0c91..9d5fc87 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -231,7 +231,21 @@ public class JSONObject { if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } - this.putOnce(key, x.nextValue()); + + // Replace: this.putOnce(key, x.nextValue()); + // Use syntaxError(..) to include error location + + if (key != null) { + // Check if key exists + if (this.opt(key) != null) { + throw x.syntaxError("Duplicate key \"" + key + "\""); + } + // Only add value if non-null + Object value = x.nextValue(); + if (value!=null) { + this.put(key, value); + } + } // Pairs are separated by ','. From 1acb18091a7006fd8a113c474a912cfd4cc6a375 Mon Sep 17 00:00:00 2001 From: Miguel Date: Wed, 9 Aug 2017 21:57:10 -0400 Subject: [PATCH 336/451] Remove System.out.println --- src/test/java/org/json/junit/JSONObjectTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 35cf493..6470ebb 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -2138,7 +2138,6 @@ public class JSONObjectTest { +" }\n" +" }\n" + "]"; - System.out.println(str); new JSONArray(str); fail("Expected an exception"); } catch (JSONException e) { From df466db7b9630e689813dd82de5f512ca0713273 Mon Sep 17 00:00:00 2001 From: Miguel Date: Wed, 9 Aug 2017 21:59:08 -0400 Subject: [PATCH 337/451] Replacing tabs with 4 spaces --- .../java/org/json/junit/JSONObjectTest.java | 290 +++++++++--------- 1 file changed, 145 insertions(+), 145 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 6470ebb..2dcebe4 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1977,173 +1977,173 @@ public class JSONObjectTest { assertTrue("", true); } try { - // test exception message when including a duplicate key (level 0) - String str = "{\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr02\":\"value-02\",\n" - +" \"attr03\":\"value-03\",\n" - +" \"attr03\":\"value-04\"\n" - + "}"; - new JSONObject(str); - fail("Expected an exception"); + // test exception message when including a duplicate key (level 0) + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr03\":\"value-04\"\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 90 [character 13 line 5]", - e.getMessage()); + assertEquals("Expecting an expection message", + "Duplicate key \"attr03\" at 90 [character 13 line 5]", + e.getMessage()); } try { - // test exception message when including a duplicate key (level 0) holding an object - String str = "{\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr02\":\"value-02\",\n" - +" \"attr03\":\"value-03\",\n" - +" \"attr03\": {" - +" \"attr04-01\":\"value-04-01\",n" - +" \"attr04-02\":\"value-04-02\",n" - +" \"attr04-03\":\"value-04-03\"n" - + " }\n" - + "}"; - new JSONObject(str); - fail("Expected an exception"); + // test exception message when including a duplicate key (level 0) holding an object + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr03\": {" + +" \"attr04-01\":\"value-04-01\",n" + +" \"attr04-02\":\"value-04-02\",n" + +" \"attr04-03\":\"value-04-03\"n" + + " }\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 90 [character 13 line 5]", - e.getMessage()); + assertEquals("Expecting an expection message", + "Duplicate key \"attr03\" at 90 [character 13 line 5]", + e.getMessage()); } try { - // test exception message when including a duplicate key (level 0) holding an array - String str = "{\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr02\":\"value-02\",\n" - +" \"attr03\":\"value-03\",\n" - +" \"attr03\": [\n" - +" {" - +" \"attr04-01\":\"value-04-01\",n" - +" \"attr04-02\":\"value-04-02\",n" - +" \"attr04-03\":\"value-04-03\"n" - +" }\n" - + " ]\n" - + "}"; - new JSONObject(str); - fail("Expected an exception"); + // test exception message when including a duplicate key (level 0) holding an array + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr03\": [\n" + +" {" + +" \"attr04-01\":\"value-04-01\",n" + +" \"attr04-02\":\"value-04-02\",n" + +" \"attr04-03\":\"value-04-03\"n" + +" }\n" + + " ]\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 90 [character 13 line 5]", - e.getMessage()); + assertEquals("Expecting an expection message", + "Duplicate key \"attr03\" at 90 [character 13 line 5]", + e.getMessage()); } try { - // test exception message when including a duplicate key (level 1) - String str = "{\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr02\":\"value-02\",\n" - +" \"attr03\":\"value-03\",\n" - +" \"attr04\": {\n" - +" \"attr04-01\":\"value04-01\",\n" - +" \"attr04-02\":\"value04-02\",\n" - +" \"attr04-03\":\"value04-03\",\n" - +" \"attr04-03\":\"value04-04\"\n" - + " }\n" - + "}"; - new JSONObject(str); - fail("Expected an exception"); + // test exception message when including a duplicate key (level 1) + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr04\": {\n" + +" \"attr04-01\":\"value04-01\",\n" + +" \"attr04-02\":\"value04-02\",\n" + +" \"attr04-03\":\"value04-03\",\n" + +" \"attr04-03\":\"value04-04\"\n" + + " }\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", - e.getMessage()); + assertEquals("Expecting an expection message", + "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + e.getMessage()); } try { - // test exception message when including a duplicate key (level 1) holding an object - String str = "{\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr02\":\"value-02\",\n" - +" \"attr03\":\"value-03\",\n" - +" \"attr04\": {\n" - +" \"attr04-01\":\"value04-01\",\n" - +" \"attr04-02\":\"value04-02\",\n" - +" \"attr04-03\":\"value04-03\",\n" - +" \"attr04-03\": {\n" - +" \"attr04-04-01\":\"value04-04-01\",\n" - +" \"attr04-04-02\":\"value04-04-02\",\n" - +" \"attr04-04-03\":\"value04-04-03\",\n" - +" }\n" - +" }\n" - + "}"; - new JSONObject(str); - fail("Expected an exception"); + // test exception message when including a duplicate key (level 1) holding an object + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr04\": {\n" + +" \"attr04-01\":\"value04-01\",\n" + +" \"attr04-02\":\"value04-02\",\n" + +" \"attr04-03\":\"value04-03\",\n" + +" \"attr04-03\": {\n" + +" \"attr04-04-01\":\"value04-04-01\",\n" + +" \"attr04-04-02\":\"value04-04-02\",\n" + +" \"attr04-04-03\":\"value04-04-03\",\n" + +" }\n" + +" }\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", - e.getMessage()); + assertEquals("Expecting an expection message", + "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + e.getMessage()); } try { - // test exception message when including a duplicate key (level 1) holding an array - String str = "{\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr02\":\"value-02\",\n" - +" \"attr03\":\"value-03\",\n" - +" \"attr04\": {\n" - +" \"attr04-01\":\"value04-01\",\n" - +" \"attr04-02\":\"value04-02\",\n" - +" \"attr04-03\":\"value04-03\",\n" - +" \"attr04-03\": [\n" - +" {\n" - +" \"attr04-04-01\":\"value04-04-01\",\n" - +" \"attr04-04-02\":\"value04-04-02\",\n" - +" \"attr04-04-03\":\"value04-04-03\",\n" - +" }\n" - +" ]\n" - +" }\n" - + "}"; - new JSONObject(str); - fail("Expected an exception"); + // test exception message when including a duplicate key (level 1) holding an array + String str = "{\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\",\n" + +" \"attr03\":\"value-03\",\n" + +" \"attr04\": {\n" + +" \"attr04-01\":\"value04-01\",\n" + +" \"attr04-02\":\"value04-02\",\n" + +" \"attr04-03\":\"value04-03\",\n" + +" \"attr04-03\": [\n" + +" {\n" + +" \"attr04-04-01\":\"value04-04-01\",\n" + +" \"attr04-04-02\":\"value04-04-02\",\n" + +" \"attr04-04-03\":\"value04-04-03\",\n" + +" }\n" + +" ]\n" + +" }\n" + + "}"; + new JSONObject(str); + fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", - e.getMessage()); + assertEquals("Expecting an expection message", + "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + e.getMessage()); } try { - // test exception message when including a duplicate key in object (level 0) within an array - String str = "[\n" - +" {\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr02\":\"value-02\"\n" - +" },\n" - +" {\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr01\":\"value-02\"\n" - +" }\n" - + "]"; - new JSONArray(str); - fail("Expected an exception"); + // test exception message when including a duplicate key in object (level 0) within an array + String str = "[\n" + +" {\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\":\"value-02\"\n" + +" },\n" + +" {\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr01\":\"value-02\"\n" + +" }\n" + + "]"; + new JSONArray(str); + fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr01\" at 124 [character 17 line 8]", - e.getMessage()); + assertEquals("Expecting an expection message", + "Duplicate key \"attr01\" at 124 [character 17 line 8]", + e.getMessage()); } try { - // test exception message when including a duplicate key in object (level 1) within an array - String str = "[\n" - +" {\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr02\": {\n" - +" \"attr02-01\":\"value-02-01\",\n" - +" \"attr02-02\":\"value-02-02\"\n" - +" }\n" - +" },\n" - +" {\n" - +" \"attr01\":\"value-01\",\n" - +" \"attr02\": {\n" - +" \"attr02-01\":\"value-02-01\",\n" - +" \"attr02-01\":\"value-02-02\"\n" - +" }\n" - +" }\n" - + "]"; - new JSONArray(str); - fail("Expected an exception"); + // test exception message when including a duplicate key in object (level 1) within an array + String str = "[\n" + +" {\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\": {\n" + +" \"attr02-01\":\"value-02-01\",\n" + +" \"attr02-02\":\"value-02-02\"\n" + +" }\n" + +" },\n" + +" {\n" + +" \"attr01\":\"value-01\",\n" + +" \"attr02\": {\n" + +" \"attr02-01\":\"value-02-01\",\n" + +" \"attr02-01\":\"value-02-02\"\n" + +" }\n" + +" }\n" + + "]"; + new JSONArray(str); + fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr02-01\" at 269 [character 24 line 13]", - e.getMessage()); + assertEquals("Expecting an expection message", + "Duplicate key \"attr02-01\" at 269 [character 24 line 13]", + e.getMessage()); } } From c365e2a774693a8bdf8b19c6ddcd039678856ed4 Mon Sep 17 00:00:00 2001 From: Miguel Date: Wed, 9 Aug 2017 22:03:09 -0400 Subject: [PATCH 338/451] Remov slf4j reference --- build.gradle | 1 - 1 file changed, 1 deletion(-) diff --git a/build.gradle b/build.gradle index 53fbdb3..43656ae 100644 --- a/build.gradle +++ b/build.gradle @@ -22,7 +22,6 @@ dependencies { testCompile group: 'junit', name: 'junit', version: '4.+' testCompile group: 'com.jayway.jsonpath', name: 'json-path', version: '2.1.0' testCompile group: 'org.mockito', name: 'mockito-all', version: '1.9.5' - testCompile group: 'slf4j.org', name: 'slf4j', version: '1.6.1' // Uncomment if you are testing against a JSON-Java release // testCompile 'org.json:json:20160212' // Uncomment if you have copied a local JSON-Java jar file into this project From 7d8353401ad0943a00423cb4f3e7d71a4b6a162f Mon Sep 17 00:00:00 2001 From: Miguel Date: Thu, 10 Aug 2017 19:05:57 -0400 Subject: [PATCH 339/451] Adding JSONTokener.back() just before throwing JSONException This forces JSONTokener.syntaxError(..) to point to the last character of the duplicate key. --- JSONObject.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/JSONObject.java b/JSONObject.java index 9d5fc87..28f401e 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -232,12 +232,13 @@ public class JSONObject { throw x.syntaxError("Expected a ':' after a key"); } - // Replace: this.putOnce(key, x.nextValue()); // Use syntaxError(..) to include error location if (key != null) { // Check if key exists if (this.opt(key) != null) { + // back one token to point to the last key character + x.back(); throw x.syntaxError("Duplicate key \"" + key + "\""); } // Only add value if non-null From 68b262914df7b3a98b2d970edb1adc9b72fed4fb Mon Sep 17 00:00:00 2001 From: Miguel Date: Thu, 10 Aug 2017 19:06:55 -0400 Subject: [PATCH 340/451] JSONObject(JSONTokener) now points to last character of duplicate key Updating exception message accordingly (position -1) --- src/test/java/org/json/junit/JSONObjectTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 2dcebe4..5d49daa 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1988,7 +1988,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 90 [character 13 line 5]", + "Duplicate key \"attr03\" at 89 [character 12 line 5]", e.getMessage()); } try { @@ -2007,7 +2007,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 90 [character 13 line 5]", + "Duplicate key \"attr03\" at 89 [character 12 line 5]", e.getMessage()); } try { @@ -2028,7 +2028,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 90 [character 13 line 5]", + "Duplicate key \"attr03\" at 89 [character 12 line 5]", e.getMessage()); } try { @@ -2048,7 +2048,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + "Duplicate key \"attr04-03\" at 214 [character 19 line 9]", e.getMessage()); } try { @@ -2072,7 +2072,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + "Duplicate key \"attr04-03\" at 214 [character 19 line 9]", e.getMessage()); } try { @@ -2098,7 +2098,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + "Duplicate key \"attr04-03\" at 214 [character 19 line 9]", e.getMessage()); } try { @@ -2117,7 +2117,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr01\" at 124 [character 17 line 8]", + "Duplicate key \"attr01\" at 123 [character 16 line 8]", e.getMessage()); } try { @@ -2142,7 +2142,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr02-01\" at 269 [character 24 line 13]", + "Duplicate key \"attr02-01\" at 268 [character 23 line 13]", e.getMessage()); } } From f177c972589463674c4e3883a494cf4c1f186721 Mon Sep 17 00:00:00 2001 From: Miguel Date: Thu, 10 Aug 2017 19:12:41 -0400 Subject: [PATCH 341/451] Replacing tabs with 4-spaces --- JSONObject.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index 28f401e..a55ecf8 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -236,15 +236,15 @@ public class JSONObject { if (key != null) { // Check if key exists - if (this.opt(key) != null) { - // back one token to point to the last key character - x.back(); + if (this.opt(key) != null) { + // back one token to point to the last key character + x.back(); throw x.syntaxError("Duplicate key \"" + key + "\""); - } + } // Only add value if non-null Object value = x.nextValue(); if (value!=null) { - this.put(key, value); + this.put(key, value); } } From 2e0a8137bd911736ded8bda32c07203a0a97e9a6 Mon Sep 17 00:00:00 2001 From: Miguel Date: Mon, 14 Aug 2017 13:01:31 -0400 Subject: [PATCH 342/451] Removed JSONTokener.back() --- JSONObject.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index a55ecf8..1b7b0a1 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -237,8 +237,7 @@ public class JSONObject { if (key != null) { // Check if key exists if (this.opt(key) != null) { - // back one token to point to the last key character - x.back(); + // key already exists throw x.syntaxError("Duplicate key \"" + key + "\""); } // Only add value if non-null From b90bee0f225e2502c8b62d494f571fd27ce5bea4 Mon Sep 17 00:00:00 2001 From: Miguel Date: Mon, 14 Aug 2017 13:05:23 -0400 Subject: [PATCH 343/451] Update error message location (+1) `JSONTokener.back()` call removed from `JSONObject(JSONTokener)` constructor. --- src/test/java/org/json/junit/JSONObjectTest.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 5d49daa..2dcebe4 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1988,7 +1988,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 89 [character 12 line 5]", + "Duplicate key \"attr03\" at 90 [character 13 line 5]", e.getMessage()); } try { @@ -2007,7 +2007,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 89 [character 12 line 5]", + "Duplicate key \"attr03\" at 90 [character 13 line 5]", e.getMessage()); } try { @@ -2028,7 +2028,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 89 [character 12 line 5]", + "Duplicate key \"attr03\" at 90 [character 13 line 5]", e.getMessage()); } try { @@ -2048,7 +2048,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 214 [character 19 line 9]", + "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", e.getMessage()); } try { @@ -2072,7 +2072,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 214 [character 19 line 9]", + "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", e.getMessage()); } try { @@ -2098,7 +2098,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 214 [character 19 line 9]", + "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", e.getMessage()); } try { @@ -2117,7 +2117,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr01\" at 123 [character 16 line 8]", + "Duplicate key \"attr01\" at 124 [character 17 line 8]", e.getMessage()); } try { @@ -2142,7 +2142,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an expection message", - "Duplicate key \"attr02-01\" at 268 [character 23 line 13]", + "Duplicate key \"attr02-01\" at 269 [character 24 line 13]", e.getMessage()); } } From cb61bbf720253b2d93832544b189d0a78501c604 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sat, 19 Aug 2017 18:19:22 -0400 Subject: [PATCH 344/451] New tests for XML unescaping --- src/test/java/org/json/junit/XMLTest.java | 24 +++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 244c9e9..5daca5c 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -764,5 +764,29 @@ public class XMLTest { assertEquals(expectedReverseXml, reverseXml); } + + /** + * test to validate certain conditions of XML unescaping. + */ + @Test + public void testUnescape() { + assertEquals("{\"xml\":\"Can cope <;\"}", + XML.toJSONObject("Can cope <; ").toString()); + assertEquals("Can cope <; ", XML.unescape("Can cope <; ")); + + assertEquals("{\"xml\":\"Can cope & ;\"}", + XML.toJSONObject("Can cope & ; ").toString()); + assertEquals("Can cope & ; ", XML.unescape("Can cope & ; ")); + + assertEquals("{\"xml\":\"Can cope &;\"}", + XML.toJSONObject("Can cope &; ").toString()); + assertEquals("Can cope &; ", XML.unescape("Can cope &; ")); + + // double escaped + assertEquals("{\"xml\":\"Can cope <\"}", + XML.toJSONObject("Can cope &lt; ").toString()); + assertEquals("Can cope < ", XML.unescape("Can cope &lt; ")); + + } } \ No newline at end of file From de855c50aa4435fa54510e299e10c1481ef59ea0 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sat, 19 Aug 2017 18:21:56 -0400 Subject: [PATCH 345/451] Fixes #361. * Removes unescape from the XML class calls * fixes bug with unescape method * moves unescape logic into the XMLTokener class for more consistency --- JSONML.java | 2 +- XML.java | 38 +++++--------------------------------- XMLTokener.java | 33 +++++++++++++++++++++++++++++++-- 3 files changed, 37 insertions(+), 36 deletions(-) diff --git a/JSONML.java b/JSONML.java index c1d50b3..be16693 100644 --- a/JSONML.java +++ b/JSONML.java @@ -174,7 +174,7 @@ public class JSONML { if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } - newjo.accumulate(attribute, keepStrings ? XML.unescape((String)token) :XML.stringToValue((String)token)); + newjo.accumulate(attribute, keepStrings ? ((String)token) :XML.stringToValue((String)token)); token = null; } else { newjo.accumulate(attribute, ""); diff --git a/XML.java b/XML.java index 36f44c8..faa5b65 100644 --- a/XML.java +++ b/XML.java @@ -141,7 +141,7 @@ public class XML { if (mustEscape(cp)) { sb.append("&#x"); sb.append(Integer.toHexString(cp)); - sb.append(";"); + sb.append(';'); } else { sb.appendCodePoint(cp); } @@ -191,31 +191,7 @@ public class XML { final int semic = string.indexOf(';', i); if (semic > i) { final String entity = string.substring(i + 1, semic); - if (entity.charAt(0) == '#') { - int cp; - if (entity.charAt(1) == 'x') { - // hex encoded unicode - cp = Integer.parseInt(entity.substring(2), 16); - } else { - // decimal encoded unicode - cp = Integer.parseInt(entity.substring(1)); - } - sb.appendCodePoint(cp); - } else { - if ("quot".equalsIgnoreCase(entity)) { - sb.append('"'); - } else if ("amp".equalsIgnoreCase(entity)) { - sb.append('&'); - } else if ("apos".equalsIgnoreCase(entity)) { - sb.append('\''); - } else if ("lt".equalsIgnoreCase(entity)) { - sb.append('<'); - } else if ("gt".equalsIgnoreCase(entity)) { - sb.append('>'); - } else {// unsupported xml entity. leave encoded - sb.append('&').append(entity).append(';'); - } - } + sb.append(XMLTokener.unescapeEntity(entity)); // skip past the entity we just parsed. i += entity.length() + 1; } else { @@ -364,7 +340,7 @@ public class XML { throw x.syntaxError("Missing value"); } jsonobject.accumulate(string, - keepStrings ? unescape((String)token) : stringToValue((String) token)); + keepStrings ? ((String)token) : stringToValue((String) token)); token = null; } else { jsonobject.accumulate(string, ""); @@ -396,7 +372,7 @@ public class XML { string = (String) token; if (string.length() > 0) { jsonobject.accumulate("content", - keepStrings ? unescape(string) : stringToValue(string)); + keepStrings ? string : stringToValue(string)); } } else if (token == LT) { @@ -430,11 +406,7 @@ public class XML { * @return JSON value of this string or the string */ public static Object stringToValue(String string) { - Object ret = JSONObject.stringToValue(string); - if(ret instanceof String){ - return unescape((String)ret); - } - return ret; + return JSONObject.stringToValue(string); } /** diff --git a/XMLTokener.java b/XMLTokener.java index 1c5f2b5..fb54da3 100644 --- a/XMLTokener.java +++ b/XMLTokener.java @@ -138,8 +138,37 @@ public class XMLTokener extends JSONTokener { } } String string = sb.toString(); - Object object = entity.get(string); - return object != null ? object : ampersand + string + ";"; + return unescapeEntity(string); + } + + /** + * Unescapes an XML entity encoding; + * @param e entity (only the actual entity value, not the preceding & or ending ; + * @return + */ + static String unescapeEntity(String e) { + // validate + if (e == null || e.isEmpty()) { + return ""; + } + // if our entity is an encoded unicode point, parse it. + if (e.charAt(0) == '#') { + int cp; + if (e.charAt(1) == 'x') { + // hex encoded unicode + cp = Integer.parseInt(e.substring(2), 16); + } else { + // decimal encoded unicode + cp = Integer.parseInt(e.substring(1)); + } + return new String(new int[] {cp},0,1); + } + Character knownEntity = entity.get(e); + if(knownEntity==null) { + // we don't know the entity so keep it encoded + return '&' + e + ';'; + } + return knownEntity.toString(); } From 2713f2e2a4a5fa93cdf47b4f926ff5ea088abe68 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sat, 19 Aug 2017 18:45:53 -0400 Subject: [PATCH 346/451] Adds testing for unicode entities --- src/test/java/org/json/junit/XMLTest.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 5daca5c..c34bf0f 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -782,11 +782,20 @@ public class XMLTest { XML.toJSONObject("Can cope &; ").toString()); assertEquals("Can cope &; ", XML.unescape("Can cope &; ")); + // unicode entity + assertEquals("{\"xml\":\"Can cope 4;\"}", + XML.toJSONObject("Can cope 4; ").toString()); + assertEquals("Can cope 4; ", XML.unescape("Can cope 4; ")); + // double escaped assertEquals("{\"xml\":\"Can cope <\"}", XML.toJSONObject("Can cope &lt; ").toString()); assertEquals("Can cope < ", XML.unescape("Can cope &lt; ")); - } + assertEquals("{\"xml\":\"Can cope 4\"}", + XML.toJSONObject("Can cope &#x34; ").toString()); + assertEquals("Can cope 4 ", XML.unescape("Can cope &#x34; ")); + + } } \ No newline at end of file From cdf3cf7f814ad6a75ac51b1ec74f0d59ce8f6e6a Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 17 Oct 2017 20:05:29 -0500 Subject: [PATCH 347/451] Update README --- README | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README b/README index 2fbae18..9783046 100644 --- a/README +++ b/README @@ -89,6 +89,8 @@ invalid number formats (1.2e6.3) will cause errors as such documents can not be reliably. Release history: +20171018 Checkpoint for recent commits. + 20170516 Roll up recent commits. 20160810 Revert code that was breaking opt*() methods. From ed8745cd634f3276b7f7bef4bf0f49987c83256d Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 30 Oct 2017 08:10:06 -0400 Subject: [PATCH 348/451] fixes #372. Corrects behavior of unclosed arrays --- JSONArray.java | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 8775a19..4864fd5 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -107,7 +107,13 @@ public class JSONArray implements Iterable { if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } - if (x.nextClean() != ']') { + + char nextChar = x.nextClean(); + if (nextChar == 0) { + // array is unclosed. No ']' found, instead EOF + throw new JSONException(x.syntaxError("Expected a ',' or ']'")); + } + if (nextChar != ']') { x.back(); for (;;) { if (x.nextClean() == ',') { @@ -118,8 +124,16 @@ public class JSONArray implements Iterable { this.myArrayList.add(x.nextValue()); } switch (x.nextClean()) { + case 0: + // array is unclosed. No ']' found, instead EOF + throw new JSONException(x.syntaxError("Expected a ',' or ']'")); case ',': - if (x.nextClean() == ']') { + nextChar = x.nextClean(); + if (nextChar == 0) { + // array is unclosed. No ']' found, instead EOF + throw new JSONException(x.syntaxError("Expected a ',' or ']'")); + } + if (nextChar == ']') { return; } x.back(); From 52ecc8970237e50f52632b42f4b30ef98e565b51 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 30 Oct 2017 07:27:42 -0400 Subject: [PATCH 349/451] New test to verify unclosed array --- src/test/java/org/json/junit/JSONArrayTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 0df7c5d..1c14774 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -79,6 +79,21 @@ public class JSONArrayTest { e.getMessage()); } } + + /** + * Attempt to create a JSONArray with an unclosed array. + * Expects an exception + */ + @Test + public void unclosedArray() { + try { + assertNull("Should throw an exception", new JSONArray("[")); + } catch (JSONException e) { + assertEquals("Expected an exception message", + "A JSONArray text must start with '[' at 0 [character 1 line 1]", + e.getMessage()); + } + } /** * Attempt to create a JSONArray with a string as object that is From bde6ba1c52b1393526a24d51b04a2295e786ebfa Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 30 Oct 2017 07:41:11 -0400 Subject: [PATCH 350/451] Updates exception expected message --- src/test/java/org/json/junit/JSONArrayTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 1c14774..442fb0a 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -90,7 +90,7 @@ public class JSONArrayTest { assertNull("Should throw an exception", new JSONArray("[")); } catch (JSONException e) { assertEquals("Expected an exception message", - "A JSONArray text must start with '[' at 0 [character 1 line 1]", + "Expected a ',' or ']' at 1 [character 2 line 1]", e.getMessage()); } } From dfa37a298f019516224fe1b563a4fec66253e103 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 30 Oct 2017 08:09:42 -0400 Subject: [PATCH 351/451] Add more tests for unclosed arrays --- .../java/org/json/junit/JSONArrayTest.java | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 442fb0a..4a0249d 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -30,7 +30,7 @@ import com.jayway.jsonpath.JsonPath; * Tests for JSON-Java JSONArray.java */ public class JSONArrayTest { - String arrayStr = + private final String arrayStr = "["+ "true,"+ "false,"+ @@ -94,6 +94,36 @@ public class JSONArrayTest { e.getMessage()); } } + + /** + * Attempt to create a JSONArray with an unclosed array. + * Expects an exception + */ + @Test + public void unclosedArray2() { + try { + assertNull("Should throw an exception", new JSONArray("[\"test\"")); + } catch (JSONException e) { + assertEquals("Expected an exception message", + "Expected a ',' or ']' at 7 [character 8 line 1]", + e.getMessage()); + } + } + + /** + * Attempt to create a JSONArray with an unclosed array. + * Expects an exception + */ + @Test + public void unclosedArray3() { + try { + assertNull("Should throw an exception", new JSONArray("[\"test\",")); + } catch (JSONException e) { + assertEquals("Expected an exception message", + "Expected a ',' or ']' at 8 [character 9 line 1]", + e.getMessage()); + } + } /** * Attempt to create a JSONArray with a string as object that is @@ -372,7 +402,7 @@ public class JSONArrayTest { assertTrue("expected empty JSONArray length 0", new JSONArray().length() == 0); JSONArray jsonArray = new JSONArray(this.arrayStr); - assertTrue("expected JSONArray length 13", jsonArray.length() == 13); + assertTrue("expected JSONArray length 13. instead found "+jsonArray.length(), jsonArray.length() == 13); JSONArray nestedJsonArray = jsonArray.getJSONArray(9); assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1); } From 578a442ef764691db51f2a0e880af9c86b675409 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 30 Oct 2017 08:43:56 -0500 Subject: [PATCH 352/451] Update README.md --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 79f8724..5f83c6c 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,11 @@ When adding a new unit test, don't forget to update JunitTestSuite.java. * If you have unit test results along with pull requests, the reviewer has an easier time understanding your code and determining if the it works as intended. When you start working on a test, add the empty file to the repository and update the readme, so that others will know that test is taken. +**Caveats:** +JSON-Java is Java 1.6-compatible, but JSON-Java-unit-tests requests Java 1.8. If you see this error, make sure you have 1.8 installed, on your path, and set in JAVA_HOME: +Execution failed for task ':compileJava'. +> invalid flag: -parameters + A unit test has the following stages: From ee3aa03da156e4f8d03eb40cf86c11810f2ac120 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 30 Oct 2017 08:44:21 -0500 Subject: [PATCH 353/451] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5f83c6c..86dd85c 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ When adding a new unit test, don't forget to update JunitTestSuite.java. * If you have unit test results along with pull requests, the reviewer has an easier time understanding your code and determining if the it works as intended. When you start working on a test, add the empty file to the repository and update the readme, so that others will know that test is taken. + **Caveats:** JSON-Java is Java 1.6-compatible, but JSON-Java-unit-tests requests Java 1.8. If you see this error, make sure you have 1.8 installed, on your path, and set in JAVA_HOME: Execution failed for task ':compileJava'. From e0801befe5981dfd2b93b04c4980d0fcf73c46cf Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 30 Oct 2017 08:45:41 -0500 Subject: [PATCH 354/451] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 86dd85c..07f9445 100644 --- a/README.md +++ b/README.md @@ -84,9 +84,10 @@ When you start working on a test, add the empty file to the repository and updat **Caveats:** JSON-Java is Java 1.6-compatible, but JSON-Java-unit-tests requests Java 1.8. If you see this error, make sure you have 1.8 installed, on your path, and set in JAVA_HOME: +``` Execution failed for task ':compileJava'. > invalid flag: -parameters - +``` A unit test has the following stages: From 936db93445a9481533494f0333738f1fc5198a7e Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 30 Oct 2017 08:46:43 -0500 Subject: [PATCH 355/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 07f9445..1ca5c64 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ When adding a new unit test, don't forget to update JunitTestSuite.java. When you start working on a test, add the empty file to the repository and update the readme, so that others will know that test is taken. **Caveats:** -JSON-Java is Java 1.6-compatible, but JSON-Java-unit-tests requests Java 1.8. If you see this error, make sure you have 1.8 installed, on your path, and set in JAVA_HOME: +JSON-Java is Java 1.6-compatible, but JSON-Java-unit-tests requires Java 1.8. If you see this error when building JSON-Java-unit-test, make sure you have 1.8 installed, on your path, and set in JAVA_HOME: ``` Execution failed for task ':compileJava'. > invalid flag: -parameters From 18952b5ac0a0497378ae1462a8780b332d3cd859 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 2 Nov 2017 22:32:24 -0400 Subject: [PATCH 356/451] fixes wrapped exceptions --- JSONArray.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 4864fd5..480b746 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -111,7 +111,7 @@ public class JSONArray implements Iterable { char nextChar = x.nextClean(); if (nextChar == 0) { // array is unclosed. No ']' found, instead EOF - throw new JSONException(x.syntaxError("Expected a ',' or ']'")); + throw x.syntaxError("Expected a ',' or ']'"); } if (nextChar != ']') { x.back(); @@ -126,12 +126,12 @@ public class JSONArray implements Iterable { switch (x.nextClean()) { case 0: // array is unclosed. No ']' found, instead EOF - throw new JSONException(x.syntaxError("Expected a ',' or ']'")); + throw x.syntaxError("Expected a ',' or ']'"); case ',': nextChar = x.nextClean(); if (nextChar == 0) { // array is unclosed. No ']' found, instead EOF - throw new JSONException(x.syntaxError("Expected a ',' or ']'")); + throw x.syntaxError("Expected a ',' or ']'"); } if (nextChar == ']') { return; From 08d93f3eb5db5e3bde58fe3ca1da9da2acd4f1ed Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 6 Nov 2017 10:27:45 -0500 Subject: [PATCH 357/451] test cases for issue https://github.com/stleary/JSON-java/issues/379 --- .../java/org/json/junit/JSONArrayTest.java | 27 +++++++++++++++++++ .../java/org/json/junit/JSONObjectTest.java | 27 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 4a0249d..48050b9 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -1,6 +1,7 @@ package org.json.junit; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -54,6 +55,32 @@ public class JSONArrayTest { "\"-1\""+ "]"; + /** + * Tests that the similar method is working as expected. + */ + @Test + public void aaaVerifySimilar() { + final String string1 = "HasSameRef"; + JSONArray obj1 = new JSONArray() + .put("abc") + .put(string1) + .put(2); + + JSONArray obj2 = new JSONArray() + .put("abc") + .put(string1) + .put(3); + + JSONArray obj3 = new JSONArray() + .put("abc") + .put(new String(string1)) + .put(2); + + assertFalse("Should eval to false", obj1.similar(obj2)); + + assertTrue("Should eval to true", obj1.similar(obj3)); + } + /** * Attempt to create a JSONArray with a null string. * Expects a NullPointerException. diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 2dcebe4..6b248ad 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -58,6 +58,33 @@ import com.jayway.jsonpath.JsonPath; * otherwise be impossible. */ public class JSONObjectTest { + + /** + * Tests that the similar method is working as expected. + */ + @Test + public void aaaVerifySimilar() { + final String string1 = "HasSameRef"; + JSONObject obj1 = new JSONObject() + .put("key1", "abc") + .put("key2", 2) + .put("key3", string1); + + JSONObject obj2 = new JSONObject() + .put("key1", "abc") + .put("key2", 3) + .put("key3", string1); + + JSONObject obj3 = new JSONObject() + .put("key1", "abc") + .put("key2", 2) + .put("key3", new String(string1)); + + assertFalse("Should eval to false", obj1.similar(obj2)); + + assertTrue("Should eval to true", obj1.similar(obj3)); + + } /** * JSONObject built from a bean, but only using a null value. From 4a4b2db8c113e5843d9a1e7221cdb4ad75d0f0c2 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 6 Nov 2017 10:28:28 -0500 Subject: [PATCH 358/451] fix for issue #379 --- .gitignore | 3 +++ JSONArray.java | 2 +- JSONObject.java | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8593f48 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +# ignore eclipse project files +.project +.classpath diff --git a/JSONArray.java b/JSONArray.java index 480b746..4a82b99 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1289,7 +1289,7 @@ public class JSONArray implements Iterable { Object valueThis = this.myArrayList.get(i); Object valueOther = ((JSONArray)other).myArrayList.get(i); if(valueThis == valueOther) { - return true; + continue; } if(valueThis == null) { return false; diff --git a/JSONObject.java b/JSONObject.java index 54efa6e..f3a715f 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1844,7 +1844,7 @@ public class JSONObject { Object valueThis = entry.getValue(); Object valueOther = ((JSONObject)other).get(name); if(valueThis == valueOther) { - return true; + continue; } if(valueThis == null) { return false; From dae88d7c5cbf5569a28c5653d4d6d354d1fc2ce6 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 6 Nov 2017 10:35:49 -0500 Subject: [PATCH 359/451] fix method names --- src/test/java/org/json/junit/JSONArrayTest.java | 2 +- src/test/java/org/json/junit/JSONObjectTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 48050b9..8a31c87 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -59,7 +59,7 @@ public class JSONArrayTest { * Tests that the similar method is working as expected. */ @Test - public void aaaVerifySimilar() { + public void verifySimilar() { final String string1 = "HasSameRef"; JSONArray obj1 = new JSONArray() .put("abc") diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 6b248ad..85c37fd 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -63,7 +63,7 @@ public class JSONObjectTest { * Tests that the similar method is working as expected. */ @Test - public void aaaVerifySimilar() { + public void verifySimilar() { final String string1 = "HasSameRef"; JSONObject obj1 = new JSONObject() .put("key1", "abc") From b7e2eee4d692a0fd9b8c98ed66a67fc5fbbdd3ab Mon Sep 17 00:00:00 2001 From: Felix Leipold Date: Tue, 14 Nov 2017 16:52:03 +0100 Subject: [PATCH 360/451] Renaming README to README.md --- README => README.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename README => README.md (100%) diff --git a/README b/README.md similarity index 100% rename from README rename to README.md From 26160e1619326410e15e1bb6dc792546ddac4ec2 Mon Sep 17 00:00:00 2001 From: Felix Leipold Date: Tue, 14 Nov 2017 17:01:22 +0100 Subject: [PATCH 361/451] Remove trailing whitespace --- README.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 9783046..3e0c9d9 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ tokens. It can be constructed from a String, Reader, or InputStream. JSONException.java: The JSONException is the standard exception type thrown by this package. -JSONPointer.java: Implementation of +JSONPointer.java: Implementation of [JSON Pointer (RFC 6901)](https://tools.ietf.org/html/rfc6901). Supports JSON Pointers both in the form of string representation and URI fragment representation. @@ -65,16 +65,16 @@ JSONML.java: JSONML provides support for converting between JSONML and XML. XMLTokener.java: XMLTokener extends JSONTokener for parsing XML text. -Unit tests are maintained in a separate project. Contributing developers can test -JSON-java pull requests with the code in this project: +Unit tests are maintained in a separate project. Contributing developers can test +JSON-java pull requests with the code in this project: https://github.com/stleary/JSON-Java-unit-test -Numeric types in this package comply with ECMA-404: The JSON Data Interchange Format -(http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) and -RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format -(https://tools.ietf.org/html/rfc7159#section-6). -This package fully supports Integer, Long, and Double Java types. Partial support -for BigInteger and BigDecimal values in JSONObject and JSONArray objects is provided +Numeric types in this package comply with ECMA-404: The JSON Data Interchange Format +(http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) and +RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format +(https://tools.ietf.org/html/rfc7159#section-6). +This package fully supports Integer, Long, and Double Java types. Partial support +for BigInteger and BigDecimal values in JSONObject and JSONArray objects is provided in the form of get(), opt(), and put() API methods. Although 1.6 compatibility is currently supported, it is not a project goal and may be @@ -95,10 +95,10 @@ Release history: 20160810 Revert code that was breaking opt*() methods. -20160807 This release contains a bug in the JSONObject.opt*() and JSONArray.opt*() methods, +20160807 This release contains a bug in the JSONObject.opt*() and JSONArray.opt*() methods, it is not recommended for use. Java 1.6 compatability fixed, JSONArray.toList() and JSONObject.toMap(), -RFC4180 compatibility, JSONPointer, some exception fixes, optional XML type conversion. +RFC4180 compatibility, JSONPointer, some exception fixes, optional XML type conversion. Contains the latest code as of 7 Aug, 2016 20160212 Java 1.6 compatibility, OSGi bundle. Contains the latest code as of 12 Feb, 2016. @@ -106,9 +106,9 @@ Contains the latest code as of 7 Aug, 2016 20151123 JSONObject and JSONArray initialization with generics. Contains the latest code as of 23 Nov, 2015. -20150729 Checkpoint for Maven central repository release. Contains the latest code -as of 29 July, 2015. +20150729 Checkpoint for Maven central repository release. Contains the latest code +as of 29 July, 2015. -JSON-java releases can be found by searching the Maven repository for groupId "org.json" -and artifactId "json". For example: +JSON-java releases can be found by searching the Maven repository for groupId "org.json" +and artifactId "json". For example: https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.json%22%20AND%20a%3A%22json%22 From dba4afd0cfd88408215f7b8a0725d104ef450337 Mon Sep 17 00:00:00 2001 From: Felix Leipold Date: Tue, 14 Nov 2017 16:51:14 +0100 Subject: [PATCH 362/451] Adding maven repo badge --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3e0c9d9..97f9379 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +[![Maven Central](https://img.shields.io/maven-central/v/org.json/json.svg)](https://mvnrepository.com/artifact/org.json/json) + JSON in Java [package org.json] JSON is a light-weight, language independent, data interchange format. From b3068d9fe411978ad6dffe6fc47ec0194513e879 Mon Sep 17 00:00:00 2001 From: Felix Leipold Date: Tue, 14 Nov 2017 17:05:27 +0100 Subject: [PATCH 363/451] Marking file and class names with single quotes --- README.md | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 97f9379..3c0d7f2 100644 --- a/README.md +++ b/README.md @@ -20,52 +20,52 @@ package. The package compiles on Java 1.6-1.8. -JSONObject.java: The JSONObject can parse text from a String or a JSONTokener +`JSONObject.java`: The `JSONObject` can parse text from a `String` or a `JSONTokener` to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. -JSONArray.java: The JSONArray can parse text from a String or a JSONTokener +`JSONArray.java`: The `JSONArray` can parse text from a String or a `JSONTokener` to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization. -JSONTokener.java: The JSONTokener breaks a text into a sequence of individual -tokens. It can be constructed from a String, Reader, or InputStream. +`JSONTokener.java`: The `JSONTokener` breaks a text into a sequence of individual +tokens. It can be constructed from a `String`, `Reader`, or `InputStream`. -JSONException.java: The JSONException is the standard exception type thrown +`JSONException.java`: The `JSONException` is the standard exception type thrown by this package. -JSONPointer.java: Implementation of +`JSONPointer.java`: Implementation of [JSON Pointer (RFC 6901)](https://tools.ietf.org/html/rfc6901). Supports JSON Pointers both in the form of string representation and URI fragment representation. -JSONString.java: The JSONString interface requires a toJSONString method, +`JSONString.java`: The `JSONString` interface requires a `toJSONString` method, allowing an object to provide its own serialization. -JSONStringer.java: The JSONStringer provides a convenient facility for +`JSONStringer.java`: The `JSONStringer` provides a convenient facility for building JSON strings. -JSONWriter.java: The JSONWriter provides a convenient facility for building +`JSONWriter.java`: The `JSONWriter` provides a convenient facility for building JSON text through a writer. -CDL.java: CDL provides support for converting between JSON and comma +`CDL.java`: `CDL` provides support for converting between JSON and comma delimited lists. -Cookie.java: Cookie provides support for converting between JSON and cookies. +`Cookie.java`: `Cookie` provides support for converting between JSON and cookies. -CookieList.java: CookieList provides support for converting between JSON and +`CookieList.java`: `CookieList` provides support for converting between JSON and cookie lists. -HTTP.java: HTTP provides support for converting between JSON and HTTP headers. +`HTTP.java`: `HTTP` provides support for converting between JSON and HTTP headers. -HTTPTokener.java: HTTPTokener extends JSONTokener for parsing HTTP headers. +`HTTPTokener.java`: `HTTPTokener` extends `JSONTokener` for parsing HTTP headers. -XML.java: XML provides support for converting between JSON and XML. +`XML.java`: `XML` provides support for converting between JSON and XML. -JSONML.java: JSONML provides support for converting between JSONML and XML. +`JSONML.java`: `JSONML` provides support for converting between JSONML and XML. -XMLTokener.java: XMLTokener extends JSONTokener for parsing XML text. +`XMLTokener.java`: `XMLTokener` extends JSONTokener for parsing XML text. Unit tests are maintained in a separate project. Contributing developers can test JSON-java pull requests with the code in this project: From c88653ca2e4fe70d550b42781232fced3f0e2397 Mon Sep 17 00:00:00 2001 From: Felix Leipold Date: Tue, 14 Nov 2017 17:16:51 +0100 Subject: [PATCH 364/451] History with fixed font --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 3c0d7f2..7857df8 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,8 @@ invalid number formats (1.2e6.3) will cause errors as such documents can not be reliably. Release history: + +~~~ 20171018 Checkpoint for recent commits. 20170516 Roll up recent commits. @@ -110,6 +112,8 @@ latest code as of 23 Nov, 2015. 20150729 Checkpoint for Maven central repository release. Contains the latest code as of 29 July, 2015. +~~~ + JSON-java releases can be found by searching the Maven repository for groupId "org.json" and artifactId "json". For example: From 28efdb4860672faa3154db52cb6aa4669dbb0a1c Mon Sep 17 00:00:00 2001 From: Felix Leipold Date: Fri, 17 Nov 2017 12:24:03 +0100 Subject: [PATCH 365/451] Moving Badge below title --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7857df8..73083d5 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ -[![Maven Central](https://img.shields.io/maven-central/v/org.json/json.svg)](https://mvnrepository.com/artifact/org.json/json) - JSON in Java [package org.json] +=============================== + +[![Maven Central](https://img.shields.io/maven-central/v/org.json/json.svg)](https://mvnrepository.com/artifact/org.json/json) JSON is a light-weight, language independent, data interchange format. See http://www.JSON.org/ From 195963357c4d79c40a14443af8a48edab03626d0 Mon Sep 17 00:00:00 2001 From: Felix Leipold Date: Fri, 17 Nov 2017 12:24:17 +0100 Subject: [PATCH 366/451] Make file names bold --- README.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 73083d5..6dfd22a 100644 --- a/README.md +++ b/README.md @@ -21,52 +21,52 @@ package. The package compiles on Java 1.6-1.8. -`JSONObject.java`: The `JSONObject` can parse text from a `String` or a `JSONTokener` +**JSONObject.java**: The `JSONObject` can parse text from a `String` or a `JSONTokener` to produce a map-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant object serialization. -`JSONArray.java`: The `JSONArray` can parse text from a String or a `JSONTokener` +**JSONArray.java**: The `JSONArray` can parse text from a String or a `JSONTokener` to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization. -`JSONTokener.java`: The `JSONTokener` breaks a text into a sequence of individual +**JSONTokener.java**: The `JSONTokener` breaks a text into a sequence of individual tokens. It can be constructed from a `String`, `Reader`, or `InputStream`. -`JSONException.java`: The `JSONException` is the standard exception type thrown +**JSONException.java**: The `JSONException` is the standard exception type thrown by this package. -`JSONPointer.java`: Implementation of +**JSONPointer.java**: Implementation of [JSON Pointer (RFC 6901)](https://tools.ietf.org/html/rfc6901). Supports JSON Pointers both in the form of string representation and URI fragment representation. -`JSONString.java`: The `JSONString` interface requires a `toJSONString` method, +**JSONString.java**: The `JSONString` interface requires a `toJSONString` method, allowing an object to provide its own serialization. -`JSONStringer.java`: The `JSONStringer` provides a convenient facility for +**JSONStringer.java**: The `JSONStringer` provides a convenient facility for building JSON strings. -`JSONWriter.java`: The `JSONWriter` provides a convenient facility for building +**JSONWriter.java**: The `JSONWriter` provides a convenient facility for building JSON text through a writer. -`CDL.java`: `CDL` provides support for converting between JSON and comma +**CDL.java**: `CDL` provides support for converting between JSON and comma delimited lists. -`Cookie.java`: `Cookie` provides support for converting between JSON and cookies. +**Cookie.java**: `Cookie` provides support for converting between JSON and cookies. -`CookieList.java`: `CookieList` provides support for converting between JSON and +**CookieList.java**: `CookieList` provides support for converting between JSON and cookie lists. -`HTTP.java`: `HTTP` provides support for converting between JSON and HTTP headers. +**HTTP.java**: `HTTP` provides support for converting between JSON and HTTP headers. -`HTTPTokener.java`: `HTTPTokener` extends `JSONTokener` for parsing HTTP headers. +**HTTPTokener.java**: `HTTPTokener` extends `JSONTokener` for parsing HTTP headers. -`XML.java`: `XML` provides support for converting between JSON and XML. +**XML.java**: `XML` provides support for converting between JSON and XML. -`JSONML.java`: `JSONML` provides support for converting between JSONML and XML. +**JSONML.java**: `JSONML` provides support for converting between JSONML and XML. -`XMLTokener.java`: `XMLTokener` extends JSONTokener for parsing XML text. +**XMLTokener.java**: `XMLTokener` extends JSONTokener for parsing XML text. Unit tests are maintained in a separate project. Contributing developers can test JSON-java pull requests with the code in this project: From 9eb8c27724a669841f7a6ab38f7916bf8d4c691d Mon Sep 17 00:00:00 2001 From: Felix Leipold Date: Fri, 17 Nov 2017 12:33:50 +0100 Subject: [PATCH 367/451] Marking up class and method names as inline code --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6dfd22a..dcbdef5 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ cookie lists. **JSONML.java**: `JSONML` provides support for converting between JSONML and XML. -**XMLTokener.java**: `XMLTokener` extends JSONTokener for parsing XML text. +**XMLTokener.java**: `XMLTokener` extends `JSONTokener` for parsing XML text. Unit tests are maintained in a separate project. Contributing developers can test JSON-java pull requests with the code in this project: @@ -76,9 +76,9 @@ Numeric types in this package comply with ECMA-404: The JSON Data Interchange Fo (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) and RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format (https://tools.ietf.org/html/rfc7159#section-6). -This package fully supports Integer, Long, and Double Java types. Partial support -for BigInteger and BigDecimal values in JSONObject and JSONArray objects is provided -in the form of get(), opt(), and put() API methods. +This package fully supports `Integer`, `Long`, and `Double` Java types. Partial support +for `BigInteger` and `BigDecimal` values in `JSONObject` and `JSONArray` objects is provided +in the form of `get()`, `opt()`, and `put()` API methods. Although 1.6 compatibility is currently supported, it is not a project goal and may be removed in some future release. From b6efbabc3202feefbd8cd66a307d247f66496c3b Mon Sep 17 00:00:00 2001 From: Felix Leipold Date: Fri, 17 Nov 2017 12:46:01 +0100 Subject: [PATCH 368/451] Making links markdown links --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index dcbdef5..54abcb0 100644 --- a/README.md +++ b/README.md @@ -72,10 +72,9 @@ Unit tests are maintained in a separate project. Contributing developers can tes JSON-java pull requests with the code in this project: https://github.com/stleary/JSON-Java-unit-test -Numeric types in this package comply with ECMA-404: The JSON Data Interchange Format -(http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) and -RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format -(https://tools.ietf.org/html/rfc7159#section-6). +Numeric types in this package comply with +[ECMA-404: The JSON Data Interchange Format](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) and +[RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc7159#section-6). This package fully supports `Integer`, `Long`, and `Double` Java types. Partial support for `BigInteger` and `BigDecimal` values in `JSONObject` and `JSONArray` objects is provided in the form of `get()`, `opt()`, and `put()` API methods. From 15719886f739259800b1cd3f50fd00776b8a48ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philipp=20Gill=C3=A9?= Date: Wed, 17 Jan 2018 18:41:48 +0100 Subject: [PATCH 369/451] Remove wrong apostrophe --- JSONObject.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JSONObject.java b/JSONObject.java index f3a715f..5a6b734 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -2212,7 +2212,7 @@ public class JSONObject { // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary final String numberAsString = numberToString((Number) value); try { - // Use the BigDecimal constructor for it's parser to validate the format. + // Use the BigDecimal constructor for its parser to validate the format. @SuppressWarnings("unused") BigDecimal testNum = new BigDecimal(numberAsString); // Close enough to a JSON number that we will use it unquoted From 61cdfefc364fd7d55b51eb00e8095d72e7138cdf Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Tue, 30 Jan 2018 19:46:24 -0600 Subject: [PATCH 370/451] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 54abcb0..a62a0ea 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,8 @@ invalid number formats (1.2e6.3) will cause errors as such documents can not be Release history: ~~~ +20180130 Recent commits + 20171018 Checkpoint for recent commits. 20170516 Roll up recent commits. From cc2ed79e57dea53bb21418daaf3bbf39a68b1bed Mon Sep 17 00:00:00 2001 From: dengjianbao Date: Fri, 2 Feb 2018 22:54:08 +0800 Subject: [PATCH 371/451] Correct the message to match the function --- src/test/java/org/json/junit/JSONObjectTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 85c37fd..80283ae 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -266,7 +266,7 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(new MyNumberContainer()); String actual = jsonObject.toString(); String expected = "{\"myNumber\":{\"number\":42}}"; - assertEquals("Not Equal", expected , actual); + assertEquals("Equal", expected , actual); /** * JSONObject.put() handles objects differently than the @@ -280,7 +280,7 @@ public class JSONObjectTest { jsonObject.put("myNumber", new MyNumber()); actual = jsonObject.toString(); expected = "{\"myNumber\":42}"; - assertEquals("Not Equal", expected , actual); + assertEquals("Equal", expected , actual); /** * Calls the JSONObject(Map) ctor, which calls wrap() for values. @@ -293,7 +293,7 @@ public class JSONObjectTest { jsonObject = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); actual = jsonObject.toString(); expected = "{\"myNumber\":\"42\"}"; - assertEquals("Not Equal", expected , actual); + assertEquals("Equal", expected , actual); /** * JSONObject.put() inserts the AtomicInteger directly into the @@ -305,7 +305,7 @@ public class JSONObjectTest { jsonObject.put("myNumber", new AtomicInteger(42)); actual = jsonObject.toString(); expected = "{\"myNumber\":42}"; - assertEquals("Not Equal", expected , actual); + assertEquals("Equal", expected , actual); /** * Calls the JSONObject(Map) ctor, which calls wrap() for values. @@ -332,7 +332,7 @@ public class JSONObjectTest { jsonObject.put("myNumber", new Fraction(4,2)); actual = jsonObject.toString(); expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed - assertEquals("Not Equal", expected , actual); + assertEquals("Equal", expected , actual); } /** From 7073bc8c47aa26fe97e3ad6d545f7c7d843cb3a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gy=C3=B6rgy=20F=C3=B6ldv=C3=A1ri?= Date: Sun, 4 Feb 2018 18:43:35 +0100 Subject: [PATCH 372/451] XML toJSONObject(Readre reader) --- XML.java | 63 ++++++++++++++++++++++++++++++++++++++++++------- XMLTokener.java | 10 ++++++++ 2 files changed, 64 insertions(+), 9 deletions(-) diff --git a/XML.java b/XML.java index 08666f7..55362b2 100644 --- a/XML.java +++ b/XML.java @@ -24,6 +24,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +import java.io.Reader; +import java.io.StringReader; import java.util.Iterator; /** @@ -470,6 +472,56 @@ public class XML { return toJSONObject(string, false); } + /** + * Convert a well-formed (but not necessarily valid) XML into a + * JSONObject. Some information may be lost in this transformation because + * JSON is a data format and XML is a document format. XML uses elements, + * attributes, and content text, while JSON uses unordered collections of + * name/value pairs and arrays of values. JSON does not does not like to + * distinguish between elements and attributes. Sequences of similar + * elements are represented as JSONArrays. Content text may be placed in a + * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * are ignored. + * + * @param reader The XML source reader. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException Thrown if there is an errors while parsing the string + */ + public static JSONObject toJSONObject(Reader reader) throws JSONException { + return toJSONObject(reader, false); + } + + /** + * Convert a well-formed (but not necessarily valid) XML into a + * JSONObject. Some information may be lost in this transformation because + * JSON is a data format and XML is a document format. XML uses elements, + * attributes, and content text, while JSON uses unordered collections of + * name/value pairs and arrays of values. JSON does not does not like to + * distinguish between elements and attributes. Sequences of similar + * elements are represented as JSONArrays. Content text may be placed in a + * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * are ignored. + * + * All values are converted as strings, for 1, 01, 29.0 will not be coerced to + * numbers but will instead be the exact value as seen in the XML document. + * + * @param reader The XML source reader. + * @param keepStrings If true, then values will not be coerced into boolean + * or numeric values and will instead be left as strings + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException Thrown if there is an errors while parsing the string + */ + public static JSONObject toJSONObject(Reader reader, boolean keepStrings) throws JSONException { + JSONObject jo = new JSONObject(); + XMLTokener x = new XMLTokener(reader); + while (x.more()) { + x.skipPast("<"); + if(x.more()) { + parse(x, jo, null, keepStrings); + } + } + return jo; + } /** * Convert a well-formed (but not necessarily valid) XML string into a @@ -493,16 +545,9 @@ public class XML { * @throws JSONException Thrown if there is an errors while parsing the string */ public static JSONObject toJSONObject(String string, boolean keepStrings) throws JSONException { - JSONObject jo = new JSONObject(); - XMLTokener x = new XMLTokener(string); - while (x.more()) { - x.skipPast("<"); - if(x.more()) { - parse(x, jo, null, keepStrings); - } - } - return jo; + return toJSONObject(new StringReader(string), keepStrings); } + /** * Convert a JSONObject into a well-formed, element-normal XML string. * diff --git a/XMLTokener.java b/XMLTokener.java index 1da8b84..50e3acc 100644 --- a/XMLTokener.java +++ b/XMLTokener.java @@ -24,6 +24,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +import java.io.Reader; + /** * The XMLTokener extends the JSONTokener to provide additional methods * for the parsing of XML texts. @@ -47,6 +49,14 @@ public class XMLTokener extends JSONTokener { entity.put("quot", XML.QUOT); } + /** + * Construct an XMLTokener from a Reader. + * @param r A source reader. + */ + public XMLTokener(Reader r) { + super(r); + } + /** * Construct an XMLTokener from a string. * @param s A source string. From 97e180444d78609865e9c8612bbf76283064d29d Mon Sep 17 00:00:00 2001 From: Pavel Polushkin Date: Sun, 25 Feb 2018 13:08:58 +0300 Subject: [PATCH 373/451] ignore Intellij Idea project files --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 8593f48..50b216e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ # ignore eclipse project files .project .classpath +# ignore Intellij Idea project files +.idea +*.iml From aa5e80bc8d694bf8a552401534d93d8938eaa665 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 7 Mar 2018 12:11:17 -0500 Subject: [PATCH 374/451] add test cases for null keys --- .../java/org/json/junit/JSONObjectTest.java | 72 ++++++++++++++++--- 1 file changed, 64 insertions(+), 8 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 80283ae..5ada98c 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1973,13 +1973,7 @@ public class JSONObjectTest { "Null pointer", e.getMessage()); } - try { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, 0); - fail("Expected an exception"); - } catch (NullPointerException ignored) { - } + try { // multiple putOnce key JSONObject jsonObject = new JSONObject("{}"); @@ -2182,6 +2176,10 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(); jsonObject.putOnce(null, null); assertTrue("jsonObject should be empty", jsonObject.length() == 0); + jsonObject.putOnce("", null); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); + jsonObject.putOnce(null, ""); + assertTrue("jsonObject should be empty", jsonObject.length() == 0); } /** @@ -2453,7 +2451,7 @@ public class JSONObjectTest { * Confirms that exceptions thrown when writing values are wrapped properly. */ @Test - public void testJSONWriterException() throws IOException { + public void testJSONWriterException() { final JSONObject jsonObject = new JSONObject(); jsonObject.put("someKey",new BrokenToString()); @@ -2893,4 +2891,62 @@ public class JSONObjectTest { assertTrue(jo.get("closeable") instanceof JSONObject); assertTrue(jo.getJSONObject("closeable").has("string")); } + + @Test(expected=NullPointerException.class) + public void testPutNullBoolean() { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, false); + fail("Expected an exception"); + } + @Test(expected=NullPointerException.class) + public void testPutNullCollection() { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, Collections.emptySet()); + fail("Expected an exception"); + } + @Test(expected=NullPointerException.class) + public void testPutNullDouble() { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0.0d); + fail("Expected an exception"); + } + @Test(expected=NullPointerException.class) + public void testPutNullFloat() { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0.0f); + fail("Expected an exception"); + } + @Test(expected=NullPointerException.class) + public void testPutNullInt() { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0); + fail("Expected an exception"); + } + @Test(expected=NullPointerException.class) + public void testPutNullLong() { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0L); + fail("Expected an exception"); + } + @Test(expected=NullPointerException.class) + public void testPutNullMap() { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, Collections.emptyMap()); + fail("Expected an exception"); + } + @Test(expected=NullPointerException.class) + public void testPutNullObject() { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, new Object()); + fail("Expected an exception"); + } + } From b63b976acb140e6e0142a9e1cceae89102a7dccd Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 7 Mar 2018 12:14:32 -0500 Subject: [PATCH 375/451] Updates javadoc to match actual exceptions thrown. Also optimizes some boxing statements and returns. --- JSONArray.java | 116 ++++++++++++++++++++++++++++++------------------ JSONObject.java | 80 +++++++++++++++++++++------------ 2 files changed, 124 insertions(+), 72 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 4a82b99..421dd93 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -36,6 +36,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; + /** * A JSONArray is an ordered sequence of values. Its external text form is a * string wrapped in square brackets with commas separating the values. The @@ -182,7 +183,7 @@ public class JSONArray implements Iterable { * Construct a JSONArray from an array * * @throws JSONException - * If not an array. + * If not an array or if an array value is non-finite number. */ public JSONArray(Object array) throws JSONException { this(); @@ -465,11 +466,11 @@ public class JSONArray implements Iterable { } /** - * Determine if the value is null. + * Determine if the value is null. * * @param index * The index must be between 0 and length() - 1. - * @return true if the value at the index is null, or if there is no value. + * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(this.opt(index)); @@ -953,8 +954,7 @@ public class JSONArray implements Iterable { * @return this. */ public JSONArray put(boolean value) { - this.put(value ? Boolean.TRUE : Boolean.FALSE); - return this; + return this.put(value ? Boolean.TRUE : Boolean.FALSE); } /** @@ -964,10 +964,11 @@ public class JSONArray implements Iterable { * @param value * A Collection value. * @return this. + * @throws JSONException + * If the value is non-finite number. */ public JSONArray put(Collection value) { - this.put(new JSONArray(value)); - return this; + return this.put(new JSONArray(value)); } /** @@ -975,15 +976,25 @@ public class JSONArray implements Iterable { * * @param value * A double value. + * @return this. * @throws JSONException * if the value is not finite. - * @return this. */ public JSONArray put(double value) throws JSONException { - Double d = new Double(value); - JSONObject.testValidity(d); - this.put(d); - return this; + return this.put(Double.valueOf(value)); + } + + /** + * Append a float value. This increases the array's length by one. + * + * @param value + * A float value. + * @return this. + * @throws JSONException + * if the value is not finite. + */ + public JSONArray put(float value) throws JSONException { + return this.put(Float.valueOf(value)); } /** @@ -994,8 +1005,7 @@ public class JSONArray implements Iterable { * @return this. */ public JSONArray put(int value) { - this.put(new Integer(value)); - return this; + return this.put(Integer.valueOf(value)); } /** @@ -1006,8 +1016,7 @@ public class JSONArray implements Iterable { * @return this. */ public JSONArray put(long value) { - this.put(new Long(value)); - return this; + return this.put(Long.valueOf(value)); } /** @@ -1017,10 +1026,13 @@ public class JSONArray implements Iterable { * @param value * A Map value. * @return this. + * @throws JSONException + * If a value in the map is non-finite number. + * @throws NullPointerException + * If a key in the map is null */ public JSONArray put(Map value) { - this.put(new JSONObject(value)); - return this; + return this.put(new JSONObject(value)); } /** @@ -1031,8 +1043,11 @@ public class JSONArray implements Iterable { * Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. + * @throws JSONException + * If the value is non-finite number. */ public JSONArray put(Object value) { + JSONObject.testValidity(value); this.myArrayList.add(value); return this; } @@ -1051,8 +1066,7 @@ public class JSONArray implements Iterable { * If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { - this.put(index, value ? Boolean.TRUE : Boolean.FALSE); - return this; + return this.put(index, value ? Boolean.TRUE : Boolean.FALSE); } /** @@ -1065,11 +1079,10 @@ public class JSONArray implements Iterable { * A Collection value. * @return this. * @throws JSONException - * If the index is negative or if the value is not finite. + * If the index is negative or if the value is non-finite. */ public JSONArray put(int index, Collection value) throws JSONException { - this.put(index, new JSONArray(value)); - return this; + return this.put(index, new JSONArray(value)); } /** @@ -1083,11 +1096,27 @@ public class JSONArray implements Iterable { * A double value. * @return this. * @throws JSONException - * If the index is negative or if the value is not finite. + * If the index is negative or if the value is non-finite. */ public JSONArray put(int index, double value) throws JSONException { - this.put(index, new Double(value)); - return this; + return this.put(index, Double.valueOf(value)); + } + + /** + * Put or replace a float value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad it + * out. + * + * @param index + * The subscript. + * @param value + * A float value. + * @return this. + * @throws JSONException + * If the index is negative or if the value is non-finite. + */ + public JSONArray put(int index, float value) throws JSONException { + return this.put(index, Float.valueOf(value)); } /** @@ -1104,8 +1133,7 @@ public class JSONArray implements Iterable { * If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { - this.put(index, new Integer(value)); - return this; + return this.put(index, Integer.valueOf(value)); } /** @@ -1122,8 +1150,7 @@ public class JSONArray implements Iterable { * If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { - this.put(index, new Long(value)); - return this; + return this.put(index, Long.valueOf(value)); } /** @@ -1138,6 +1165,8 @@ public class JSONArray implements Iterable { * @throws JSONException * If the index is negative or if the the value is an invalid * number. + * @throws NullPointerException + * If a key in the map is null */ public JSONArray put(int index, Map value) throws JSONException { this.put(index, new JSONObject(value)); @@ -1161,25 +1190,26 @@ public class JSONArray implements Iterable { * number. */ public JSONArray put(int index, Object value) throws JSONException { - JSONObject.testValidity(value); if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } if (index < this.length()) { + JSONObject.testValidity(value); this.myArrayList.set(index, value); - } else if(index == this.length()){ - // simple append - this.put(value); - } else { - // if we are inserting past the length, we want to grow the array all at once - // instead of incrementally. - this.myArrayList.ensureCapacity(index + 1); - while (index != this.length()) { - this.put(JSONObject.NULL); - } - this.put(value); + return this; } - return this; + if(index == this.length()){ + // simple append + return this.put(value); + } + // if we are inserting past the length, we want to grow the array all at once + // instead of incrementally. + this.myArrayList.ensureCapacity(index + 1); + while (index != this.length()) { + // we don't need to test validity of NULL objects + this.myArrayList.add(JSONObject.NULL); + } + return this.put(value); } /** diff --git a/JSONObject.java b/JSONObject.java index 5a6b734..6ddf6f3 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -271,6 +271,10 @@ public class JSONObject { * @param m * A map object that can be used to initialize the contents of * the JSONObject. + * @throws JSONException + * If a value in the map is non-finite number. + * @throws NullPointerException + * If a key in the map is null */ public JSONObject(Map m) { if (m == null) { @@ -278,6 +282,9 @@ public class JSONObject { } else { this.map = new HashMap(m.size()); for (final Entry e : m.entrySet()) { + if(e.getKey() == null) { + throw new NullPointerException("Null key."); + } final Object value = e.getValue(); if (value != null) { this.map.put(String.valueOf(e.getKey()), wrap(value)); @@ -428,7 +435,9 @@ public class JSONObject { * 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. + * If the value is non-finite number. + * @throws NullPointerException + * If the key is null. */ public JSONObject accumulate(String key, Object value) throws JSONException { testValidity(value); @@ -457,8 +466,10 @@ public class JSONObject { * An object to be accumulated under the key. * @return this. * @throws JSONException - * If the key is null or if the current value associated with + * If the value is non-finite number or if the current value associated with * the key is not a JSONArray. + * @throws NullPointerException + * If the key is null. */ public JSONObject append(String key, Object value) throws JSONException { testValidity(value); @@ -856,13 +867,13 @@ public class JSONObject { } /** - * Determine if the value associated with the key is null or if there is no + * Determine if the value associated with the key is null or if there is no * value. * * @param key * A key string. * @return true if there is no value associated with the key or if the value - * is the JSONObject.NULL object. + * is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(this.opt(key)); @@ -922,7 +933,7 @@ public class JSONObject { * JSONObject. * * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. + * is empty. */ public JSONArray names() { if(this.map.isEmpty()) { @@ -1485,11 +1496,12 @@ public class JSONObject { * A boolean which is the value. * @return this. * @throws JSONException - * If the key is null. + * If the value is non-finite number. + * @throws NullPointerException + * If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { - this.put(key, value ? Boolean.TRUE : Boolean.FALSE); - return this; + return this.put(key, value ? Boolean.TRUE : Boolean.FALSE); } /** @@ -1502,10 +1514,12 @@ public class JSONObject { * A Collection value. * @return this. * @throws JSONException + * If the value is non-finite number. + * @throws NullPointerException + * If the key is null. */ public JSONObject put(String key, Collection value) throws JSONException { - this.put(key, new JSONArray(value)); - return this; + return this.put(key, new JSONArray(value)); } /** @@ -1517,11 +1531,12 @@ public class JSONObject { * A double which is the value. * @return this. * @throws JSONException - * If the key is null or if the number is invalid. + * If the value is non-finite number. + * @throws NullPointerException + * If the key is null. */ public JSONObject put(String key, double value) throws JSONException { - this.put(key, Double.valueOf(value)); - return this; + return this.put(key, Double.valueOf(value)); } /** @@ -1533,11 +1548,12 @@ public class JSONObject { * A float which is the value. * @return this. * @throws JSONException - * If the key is null or if the number is invalid. + * If the value is non-finite number. + * @throws NullPointerException + * If the key is null. */ public JSONObject put(String key, float value) throws JSONException { - this.put(key, Float.valueOf(value)); - return this; + return this.put(key, Float.valueOf(value)); } /** @@ -1549,11 +1565,12 @@ public class JSONObject { * An int which is the value. * @return this. * @throws JSONException - * If the key is null. + * If the value is non-finite number. + * @throws NullPointerException + * If the key is null. */ public JSONObject put(String key, int value) throws JSONException { - this.put(key, Integer.valueOf(value)); - return this; + return this.put(key, Integer.valueOf(value)); } /** @@ -1565,11 +1582,12 @@ public class JSONObject { * A long which is the value. * @return this. * @throws JSONException - * If the key is null. + * If the value is non-finite number. + * @throws NullPointerException + * If the key is null. */ public JSONObject put(String key, long value) throws JSONException { - this.put(key, Long.valueOf(value)); - return this; + return this.put(key, Long.valueOf(value)); } /** @@ -1582,14 +1600,16 @@ public class JSONObject { * A Map value. * @return this. * @throws JSONException + * If the value is non-finite number. + * @throws NullPointerException + * If the key is null. */ public JSONObject put(String key, Map value) throws JSONException { - this.put(key, new JSONObject(value)); - return this; + return this.put(key, new JSONObject(value)); } /** - * Put a key/value pair in the JSONObject. If the value is null, then the + * Put a key/value pair in the JSONObject. If the value is null, then the * key will be removed from the JSONObject if it is present. * * @param key @@ -1600,7 +1620,9 @@ public class JSONObject { * String, or the JSONObject.NULL object. * @return this. * @throws JSONException - * If the value is non-finite number or if the key is null. + * If the value is non-finite number. + * @throws NullPointerException + * If the key is null. */ public JSONObject put(String key, Object value) throws JSONException { if (key == null) { @@ -1631,7 +1653,7 @@ public class JSONObject { if (this.opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } - this.put(key, value); + return this.put(key, value); } return this; } @@ -1652,7 +1674,7 @@ public class JSONObject { */ public JSONObject putOpt(String key, Object value) throws JSONException { if (key != null && value != null) { - this.put(key, value); + return this.put(key, value); } return this; } @@ -2130,7 +2152,7 @@ public class JSONObject { } /** - * Wrap an object, if necessary. If the object is null, return the NULL + * Wrap an object, if necessary. If the object is null, return the NULL * object. If it is an array or collection, wrap it in a JSONArray. If it is * a map, wrap it in a JSONObject. If it is a standard property (Double, * String, et al) then it is already wrapped. Otherwise, if it comes from From 74b9a60f98b352a15581d98018a8a5d3318308aa Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 7 Mar 2018 14:51:37 -0500 Subject: [PATCH 376/451] Adds annotation to support custom field names during Bean serialization --- JSONObject.java | 235 ++++++++++++++++++++++++++++++++++------ JSONPropertyIgnore.java | 43 ++++++++ JSONPropertyName.java | 47 ++++++++ README.md | 12 ++ 4 files changed, 302 insertions(+), 35 deletions(-) create mode 100644 JSONPropertyIgnore.java create mode 100644 JSONPropertyName.java diff --git a/JSONObject.java b/JSONObject.java index 5a6b734..ca219c9 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -29,6 +29,7 @@ import java.io.Closeable; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; +import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -290,21 +291,44 @@ public class JSONObject { * Construct a JSONObject from an Object using bean getters. It reflects on * all of the public methods of the object. For each of the methods with no * parameters and a name starting with "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. + * "is", the method is invoked, and a key and the value + * returned from the getter method are put into the new JSONObject. *

* The key is formed by removing the "get" or "is" * prefix. If the second remaining character is not upper case, then the * first character is converted to lower case. *

+ * Methods that return void as well as static + * methods are ignored. + *

* For example, if an object has a method named "getName", and * if the result of calling object.getName() is * "Larry Fine", then the JSONObject will contain * "name": "Larry Fine". *

- * Methods that return void as well as static - * methods are ignored. + * The {@link JSONPropertyName} annotation can be used on a bean getter to + * override key name used in the JSONObject. For example, using the object + * above with the getName method, if we annotated it with: + *

+     * @JSONPropertyName("FullName")
+     * public String getName() { return this.name; }
+     * 
+ * The resulting JSON object would contain "FullName": "Larry Fine" + *

+ * The {@link JSONPropertyIgnore} annotation can be used to force the bean property + * to not be serialized into JSON. If both {@link JSONPropertyIgnore} and + * {@link JSONPropertyName} are defined on the same method, a depth comparison is + * performed and the one closest to the concrete class being serialized is used. + * If both annotations are at the same level, then the {@link JSONPropertyIgnore} + * annotation takes precedent and the field is not serialized. + * For example, the following declaration would prevent the getName + * method from being serialized: + *

+     * @JSONPropertyName("FullName")
+     * @JSONPropertyIgnore 
+     * public String getName() { return this.name; }
+     * 
+ *

* * @param bean * An object that has getter methods that should be used to make @@ -1409,8 +1433,8 @@ public class JSONObject { } /** - * Populates the internal map of the JSONObject with the bean properties. - * The bean can not be recursive. + * Populates the internal map of the JSONObject with the bean properties. The + * bean can not be recursive. * * @see JSONObject#JSONObject(Object) * @@ -1420,49 +1444,31 @@ public class JSONObject { private void populateMap(Object bean) { Class klass = bean.getClass(); -// If klass is a System class then set includeSuperClass to false. + // If klass is a System class then set includeSuperClass to false. boolean includeSuperClass = klass.getClassLoader() != null; - Method[] methods = includeSuperClass ? klass.getMethods() : klass - .getDeclaredMethods(); + Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); for (final Method method : methods) { final int modifiers = method.getModifiers(); if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) && method.getParameterTypes().length == 0 && !method.isBridge() - && method.getReturnType() != Void.TYPE ) { - final String name = method.getName(); - String key; - if (name.startsWith("get")) { - if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { - continue; - } - key = name.substring(3); - } else if (name.startsWith("is")) { - key = name.substring(2); - } else { - continue; - } - if (key.length() > 0 - && Character.isUpperCase(key.charAt(0))) { - if (key.length() == 1) { - key = key.toLowerCase(Locale.ROOT); - } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase(Locale.ROOT) - + key.substring(1); - } - + && method.getReturnType() != Void.TYPE + && isValidMethodName(method.getName())) { + final String key = getKeyNameFromMethod(method); + if (key != null && !key.isEmpty()) { try { final Object result = method.invoke(bean); if (result != null) { this.map.put(key, wrap(result)); // we don't use the result anywhere outside of wrap - // if it's a resource we should be sure to close it after calling toString - if(result instanceof Closeable) { + // if it's a resource we should be sure to close it + // after calling toString + if (result instanceof Closeable) { try { - ((Closeable)result).close(); + ((Closeable) result).close(); } catch (IOException ignore) { } } @@ -1476,6 +1482,165 @@ public class JSONObject { } } + private boolean isValidMethodName(String name) { + return (name.startsWith("get") || name.startsWith("is")) + && !"getClass".equals(name) + && !"getDeclaringClass".equals(name); + } + + private String getKeyNameFromMethod(Method method) { + final int ignoreDepth = getAnnotationDepth(method, JSONPropertyIgnore.class); + if (ignoreDepth > 0) { + final int forcedNameDepth = getAnnotationDepth(method, JSONPropertyName.class); + if (forcedNameDepth < 0 || ignoreDepth <= forcedNameDepth) { + // the hierarchy asked to ignore, and the nearest name override + // was higher or non-existent + return null; + } + } + JSONPropertyName annotation = getAnnotation(method, JSONPropertyName.class); + if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) { + return annotation.value(); + } + String key; + final String name = method.getName(); + if (name.startsWith("get")) { + key = name.substring(3); + } else if (name.startsWith("is")) { + key = name.substring(2); + } else { + return null; + } + // if the first letter in the key is not uppercase, then skip. + // This is to maintain backwards compatibility before PR406 + // (https://github.com/stleary/JSON-java/pull/406/) + if(key.isEmpty() || Character.isLowerCase(key.charAt(0))) { + return null; + } + if (key.length() == 1) { + key = key.toLowerCase(Locale.ROOT); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1); + } + return key; + } + + /** + * Searches the class hierarchy to see if the method or it's super + * implementations and interfaces has the annotation. + * + * @param + * type of the annotation + * + * @param m + * method to check + * @param annotationClass + * annotation to look for + * @return the {@link Annotation} if the annotation exists on the current method + * or one of it's super class definitions + */ + private static A getAnnotation(final Method m, final Class annotationClass) { + // if we have invalid data the result is null + if (m == null || annotationClass == null) { + return null; + } + + if (m.isAnnotationPresent(annotationClass)) { + return m.getAnnotation(annotationClass); + } + + // if we've already reached the Object class, return null; + Class c = m.getDeclaringClass(); + if (c.getSuperclass() == null) { + return null; + } + + // check directly implemented interfaces for the method being checked + for (Class i : c.getInterfaces()) { + try { + Method im = i.getMethod(m.getName(), m.getParameterTypes()); + return getAnnotation(im, annotationClass); + } catch (final SecurityException ex) { + continue; + } catch (final NoSuchMethodException ex) { + continue; + } + } + + try { + return getAnnotation(m.getDeclaringClass().getSuperclass().getMethod(m.getName(), + m.getParameterTypes()), + annotationClass); + } catch (final SecurityException ex) { + return null; + } catch (final NoSuchMethodException ex) { + return null; + } + } + + /** + * Searches the class hierarchy to see if the method or it's super + * implementations and interfaces has the annotation. Returns the depth of the + * annotation in the hierarchy. + * + * @param + * type of the annotation + * + * @param m + * method to check + * @param annotationClass + * annotation to look for + * @return Depth of the annotation or -1 if the annotation is not on the method. + */ + private static int getAnnotationDepth(final Method m, final Class annotationClass) { + // if we have invalid data the result is -1 + if (m == null || annotationClass == null) { + return -1; + } + + if (m.isAnnotationPresent(annotationClass)) { + return 1; + } + + // if we've already reached the Object class, return -1; + Class c = m.getDeclaringClass(); + if (c.getSuperclass() == null) { + return -1; + } + + // check directly implemented interfaces for the method being checked + for (Class i : c.getInterfaces()) { + try { + Method im = i.getMethod(m.getName(), m.getParameterTypes()); + int d = getAnnotationDepth(im, annotationClass); + if (d > 0) { + // since the annotation was on the interface, add 1 + return d + 1; + } + } catch (final SecurityException ex) { + continue; + } catch (final NoSuchMethodException ex) { + continue; + } + } + + try { + int d = getAnnotationDepth( + m.getDeclaringClass().getSuperclass().getMethod(m.getName(), + m.getParameterTypes()), + annotationClass); + if (d > 0) { + // since the annotation was on the superclass, add 1 + return d + 1; + } + return -1; + } catch (final SecurityException ex) { + return -1; + } catch (final NoSuchMethodException ex) { + return -1; + } + } + /** * Put a key/boolean pair in the JSONObject. * diff --git a/JSONPropertyIgnore.java b/JSONPropertyIgnore.java new file mode 100644 index 0000000..682de74 --- /dev/null +++ b/JSONPropertyIgnore.java @@ -0,0 +1,43 @@ +package org.json; + +/* +Copyright (c) 2018 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Documented +@Retention(RUNTIME) +@Target({METHOD}) +/** + * Use this annotation on a getter method to override the Bean name + * parser for Bean -> JSONObject mapping. If this annotation is + * present at any level in the class hierarchy, then the method will + * not be serialized from the bean into the JSONObject. + */ +public @interface JSONPropertyIgnore { } diff --git a/JSONPropertyName.java b/JSONPropertyName.java new file mode 100644 index 0000000..a1bcd58 --- /dev/null +++ b/JSONPropertyName.java @@ -0,0 +1,47 @@ +package org.json; + +/* +Copyright (c) 2018 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Documented +@Retention(RUNTIME) +@Target({METHOD}) +/** + * Use this annotation on a getter method to override the Bean name + * parser for Bean -> JSONObject mapping. A value set to empty string "" + * will have the Bean parser fall back to the default field name processing. + */ +public @interface JSONPropertyName { + /** + * @return The name of the property as to be used in the JSON Object. + */ + String value(); +} diff --git a/README.md b/README.md index a62a0ea..e66f3c6 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,18 @@ by this package. JSON Pointers both in the form of string representation and URI fragment representation. +**JSONPropertyIgnore.java**: Annotation class that can be used on Java Bean getter methods. +When used on a bean method that would normally be serialized into a `JSONObject`, it +overrides the getter-to-key-name logic and forces the property to be excluded from the +resulting `JSONObject`. + +**JSONPropertyName.java**: Annotation class that can be used on Java Bean getter methods. +When used on a bean method that would normally be serialized into a `JSONObject`, it +overrides the getter-to-key-name logic and uses the value of the annotation. The Bean +processor will look through the class hierarchy. This means you can use the annotation on +a base class or interface and the value of the annotation will be used even if the getter +is overridden in a child class. + **JSONString.java**: The `JSONString` interface requires a `toJSONString` method, allowing an object to provide its own serialization. From 193a3823b53ad6684987671ee3da54f6d9a2705b Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 7 Mar 2018 14:52:50 -0500 Subject: [PATCH 377/451] new test cases to support bean annotation --- .../java/org/json/junit/JSONObjectTest.java | 77 ++++++++++++++++++- .../java/org/json/junit/data/GenericBean.java | 2 +- .../org/json/junit/data/GenericBeanInt.java | 29 ++++++- .../org/json/junit/data/MyBeanCustomName.java | 20 +++++ .../junit/data/MyBeanCustomNameInterface.java | 11 +++ .../junit/data/MyBeanCustomNameSubClass.java | 32 ++++++++ 6 files changed, 165 insertions(+), 6 deletions(-) create mode 100644 src/test/java/org/json/junit/data/MyBeanCustomName.java create mode 100644 src/test/java/org/json/junit/data/MyBeanCustomNameInterface.java create mode 100644 src/test/java/org/json/junit/data/MyBeanCustomNameSubClass.java diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 80283ae..0579acb 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -37,6 +37,8 @@ import org.json.junit.data.Fraction; import org.json.junit.data.GenericBean; import org.json.junit.data.GenericBeanInt; import org.json.junit.data.MyBean; +import org.json.junit.data.MyBeanCustomName; +import org.json.junit.data.MyBeanCustomNameSubClass; import org.json.junit.data.MyBigNumberBean; import org.json.junit.data.MyEnum; import org.json.junit.data.MyEnumField; @@ -371,7 +373,7 @@ public class JSONObjectTest { /** - * Verifies that the put Map has backwards compatability with RAW types pre-java5. + * Verifies that the put Map has backwards compatibility with RAW types pre-java5. */ @Test public void verifyPutMap() { @@ -467,7 +469,7 @@ public class JSONObjectTest { */ @SuppressWarnings("boxing") @Test - public void jsonObjectByBean() { + public void jsonObjectByBean1() { /** * Default access classes have to be mocked since JSONObject, which is * not in the same package, cannot call MyBean methods by reflection. @@ -501,6 +503,73 @@ public class JSONObjectTest { assertTrue("expected 0 callbacks[1] items", ((Map)(JsonPath.read(doc, "$.callbacks[1]"))).size() == 0); } + /** + * JSONObject built from a bean that has custom field names. + */ + @Test + public void jsonObjectByBean2() { + JSONObject jsonObject = new JSONObject(new MyBeanCustomName()); + assertNotNull(jsonObject); + assertEquals("Wrong number of keys found:", + 5, + jsonObject.keySet().size()); + assertFalse("Normal field name (someString) processing did not work", + jsonObject.has("someString")); + assertFalse("Normal field name (myDouble) processing did not work", + jsonObject.has("myDouble")); + assertFalse("Normal field name (someFloat) found", + jsonObject.has("someFloat")); + assertFalse("Ignored field found!", + jsonObject.has("ignoredInt")); + assertTrue("Normal field name (someInt) processing did not work", + jsonObject.has("someInt")); + assertTrue("Normal field name (someLong) processing did not work", + jsonObject.has("someLong")); + assertTrue("Overridden String field name (myStringField) not found", + jsonObject.has("myStringField")); + assertTrue("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) not found", + jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!")); + assertTrue("Overridden String field name (InterfaceField) not found", + jsonObject.has("InterfaceField")); + } + + /** + * JSONObject built from a bean that has custom field names inherited from a parent class. + */ + @Test + public void jsonObjectByBean3() { + JSONObject jsonObject = new JSONObject(new MyBeanCustomNameSubClass()); + assertNotNull(jsonObject); + assertEquals("Wrong number of keys found:", + 7, + jsonObject.keySet().size()); + assertFalse("Normal int field name (someInt) found, but was overridden", + jsonObject.has("someInt")); + assertFalse("Normal field name (myDouble) processing did not work", + jsonObject.has("myDouble")); + assertFalse("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) FOUND!", + jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!")); + assertFalse("Normal field name (someFloat) found", + jsonObject.has("someFloat")); + assertFalse("Ignored field found!", + jsonObject.has("ignoredInt")); + assertFalse("Ignored field at the same level as forced name found", + jsonObject.has("ShouldBeIgnored")); + assertTrue("Overridden int field name (newIntFieldName) not found", + jsonObject.has("newIntFieldName")); + assertTrue("Normal field name (someLong) processing did not work", + jsonObject.has("someLong")); + assertTrue("Overridden String field name (myStringField) not found", + jsonObject.has("myStringField")); + assertTrue(jsonObject.has("AMoreNormalName")); + assertTrue("Overridden String field name (InterfaceField) not found", + jsonObject.has("InterfaceField")); + assertTrue("Forced field not found!", + jsonObject.has("forcedInt")); + assertTrue("Normally ignored field (getable) with explicit property name not found", + jsonObject.has("Getable")); + } + /** * A bean is also an object. But in order to test the JSONObject * ctor that takes an object and a list of names, @@ -541,7 +610,7 @@ public class JSONObjectTest { assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later"))); assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator"))); } - + /** * Exercise the JSONObject.accumulate() method */ @@ -2857,7 +2926,7 @@ public class JSONObjectTest { public void testGenericIntBean() { GenericBeanInt bean = new GenericBeanInt(42); final JSONObject jo = new JSONObject(bean); - assertEquals(jo.keySet().toString(), 9, jo.length()); + assertEquals(jo.keySet().toString(), 10, jo.length()); assertEquals(42, jo.get("genericValue")); assertEquals("Expected the getter to only be called once", 1, bean.genericGetCounter); diff --git a/src/test/java/org/json/junit/data/GenericBean.java b/src/test/java/org/json/junit/data/GenericBean.java index 4740030..da6370d 100644 --- a/src/test/java/org/json/junit/data/GenericBean.java +++ b/src/test/java/org/json/junit/data/GenericBean.java @@ -20,7 +20,7 @@ public class GenericBean> implements MyBean { } /** */ - private T genericValue; + protected T genericValue; /** to be used by the calling test to see how often the getter is called */ public int genericGetCounter; /** to be used by the calling test to see how often the setter is called */ diff --git a/src/test/java/org/json/junit/data/GenericBeanInt.java b/src/test/java/org/json/junit/data/GenericBeanInt.java index 8f0248d..5056611 100644 --- a/src/test/java/org/json/junit/data/GenericBeanInt.java +++ b/src/test/java/org/json/junit/data/GenericBeanInt.java @@ -13,7 +13,7 @@ public class GenericBeanInt extends GenericBean { /** @return the a */ public char getA() { - return a; + return this.a; } /** @@ -25,6 +25,33 @@ public class GenericBeanInt extends GenericBean { return false; } + /** + * Should not be beanable + * + * @return false + */ + public boolean get() { + return false; + } + + /** + * Should not be beanable + * + * @return false + */ + public boolean is() { + return false; + } + + /** + * Should be beanable + * + * @return false + */ + public boolean isB() { + return this.genericValue.equals((Integer.valueOf(this.a+1))); + } + /** * @param genericValue * the value to initiate with. diff --git a/src/test/java/org/json/junit/data/MyBeanCustomName.java b/src/test/java/org/json/junit/data/MyBeanCustomName.java new file mode 100644 index 0000000..56756c2 --- /dev/null +++ b/src/test/java/org/json/junit/data/MyBeanCustomName.java @@ -0,0 +1,20 @@ +package org.json.junit.data; + +import org.json.JSONPropertyName; + +/** + * Test bean for the {@link JSONPropertyName} annotation. + */ +public class MyBeanCustomName implements MyBeanCustomNameInterface { + public int getSomeInt() { return 42; } + @JSONPropertyName("") + public long getSomeLong() { return 42L; } + @JSONPropertyName("myStringField") + public String getSomeString() { return "someStringValue"; } + @JSONPropertyName("Some Weird NAme that Normally Wouldn't be possible!") + public double getMyDouble() { return 0.0d; } + @Override + public float getSomeFloat() { return 2.0f; } + @Override + public int getIgnoredInt() { return 40; } +} diff --git a/src/test/java/org/json/junit/data/MyBeanCustomNameInterface.java b/src/test/java/org/json/junit/data/MyBeanCustomNameInterface.java new file mode 100644 index 0000000..b25b578 --- /dev/null +++ b/src/test/java/org/json/junit/data/MyBeanCustomNameInterface.java @@ -0,0 +1,11 @@ +package org.json.junit.data; + +import org.json.JSONPropertyIgnore; +import org.json.JSONPropertyName; + +public interface MyBeanCustomNameInterface { + @JSONPropertyName("InterfaceField") + float getSomeFloat(); + @JSONPropertyIgnore + int getIgnoredInt(); +} \ No newline at end of file diff --git a/src/test/java/org/json/junit/data/MyBeanCustomNameSubClass.java b/src/test/java/org/json/junit/data/MyBeanCustomNameSubClass.java new file mode 100644 index 0000000..8f0500c --- /dev/null +++ b/src/test/java/org/json/junit/data/MyBeanCustomNameSubClass.java @@ -0,0 +1,32 @@ +/** + * + */ +package org.json.junit.data; + +import org.json.JSONPropertyIgnore; +import org.json.JSONPropertyName; + +/** + * Test bean to verify that the {@link org.json.JSONPropertyName} annotation + * is inherited. + */ +public class MyBeanCustomNameSubClass extends MyBeanCustomName { + @Override + @JSONPropertyName("forcedInt") + public int getIgnoredInt() { return 42*42; } + @Override + @JSONPropertyName("newIntFieldName") + public int getSomeInt() { return 43; } + @Override + public String getSomeString() { return "subClassString"; } + @Override + @JSONPropertyName("AMoreNormalName") + public double getMyDouble() { return 1.0d; } + @Override + public float getSomeFloat() { return 3.0f; } + @JSONPropertyIgnore + @JSONPropertyName("ShouldBeIgnored") + public boolean getShouldNotBeJSON() { return true; } + @JSONPropertyName("Getable") + public boolean getable() { return true; } +} From a509a28ed47a5a31e0981a6de3949a7b46c5aa4a Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Sun, 11 Mar 2018 16:59:34 -0400 Subject: [PATCH 378/451] Cleans up the name check a little to be more permissive on what can be tagged with the new JSONPropertyName annotation. Also updates the javadoc to reflect the new name allowances --- JSONObject.java | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index ca219c9..58138c0 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -291,15 +291,16 @@ public class JSONObject { * Construct a JSONObject from an Object using bean getters. It reflects on * all of the public methods of the object. For each of the methods with no * parameters and a name starting with "get" or - * "is", the method is invoked, and a key and the value - * returned from the getter method are put into the new JSONObject. + * "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. *

* The key is formed by removing the "get" or "is" * prefix. If the second remaining character is not upper case, then the * first character is converted to lower case. *

- * Methods that return void as well as static - * methods are ignored. + * Methods that are static, return void, + * have parameters, or are "bridge" methods, are ignored. *

* For example, if an object has a method named "getName", and * if the result of calling object.getName() is @@ -315,6 +316,16 @@ public class JSONObject { * * The resulting JSON object would contain "FullName": "Larry Fine" *

+ * Similarly, the {@link JSONPropertyName} annotation can be used on non- + * get and is methods. We can also override key + * name used in the JSONObject as seen below even though the field would normally + * be ignored: + *

+     * @JSONPropertyName("FullName")
+     * public String fullName() { return this.name; }
+     * 
+ * The resulting JSON object would contain "FullName": "Larry Fine" + *

* The {@link JSONPropertyIgnore} annotation can be used to force the bean property * to not be serialized into JSON. If both {@link JSONPropertyIgnore} and * {@link JSONPropertyName} are defined on the same method, a depth comparison is @@ -1483,9 +1494,7 @@ public class JSONObject { } private boolean isValidMethodName(String name) { - return (name.startsWith("get") || name.startsWith("is")) - && !"getClass".equals(name) - && !"getDeclaringClass".equals(name); + return !"getClass".equals(name) && !"getDeclaringClass".equals(name); } private String getKeyNameFromMethod(Method method) { @@ -1504,9 +1513,9 @@ public class JSONObject { } String key; final String name = method.getName(); - if (name.startsWith("get")) { + if (name.startsWith("get") && name.length() > 3) { key = name.substring(3); - } else if (name.startsWith("is")) { + } else if (name.startsWith("is") && name.length() > 2) { key = name.substring(2); } else { return null; @@ -1514,7 +1523,7 @@ public class JSONObject { // if the first letter in the key is not uppercase, then skip. // This is to maintain backwards compatibility before PR406 // (https://github.com/stleary/JSON-java/pull/406/) - if(key.isEmpty() || Character.isLowerCase(key.charAt(0))) { + if (Character.isLowerCase(key.charAt(0))) { return null; } if (key.length() == 1) { @@ -1568,8 +1577,8 @@ public class JSONObject { } try { - return getAnnotation(m.getDeclaringClass().getSuperclass().getMethod(m.getName(), - m.getParameterTypes()), + return getAnnotation( + c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), annotationClass); } catch (final SecurityException ex) { return null; @@ -1626,8 +1635,7 @@ public class JSONObject { try { int d = getAnnotationDepth( - m.getDeclaringClass().getSuperclass().getMethod(m.getName(), - m.getParameterTypes()), + c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), annotationClass); if (d > 0) { // since the annotation was on the superclass, add 1 From f4201cf318cff5fba56d1e1ef687ffb3f1a7d421 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 19 Mar 2018 09:34:13 -0400 Subject: [PATCH 379/451] Test cases for issue described in https://github.com/stleary/JSON-java/issues/410. --- src/test/java/org/json/junit/JSONPointerTest.java | 13 +++++++++++++ src/test/resources/jsonpointer-testdoc.json | 3 ++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index 19dac47..c4a8781 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -62,6 +62,19 @@ public class JSONPointerTest { assertSame(document.get(""), query("/")); } + @Test + public void queryByEmptyKeySubObject() { + assertSame(document.getJSONObject("obj").getJSONObject(""), query("/obj/")); + } + + @Test + public void queryByEmptyKeySubObjectSubOject() { + assertSame( + document.getJSONObject("obj").getJSONObject("").get(""), + query("/obj//") + ); + } + @Test public void slashEscaping() { assertSame(document.get("a/b"), query("/a~1b")); diff --git a/src/test/resources/jsonpointer-testdoc.json b/src/test/resources/jsonpointer-testdoc.json index d58fe82..6c1ce28 100644 --- a/src/test/resources/jsonpointer-testdoc.json +++ b/src/test/resources/jsonpointer-testdoc.json @@ -19,6 +19,7 @@ "another/key" : [ "val" ] - } + }, + "" : { "" : "empty key of an object with an empty key" } } } \ No newline at end of file From 43f3f5e80bb845db09e34ce467c38052b08866cf Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 19 Mar 2018 09:48:50 -0400 Subject: [PATCH 380/451] Add another test --- src/test/java/org/json/junit/JSONPointerTest.java | 8 ++++++++ src/test/resources/jsonpointer-testdoc.json | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index c4a8781..5ddd089 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -74,6 +74,14 @@ public class JSONPointerTest { query("/obj//") ); } + + @Test + public void queryByEmptyKeySubObjectValue() { + assertSame( + document.getJSONObject("obj").getJSONObject("").get("subKey"), + query("/obj//subKey") + ); + } @Test public void slashEscaping() { diff --git a/src/test/resources/jsonpointer-testdoc.json b/src/test/resources/jsonpointer-testdoc.json index 6c1ce28..657ccdd 100644 --- a/src/test/resources/jsonpointer-testdoc.json +++ b/src/test/resources/jsonpointer-testdoc.json @@ -20,6 +20,9 @@ "val" ] }, - "" : { "" : "empty key of an object with an empty key" } + "" : { + "" : "empty key of an object with an empty key", + "subKey" : "Some other value" + } } } \ No newline at end of file From 2362c930d19f33571de851bfa842cb7d0787ccb5 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 19 Mar 2018 09:33:09 -0400 Subject: [PATCH 381/451] Fixes #410. Invalid processing of trailing / for JSON Pointer --- JSONPointer.java | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/JSONPointer.java b/JSONPointer.java index 0040e17..fc0b04b 100644 --- a/JSONPointer.java +++ b/JSONPointer.java @@ -158,9 +158,28 @@ public class JSONPointer { throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'"); } this.refTokens = new ArrayList(); - for (String token : refs.split("/")) { - this.refTokens.add(unescape(token)); - } + int slashIdx = -1; + int prevSlashIdx = 0; + do { + prevSlashIdx = slashIdx + 1; + slashIdx = refs.indexOf('/', prevSlashIdx); + if(prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) { + // found 2 slashes in a row ( obj//next ) + // or single slash at the end of a string ( obj/test/ ) + this.refTokens.add(""); + } else if (slashIdx >= 0) { + final String token = refs.substring(prevSlashIdx, slashIdx); + this.refTokens.add(unescape(token)); + } else { + // last item after separator, or no separator at all. + final String token = refs.substring(prevSlashIdx); + this.refTokens.add(unescape(token)); + } + } while (slashIdx >= 0); + // using split does not take into account consecutive separators or "ending nulls" + //for (String token : refs.split("/")) { + // this.refTokens.add(unescape(token)); + //} } public JSONPointer(List refTokens) { From 3fe4a767e6665d8290eb1359c4a9e2d7a13e4997 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 20 Mar 2018 22:15:25 -0400 Subject: [PATCH 382/451] Fixes incorrect syntax for JSONPointer in test. --- src/test/java/org/json/junit/JSONObjectTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 303a19a..5dc31c7 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -667,7 +667,7 @@ public class JSONObjectTest { assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1/"))); + assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1"))); assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); From ca9df045394d36c2760db6f43f2244d81ef2164b Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 21 Mar 2018 21:47:21 -0400 Subject: [PATCH 383/451] Initial implementation of XMLParserConfig object for more flexible XML parsing --- XML.java | 105 +++++++++++++++++++++++++++++------- XMLParserConfiguration.java | 86 +++++++++++++++++++++++++++++ 2 files changed, 172 insertions(+), 19 deletions(-) create mode 100644 XMLParserConfiguration.java diff --git a/XML.java b/XML.java index 55362b2..73090fc 100644 --- a/XML.java +++ b/XML.java @@ -37,6 +37,7 @@ import java.util.Iterator; */ @SuppressWarnings("boxing") public class XML { + /** The Character '&'. */ public static final Character AMP = '&'; @@ -241,7 +242,7 @@ public class XML { * @return true if the close tag is processed. * @throws JSONException */ - private static boolean parse(XMLTokener x, JSONObject context, String name, boolean keepStrings) + private static boolean parse(XMLTokener x, JSONObject context, String name, XMLParserConfiguration config) throws JSONException { char c; int i; @@ -278,7 +279,7 @@ public class XML { if (x.next() == '[') { string = x.nextCDATA(); if (string.length() > 0) { - context.accumulate("content", string); + context.accumulate(config.cDataTagName, string); } return false; } @@ -341,7 +342,7 @@ public class XML { throw x.syntaxError("Missing value"); } jsonobject.accumulate(string, - keepStrings ? ((String)token) : stringToValue((String) token)); + config.keepStrings ? ((String)token) : stringToValue((String) token)); token = null; } else { jsonobject.accumulate(string, ""); @@ -372,19 +373,19 @@ public class XML { } else if (token instanceof String) { string = (String) token; if (string.length() > 0) { - jsonobject.accumulate("content", - keepStrings ? string : stringToValue(string)); + jsonobject.accumulate(config.cDataTagName, + config.keepStrings ? string : stringToValue(string)); } } else if (token == LT) { // Nested element - if (parse(x, jsonobject, tagName,keepStrings)) { + if (parse(x, jsonobject, tagName, config)) { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); } else if (jsonobject.length() == 1 - && jsonobject.opt("content") != null) { + && jsonobject.opt(config.cDataTagName) != null) { context.accumulate(tagName, - jsonobject.opt("content")); + jsonobject.opt(config.cDataTagName)); } else { context.accumulate(tagName, jsonobject); } @@ -469,7 +470,7 @@ public class XML { * @throws JSONException Thrown if there is an errors while parsing the string */ public static JSONObject toJSONObject(String string) throws JSONException { - return toJSONObject(string, false); + return toJSONObject(string, XMLParserConfiguration.ORIGINAL); } /** @@ -488,7 +489,7 @@ public class XML { * @throws JSONException Thrown if there is an errors while parsing the string */ public static JSONObject toJSONObject(Reader reader) throws JSONException { - return toJSONObject(reader, false); + return toJSONObject(reader, XMLParserConfiguration.ORIGINAL); } /** @@ -512,12 +513,38 @@ public class XML { * @throws JSONException Thrown if there is an errors while parsing the string */ public static JSONObject toJSONObject(Reader reader, boolean keepStrings) throws JSONException { + if(keepStrings) { + return toJSONObject(reader, XMLParserConfiguration.KEEP_STRINGS); + } + return toJSONObject(reader, XMLParserConfiguration.ORIGINAL); + } + + /** + * Convert a well-formed (but not necessarily valid) XML into a + * JSONObject. Some information may be lost in this transformation because + * JSON is a data format and XML is a document format. XML uses elements, + * attributes, and content text, while JSON uses unordered collections of + * name/value pairs and arrays of values. JSON does not does not like to + * distinguish between elements and attributes. Sequences of similar + * elements are represented as JSONArrays. Content text may be placed in a + * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * are ignored. + * + * All values are converted as strings, for 1, 01, 29.0 will not be coerced to + * numbers but will instead be the exact value as seen in the XML document. + * + * @param reader The XML source reader. + * @param config Configuration options for the parser + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException Thrown if there is an errors while parsing the string + */ + public static JSONObject toJSONObject(Reader reader, XMLParserConfiguration config) throws JSONException { JSONObject jo = new JSONObject(); XMLTokener x = new XMLTokener(reader); while (x.more()) { x.skipPast("<"); if(x.more()) { - parse(x, jo, null, keepStrings); + parse(x, jo, null, config); } } return jo; @@ -548,6 +575,30 @@ public class XML { return toJSONObject(new StringReader(string), keepStrings); } + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject. Some information may be lost in this transformation because + * JSON is a data format and XML is a document format. XML uses elements, + * attributes, and content text, while JSON uses unordered collections of + * name/value pairs and arrays of values. JSON does not does not like to + * distinguish between elements and attributes. Sequences of similar + * elements are represented as JSONArrays. Content text may be placed in a + * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * are ignored. + * + * All values are converted as strings, for 1, 01, 29.0 will not be coerced to + * numbers but will instead be the exact value as seen in the XML document. + * + * @param string + * The source string. + * @param config Configuration options for the parser. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException Thrown if there is an errors while parsing the string + */ + public static JSONObject toJSONObject(String string, XMLParserConfiguration config) throws JSONException { + return toJSONObject(new StringReader(string), config); + } + /** * Convert a JSONObject into a well-formed, element-normal XML string. * @@ -557,9 +608,9 @@ public class XML { * @throws JSONException Thrown if there is an error parsing the string */ public static String toString(Object object) throws JSONException { - return toString(object, null); + return toString(object, null, XMLParserConfiguration.ORIGINAL); } - + /** * Convert a JSONObject into a well-formed, element-normal XML string. * @@ -570,7 +621,23 @@ public class XML { * @return A string. * @throws JSONException Thrown if there is an error parsing the string */ - public static String toString(final Object object, final String tagName) + public static String toString(final Object object, final String tagName) { + return toString(object, tagName, XMLParserConfiguration.ORIGINAL); + } + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * + * @param object + * A JSONObject. + * @param tagName + * The optional name of the enclosing tag. + * @param config + * Configuration that can control output to XML. + * @return A string. + * @throws JSONException Thrown if there is an error parsing the string + */ + public static String toString(final Object object, final String tagName, final XMLParserConfiguration config) throws JSONException { StringBuilder sb = new StringBuilder(); JSONArray ja; @@ -598,7 +665,7 @@ public class XML { } // Emit content in body - if ("content".equals(key)) { + if (key.equals(config.cDataTagName)) { if (value instanceof JSONArray) { ja = (JSONArray) value; int jaLength = ja.length(); @@ -626,12 +693,12 @@ public class XML { sb.append('<'); sb.append(key); sb.append('>'); - sb.append(toString(val)); + sb.append(toString(val, null, config)); sb.append("'); } else { - sb.append(toString(val, key)); + sb.append(toString(val, key, config)); } } } else if ("".equals(value)) { @@ -642,7 +709,7 @@ public class XML { // Emit a new tag } else { - sb.append(toString(value, key)); + sb.append(toString(value, key, config)); } } if (tagName != null) { @@ -669,7 +736,7 @@ public class XML { // XML does not have good support for arrays. If an array // appears in a place where XML is lacking, synthesize an // element. - sb.append(toString(val, tagName == null ? "array" : tagName)); + sb.append(toString(val, tagName == null ? "array" : tagName, config)); } return sb.toString(); } diff --git a/XMLParserConfiguration.java b/XMLParserConfiguration.java new file mode 100644 index 0000000..45af175 --- /dev/null +++ b/XMLParserConfiguration.java @@ -0,0 +1,86 @@ +package org.json; +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * Configuration object for the XML parser. + * @author AylwardJ + * + */ +public class XMLParserConfiguration { + /** Original Configuration of the XML Parser. */ + public static final XMLParserConfiguration ORIGINAL = new XMLParserConfiguration(); + /** Original configuration of the XML Parser except that values are kept as strings. */ + public static final XMLParserConfiguration KEEP_STRINGS = new XMLParserConfiguration(true); + /** + * When parsing the XML into JSON, specifies if values should be kept as strings (true), or if + * they should try to be guessed into JSON values (numeric, boolean, string) + */ + public final boolean keepStrings; + /** + * The name of the key in a JSON Object that indicates a CDATA section. Historically this has + * been the value "content" but can be changed. Use null to indicate no CDATA + * processing. + */ + public final String cDataTagName; + + /** + * Default parser configuration. Does not keep strings, and the CDATA Tag Name is "content". + */ + public XMLParserConfiguration () { + this(false, "content"); + } + + /** + * Configure the parser string processing and use the default CDATA Tag Name as "content". + * @param keepStrings true to parse all values as string. + * false to try and convert XML string values into a JSON value. + */ + public XMLParserConfiguration (final boolean keepStrings) { + this(keepStrings, "content"); + } + + /** + * Configure the parser string processing to try and convert XML values to JSON values and + * use the passed CDATA Tag Name the processing value. Pass null to + * disable CDATA processing + * @param cDataTagNamenull to disable CDATA processing. Any other value + * to use that value as the JSONObject key name to process as CDATA. + */ + public XMLParserConfiguration (final String cDataTagName) { + this(false, cDataTagName); + } + + /** + * Configure the parser to use custom settings. + * @param keepStrings true to parse all values as string. + * false to try and convert XML string values into a JSON value. + * @param cDataTagNamenull to disable CDATA processing. Any other value + * to use that value as the JSONObject key name to process as CDATA. + */ + public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName) { + this.keepStrings = keepStrings; + this.cDataTagName = cDataTagName; + } +} From a6284df9c7dde5ba4b2e803e6538ef83b4406ab7 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 2 May 2018 20:28:45 -0500 Subject: [PATCH 384/451] initial commit --- JSONWriter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JSONWriter.java b/JSONWriter.java index ac5a805..e487781 100644 --- a/JSONWriter.java +++ b/JSONWriter.java @@ -391,7 +391,7 @@ public class JSONWriter { * @throws JSONException If the number is not finite. */ public JSONWriter value(double d) throws JSONException { - return this.value(new Double(d)); + return this.value(Double.valueOf(d)); } /** From a490ebdb7852768364a9e577f89c3871c4d3392c Mon Sep 17 00:00:00 2001 From: Andrei Paikin Date: Sat, 19 May 2018 09:42:21 +0300 Subject: [PATCH 385/451] add isEmpty and isNotEmpty methods --- JSONObject.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/JSONObject.java b/JSONObject.java index d18a556..a6ece64 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -963,6 +963,24 @@ public class JSONObject { return this.map.size(); } + /** + * Check if JSONObject is empty. + * + * @return true if JSONObject is empty, otherwise false. + */ + public boolean isEmpty() { + return map.isEmpty(); + } + + /** + * Check if JSONObject is not empty. + * + * @return true if JSONObject is not empty, otherwise false. + */ + public boolean isNotEmpty() { + return !map.isEmpty(); + } + /** * Produce a JSONArray containing the names of the elements of this * JSONObject. From 05074386d3582e9ea98148eaf6fd44eeaca964da Mon Sep 17 00:00:00 2001 From: Andrei_Paikin Date: Mon, 21 May 2018 16:58:13 +0300 Subject: [PATCH 386/451] change length comparison to isEmpty method --- CDL.java | 6 +++--- JSONArray.java | 12 +++++++++++- JSONML.java | 4 ++-- JSONObject.java | 18 ++++-------------- XML.java | 10 +++++----- 5 files changed, 25 insertions(+), 25 deletions(-) diff --git a/CDL.java b/CDL.java index 1c7df32..5f907bf 100644 --- a/CDL.java +++ b/CDL.java @@ -224,7 +224,7 @@ public class CDL { */ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException { - if (names == null || names.length() == 0) { + if (names == null || names.isEmpty()) { return null; } JSONArray ja = new JSONArray(); @@ -235,7 +235,7 @@ public class CDL { } ja.put(jo); } - if (ja.length() == 0) { + if (ja.isEmpty()) { return null; } return ja; @@ -272,7 +272,7 @@ public class CDL { */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { - if (names == null || names.length() == 0) { + if (names == null || names.isEmpty()) { return null; } StringBuffer sb = new StringBuffer(); diff --git a/JSONArray.java b/JSONArray.java index 421dd93..fbc1a0f 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1352,7 +1352,7 @@ public class JSONArray implements Iterable { * If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { - if (names == null || names.length() == 0 || this.length() == 0) { + if (names == null || names.isEmpty() || this.isEmpty()) { return null; } JSONObject jo = new JSONObject(names.length()); @@ -1528,4 +1528,14 @@ public class JSONArray implements Iterable { } return results; } + + /** + * Check if JSONArray is empty. + * + * @return true if JSONArray is empty, otherwise false. + */ + public boolean isEmpty() { + return myArrayList.isEmpty(); + } + } diff --git a/JSONML.java b/JSONML.java index acec7b8..f639050 100644 --- a/JSONML.java +++ b/JSONML.java @@ -178,7 +178,7 @@ public class JSONML { newjo.accumulate(attribute, ""); } } - if (arrayForm && newjo.length() > 0) { + if (arrayForm && !newjo.isEmpty()) { newja.put(newjo); } @@ -208,7 +208,7 @@ public class JSONML { "' and '" + closeTag + "'"); } tagName = null; - if (!arrayForm && newja.length() > 0) { + if (!arrayForm && !newja.isEmpty()) { newjo.put("childNodes", newja); } if (ja == null) { diff --git a/JSONObject.java b/JSONObject.java index a6ece64..8deb6ba 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -810,11 +810,10 @@ public class JSONObject { * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { - int length = jo.length(); - if (length == 0) { + if (jo.isEmpty()) { return null; } - return jo.keySet().toArray(new String[length]); + return jo.keySet().toArray(new String[jo.length()]); } /** @@ -972,15 +971,6 @@ public class JSONObject { return map.isEmpty(); } - /** - * Check if JSONObject is not empty. - * - * @return true if JSONObject is not empty, otherwise false. - */ - public boolean isNotEmpty() { - return !map.isEmpty(); - } - /** * Produce a JSONArray containing the names of the elements of this * JSONObject. @@ -1966,7 +1956,7 @@ public class JSONObject { } public static Writer quote(String string, Writer w) throws IOException { - if (string == null || string.length() == 0) { + if (string == null || string.isEmpty()) { w.write("\"\""); return w; } @@ -2245,7 +2235,7 @@ public class JSONObject { * If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.length() == 0) { + if (names == null || names.isEmpty()) { return null; } JSONArray ja = new JSONArray(); diff --git a/XML.java b/XML.java index 55362b2..f3eaa15 100644 --- a/XML.java +++ b/XML.java @@ -277,7 +277,7 @@ public class XML { if ("CDATA".equals(token)) { if (x.next() == '[') { string = x.nextCDATA(); - if (string.length() > 0) { + if (!string.isEmpty()) { context.accumulate("content", string); } return false; @@ -353,7 +353,7 @@ public class XML { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } - if (jsonobject.length() > 0) { + if (!jsonobject.isEmpty()) { context.accumulate(tagName, jsonobject); } else { context.accumulate(tagName, ""); @@ -371,7 +371,7 @@ public class XML { return false; } else if (token instanceof String) { string = (String) token; - if (string.length() > 0) { + if (!string.isEmpty()) { jsonobject.accumulate("content", keepStrings ? string : stringToValue(string)); } @@ -379,7 +379,7 @@ public class XML { } else if (token == LT) { // Nested element if (parse(x, jsonobject, tagName,keepStrings)) { - if (jsonobject.length() == 0) { + if (jsonobject.isEmpty()) { context.accumulate(tagName, ""); } else if (jsonobject.length() == 1 && jsonobject.opt("content") != null) { @@ -676,7 +676,7 @@ public class XML { string = (object == null) ? "null" : escape(object.toString()); return (tagName == null) ? "\"" + string + "\"" - : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + : (string.isEmpty()) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + ""; } From 7cad4c3b262f2bb052f6c813f725b74285dce871 Mon Sep 17 00:00:00 2001 From: Andrei Paikin Date: Fri, 25 May 2018 22:17:03 +0300 Subject: [PATCH 387/451] partially revert changes --- CDL.java | 6 +++--- JSONML.java | 4 ++-- XML.java | 10 +++++----- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/CDL.java b/CDL.java index 5f907bf..1c7df32 100644 --- a/CDL.java +++ b/CDL.java @@ -224,7 +224,7 @@ public class CDL { */ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException { - if (names == null || names.isEmpty()) { + if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); @@ -235,7 +235,7 @@ public class CDL { } ja.put(jo); } - if (ja.isEmpty()) { + if (ja.length() == 0) { return null; } return ja; @@ -272,7 +272,7 @@ public class CDL { */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { - if (names == null || names.isEmpty()) { + if (names == null || names.length() == 0) { return null; } StringBuffer sb = new StringBuffer(); diff --git a/JSONML.java b/JSONML.java index f639050..acec7b8 100644 --- a/JSONML.java +++ b/JSONML.java @@ -178,7 +178,7 @@ public class JSONML { newjo.accumulate(attribute, ""); } } - if (arrayForm && !newjo.isEmpty()) { + if (arrayForm && newjo.length() > 0) { newja.put(newjo); } @@ -208,7 +208,7 @@ public class JSONML { "' and '" + closeTag + "'"); } tagName = null; - if (!arrayForm && !newja.isEmpty()) { + if (!arrayForm && newja.length() > 0) { newjo.put("childNodes", newja); } if (ja == null) { diff --git a/XML.java b/XML.java index f3eaa15..55362b2 100644 --- a/XML.java +++ b/XML.java @@ -277,7 +277,7 @@ public class XML { if ("CDATA".equals(token)) { if (x.next() == '[') { string = x.nextCDATA(); - if (!string.isEmpty()) { + if (string.length() > 0) { context.accumulate("content", string); } return false; @@ -353,7 +353,7 @@ public class XML { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } - if (!jsonobject.isEmpty()) { + if (jsonobject.length() > 0) { context.accumulate(tagName, jsonobject); } else { context.accumulate(tagName, ""); @@ -371,7 +371,7 @@ public class XML { return false; } else if (token instanceof String) { string = (String) token; - if (!string.isEmpty()) { + if (string.length() > 0) { jsonobject.accumulate("content", keepStrings ? string : stringToValue(string)); } @@ -379,7 +379,7 @@ public class XML { } else if (token == LT) { // Nested element if (parse(x, jsonobject, tagName,keepStrings)) { - if (jsonobject.isEmpty()) { + if (jsonobject.length() == 0) { context.accumulate(tagName, ""); } else if (jsonobject.length() == 1 && jsonobject.opt("content") != null) { @@ -676,7 +676,7 @@ public class XML { string = (object == null) ? "null" : escape(object.toString()); return (tagName == null) ? "\"" + string + "\"" - : (string.isEmpty()) ? "<" + tagName + "/>" : "<" + tagName + : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + ""; } From d00501eabd9b60c8097fd466b99796b27fbdb7e9 Mon Sep 17 00:00:00 2001 From: Andrei Paikin Date: Fri, 25 May 2018 22:47:05 +0300 Subject: [PATCH 388/451] add usage of isEmpty method --- src/test/java/org/json/junit/CookieListTest.java | 2 +- src/test/java/org/json/junit/EnumTest.java | 2 +- src/test/java/org/json/junit/JSONArrayTest.java | 2 +- src/test/java/org/json/junit/JSONObjectTest.java | 16 ++++++++-------- src/test/java/org/json/junit/PropertyTest.java | 4 ++-- src/test/java/org/json/junit/XMLTest.java | 8 ++++---- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/test/java/org/json/junit/CookieListTest.java b/src/test/java/org/json/junit/CookieListTest.java index 80cbaa8..7149644 100644 --- a/src/test/java/org/json/junit/CookieListTest.java +++ b/src/test/java/org/json/junit/CookieListTest.java @@ -65,7 +65,7 @@ public class CookieListTest { public void emptyStringCookieList() { String cookieStr = ""; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); - assertTrue(jsonObject.length() == 0); + assertTrue(jsonObject.isEmpty()); } /** diff --git a/src/test/java/org/json/junit/EnumTest.java b/src/test/java/org/json/junit/EnumTest.java index cd0d8c0..366643e 100644 --- a/src/test/java/org/json/junit/EnumTest.java +++ b/src/test/java/org/json/junit/EnumTest.java @@ -35,7 +35,7 @@ public class EnumTest { // If there are no getters then the object is empty. MyEnum myEnum = MyEnum.VAL2; JSONObject jsonObject = new JSONObject(myEnum); - assertTrue("simple enum has no getters", jsonObject.length() == 0); + assertTrue("simple enum has no getters", jsonObject.isEmpty()); // enum with a getters should create a non-empty object MyEnumField myEnumField = MyEnumField.VAL2; diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 8a31c87..845f4e7 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -691,7 +691,7 @@ public class JSONArrayTest { JSONArray jsonArray = new JSONArray(arrayStr1); jsonArray.remove(0); assertTrue("array should be empty", null == jsonArray.remove(5)); - assertTrue("jsonArray should be empty", jsonArray.length() == 0); + assertTrue("jsonArray should be empty", jsonArray.isEmpty()); } /** diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 5dc31c7..e3b9529 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -141,7 +141,7 @@ public class JSONObjectTest { @Test public void emptyJsonObject() { JSONObject jsonObject = new JSONObject(); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("jsonObject should be empty", jsonObject.isEmpty()); } /** @@ -184,7 +184,7 @@ public class JSONObjectTest { public void jsonObjectByNullMap() { Map map = null; JSONObject jsonObject = new JSONObject(map); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("jsonObject should be empty", jsonObject.isEmpty()); } /** @@ -1122,7 +1122,7 @@ public class JSONObjectTest { BigDecimal bigDecimal = new BigDecimal( "123456789012345678901234567890.12345678901234567890123456789"); jsonObject = new JSONObject(bigDecimal); - assertTrue("large bigDecimal is not stored", jsonObject.length() == 0); + assertTrue("large bigDecimal is not stored", jsonObject.isEmpty()); /** * JSONObject put(String, Object) method stores and serializes @@ -2244,11 +2244,11 @@ public class JSONObjectTest { public void jsonObjectPutOnceNull() { JSONObject jsonObject = new JSONObject(); jsonObject.putOnce(null, null); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("jsonObject should be empty", jsonObject.isEmpty()); jsonObject.putOnce("", null); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("jsonObject should be empty", jsonObject.isEmpty()); jsonObject.putOnce(null, ""); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("jsonObject should be empty", jsonObject.isEmpty()); } /** @@ -2424,11 +2424,11 @@ public class JSONObjectTest { String str = "{\"myKey\": \"myval\"}"; JSONObject jsonObjectRemove = new JSONObject(str); jsonObjectRemove.remove("myKey"); - assertEquals("jsonObject should be empty",0 ,jsonObjectRemove.length()); + assertTrue("jsonObject should be empty", jsonObjectRemove.isEmpty()); JSONObject jsonObjectPutNull = new JSONObject(str); jsonObjectPutNull.put("myKey", (Object) null); - assertEquals("jsonObject should be empty",0 ,jsonObjectPutNull.length()); + assertTrue("jsonObject should be empty", jsonObjectPutNull.isEmpty()); } diff --git a/src/test/java/org/json/junit/PropertyTest.java b/src/test/java/org/json/junit/PropertyTest.java index 60d3eb5..8804284 100644 --- a/src/test/java/org/json/junit/PropertyTest.java +++ b/src/test/java/org/json/junit/PropertyTest.java @@ -21,7 +21,7 @@ public class PropertyTest { public void shouldHandleNullProperties() { Properties properties = null; JSONObject jsonObject = Property.toJSONObject(properties); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("jsonObject should be empty", jsonObject.isEmpty()); } /** @@ -32,7 +32,7 @@ public class PropertyTest { public void shouldHandleEmptyProperties() { Properties properties = new Properties(); JSONObject jsonObject = Property.toJSONObject(properties); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("jsonObject should be empty", jsonObject.isEmpty()); } /** diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index c34bf0f..651d1a7 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -34,7 +34,7 @@ public class XMLTest { public void shouldHandleNullXML() { String xmlStr = null; JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("jsonObject should be empty", jsonObject.isEmpty()); } /** @@ -45,7 +45,7 @@ public class XMLTest { String xmlStr = ""; JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue("jsonObject should be empty", jsonObject.length() == 0); + assertTrue("jsonObject should be empty", jsonObject.isEmpty()); } /** @@ -55,7 +55,7 @@ public class XMLTest { public void shouldHandleNonXML() { String xmlStr = "{ \"this is\": \"not xml\"}"; JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue("xml string should be empty", jsonObject.length() == 0); + assertTrue("xml string should be empty", jsonObject.isEmpty()); } /** @@ -200,7 +200,7 @@ public class XMLTest { public void shouldHandleEmptyJSONXML() { JSONObject jsonObject= new JSONObject(); String xmlStr = XML.toString(jsonObject); - assertTrue("xml string should be empty", xmlStr.length() == 0); + assertTrue("xml string should be empty", xmlStr.isEmpty()); } /** From 37f5bf28e96d9dee03a4b97728cc2976f9c248c7 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 13 Aug 2018 20:46:20 -0500 Subject: [PATCH 389/451] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index e66f3c6..c7ecb24 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,8 @@ invalid number formats (1.2e6.3) will cause errors as such documents can not be Release history: ~~~ +20180813 POM change to include Automatic-Module-Name (#431) + 20180130 Recent commits 20171018 Checkpoint for recent commits. From b8a3342eb199f30569eccb81cc3626392284ddd6 Mon Sep 17 00:00:00 2001 From: johnjaylward Date: Wed, 15 Aug 2018 09:18:14 -0400 Subject: [PATCH 390/451] Update README.md update maven search example. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c7ecb24..82ffedc 100644 --- a/README.md +++ b/README.md @@ -133,4 +133,4 @@ as of 29 July, 2015. JSON-java releases can be found by searching the Maven repository for groupId "org.json" and artifactId "json". For example: -https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.json%22%20AND%20a%3A%22json%22 +https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav From 3b8b0a681c349f12ea83b490927c0da219a7550d Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 2 Oct 2018 12:38:17 -0400 Subject: [PATCH 391/451] Update test cases to verify performance change and verify opt/getBigDecimal match --- .../java/org/json/junit/JSONObjectTest.java | 95 +++++++++++++++++-- 1 file changed, 86 insertions(+), 9 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index e3b9529..63385a5 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -24,6 +24,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Pattern; import org.json.CDL; import org.json.JSONArray; @@ -60,7 +61,13 @@ import com.jayway.jsonpath.JsonPath; * otherwise be impossible. */ public class JSONObjectTest { - + + /** + * Regular Expression Pattern that matches JSON Numbers. This is primarily used for + * output to guarantee that we are always writing valid JSON. + */ + static final Pattern NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?"); + /** * Tests that the similar method is working as expected. */ @@ -87,6 +94,67 @@ public class JSONObjectTest { assertTrue("Should eval to true", obj1.similar(obj3)); } + + @Test + public void timeNumberParsing() { + // test data to use + final String[] testData = new String[] { + null, + "", + "100", + "-100", + "abc123", + "012345", + "100.5e199", + "-100.5e199", + "DEADBEEF", + "0xDEADBEEF", + "1234567890.1234567890", + "-1234567890.1234567890", + "adloghakuidghauiehgauioehgdkjfb nsruoh aeu noerty384 nkljfgh " + + "395h tdfn kdz8yt3 4hkls gn.ey85 4hzfhnz.o8y5a84 onvklt " + + "yh389thub nkz8y49lihv al4itlaithknty8hnbl" + // long (in length) number sequences with invalid data at the end of the + // string offer very poor performance for the REGEX. + ,"123467890123467890123467890123467890123467890123467890123467" + + "8901234678901234678901234678901234678901234678901234678" + + "9012346789012346789012346789012346789012346789012346789" + + "0a" + }; + final int testDataLength = testData.length; + final int iterations = 1000000; + + // 10 million iterations 1,000,000 * 10 + long startTime = System.nanoTime(); + for(int i = 0; i < iterations; i++) { + for(int j = 0; j < testDataLength; j++) { + try { + BigDecimal v1 = new BigDecimal(testData[j]); + v1.signum(); + } catch(Exception ignore) { + //do nothing + } + } + } + final long elapsedNano1 = System.nanoTime() - startTime; + System.out.println("new BigDecimal(testData[]) : " + elapsedNano1 / 1000000 + " ms"); + + startTime = System.nanoTime(); + for(int i = 0; i < iterations; i++) { + for(int j = 0; j < testDataLength; j++) { + try { + boolean v2 = NUMBER_PATTERN.matcher(testData[j]).matches(); + assert v2 == !!v2; + } catch(Exception ignore) { + //do nothing + } + } + } + final long elapsedNano2 = System.nanoTime() - startTime; + System.out.println("NUMBER_PATTERN.matcher(testData[]).matches() : " + elapsedNano2 / 1000000 + " ms"); + // don't assert normally as the testing is machine dependent. + // assertTrue("Expected Pattern matching to be faster than BigDecimal constructor",elapsedNano2 Date: Tue, 2 Oct 2018 12:37:15 -0400 Subject: [PATCH 392/451] * Fixes opt/getBigDecimal to be consistent * Performance: Updates JSONWriter to use a regex to decide if writing as a number is best. --- JSONArray.java | 64 +++++++--------------------------------- JSONObject.java | 78 ++++++++++++++++++++++++++++++++++--------------- JSONWriter.java | 12 +++----- 3 files changed, 69 insertions(+), 85 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index fbc1a0f..dd22046 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -345,12 +345,12 @@ public class JSONArray implements Iterable { */ public BigDecimal getBigDecimal (int index) throws JSONException { Object object = this.get(index); - try { - return new BigDecimal(object.toString()); - } catch (Exception e) { + BigDecimal val = JSONObject.objectToBigDecimal(object, null); + if(val == null) { throw new JSONException("JSONArray[" + index + - "] could not convert to BigDecimal.", e); + "] could not convert to BigDecimal ("+ object + ")."); } + return val; } /** @@ -365,12 +365,12 @@ public class JSONArray implements Iterable { */ public BigInteger getBigInteger (int index) throws JSONException { Object object = this.get(index); - try { - return new BigInteger(object.toString()); - } catch (Exception e) { + BigInteger val = JSONObject.objectToBigInteger(object, null); + if(val == null) { throw new JSONException("JSONArray[" + index + - "] could not convert to BigInteger.", e); + "] could not convert to BigDecimal ("+ object + ")."); } + return val; } /** @@ -739,31 +739,7 @@ public class JSONArray implements Iterable { */ public BigInteger optBigInteger(int index, BigInteger defaultValue) { Object val = this.opt(index); - if (JSONObject.NULL.equals(val)) { - return defaultValue; - } - if (val instanceof BigInteger){ - return (BigInteger) val; - } - if (val instanceof BigDecimal){ - return ((BigDecimal) val).toBigInteger(); - } - if (val instanceof Double || val instanceof Float){ - return new BigDecimal(((Number) val).doubleValue()).toBigInteger(); - } - if (val instanceof Long || val instanceof Integer - || val instanceof Short || val instanceof Byte){ - return BigInteger.valueOf(((Number) val).longValue()); - } - try { - final String valStr = val.toString(); - if(JSONObject.isDecimalNotation(valStr)) { - return new BigDecimal(valStr).toBigInteger(); - } - return new BigInteger(valStr); - } catch (Exception e) { - return defaultValue; - } + return JSONObject.objectToBigInteger(val, defaultValue); } /** @@ -779,27 +755,7 @@ public class JSONArray implements Iterable { */ public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { Object val = this.opt(index); - if (JSONObject.NULL.equals(val)) { - return defaultValue; - } - if (val instanceof BigDecimal){ - return (BigDecimal) val; - } - if (val instanceof BigInteger){ - return new BigDecimal((BigInteger) val); - } - if (val instanceof Double || val instanceof Float){ - return new BigDecimal(((Number) val).doubleValue()); - } - if (val instanceof Long || val instanceof Integer - || val instanceof Short || val instanceof Byte){ - return new BigDecimal(((Number) val).longValue()); - } - try { - return new BigDecimal(val.toString()); - } catch (Exception e) { - return defaultValue; - } + return JSONObject.objectToBigDecimal(val, defaultValue); } /** diff --git a/JSONObject.java b/JSONObject.java index 8deb6ba..1a9b9de 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -45,6 +45,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; +import java.util.regex.Pattern; /** * A JSONObject is an unordered collection of name/value pairs. Its external @@ -150,6 +151,12 @@ public class JSONObject { return "null"; } } + + /** + * Regular Expression Pattern that matches JSON Numbers. This is primarily used for + * output to guarantee that we are always writing valid JSON. + */ + static final Pattern NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?"); /** * The map where the JSONObject's properties are kept. @@ -630,16 +637,19 @@ public class JSONObject { */ public BigInteger getBigInteger(String key) throws JSONException { Object object = this.get(key); - try { - return new BigInteger(object.toString()); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] could not be converted to BigInteger.", e); + BigInteger ret = objectToBigInteger(object, null); + if (ret != null) { + return ret; } + throw new JSONException("JSONObject[" + quote(key) + + "] could not be converted to BigInteger (" + object + ")."); } /** - * Get the BigDecimal value associated with a key. + * Get the BigDecimal value associated with a key. If the value is float or + * double, the the {@link BigDecimal#BigDecimal(double)} constructor will + * be used. See notes on the constructor for conversion issues that may + * arise. * * @param key * A key string. @@ -650,15 +660,12 @@ public class JSONObject { */ public BigDecimal getBigDecimal(String key) throws JSONException { Object object = this.get(key); - if (object instanceof BigDecimal) { - return (BigDecimal)object; - } - try { - return new BigDecimal(object.toString()); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] could not be converted to BigDecimal.", e); + BigDecimal ret = objectToBigDecimal(object, null); + if (ret != null) { + return ret; } + throw new JSONException("JSONObject[" + quote(key) + + "] could not be converted to BigDecimal (" + object + ")."); } /** @@ -968,7 +975,7 @@ public class JSONObject { * @return true if JSONObject is empty, otherwise false. */ public boolean isEmpty() { - return map.isEmpty(); + return this.map.isEmpty(); } /** @@ -1113,7 +1120,10 @@ public class JSONObject { /** * Get an optional BigDecimal associated with a key, or the defaultValue if * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. + * string, an attempt will be made to evaluate it as a number. If the value + * is float or double, then the {@link BigDecimal#BigDecimal(double)} + * constructor will be used. See notes on the constructor for conversion + * issues that may arise. * * @param key * A key string. @@ -1123,6 +1133,15 @@ public class JSONObject { */ public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { Object val = this.opt(key); + return objectToBigDecimal(val, defaultValue); + } + + /** + * @param defaultValue + * @param val + * @return + */ + static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue) { if (NULL.equals(val)) { return defaultValue; } @@ -1133,6 +1152,10 @@ public class JSONObject { return new BigDecimal((BigInteger) val); } if (val instanceof Double || val instanceof Float){ + final double d = ((Number) val).doubleValue(); + if(Double.isNaN(d)) { + return defaultValue; + } return new BigDecimal(((Number) val).doubleValue()); } if (val instanceof Long || val instanceof Integer @@ -1160,6 +1183,15 @@ public class JSONObject { */ public BigInteger optBigInteger(String key, BigInteger defaultValue) { Object val = this.opt(key); + return objectToBigInteger(val, defaultValue); + } + + /** + * @param defaultValue + * @param val + * @return + */ + static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { if (NULL.equals(val)) { return defaultValue; } @@ -1170,7 +1202,11 @@ public class JSONObject { return ((BigDecimal) val).toBigInteger(); } if (val instanceof Double || val instanceof Float){ - return new BigDecimal(((Number) val).doubleValue()).toBigInteger(); + final double d = ((Number) val).doubleValue(); + if(Double.isNaN(d)) { + return defaultValue; + } + return new BigDecimal(d).toBigInteger(); } if (val instanceof Long || val instanceof Integer || val instanceof Short || val instanceof Byte){ @@ -2414,13 +2450,9 @@ public class JSONObject { } else if (value instanceof Number) { // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary final String numberAsString = numberToString((Number) value); - try { - // Use the BigDecimal constructor for its parser to validate the format. - @SuppressWarnings("unused") - BigDecimal testNum = new BigDecimal(numberAsString); - // Close enough to a JSON number that we will use it unquoted + if(NUMBER_PATTERN.matcher(numberAsString).matches()) { writer.write(numberAsString); - } catch (NumberFormatException ex){ + } else { // The Number value is not a valid JSON number. // Instead we will quote it as a string quote(numberAsString, writer); diff --git a/JSONWriter.java b/JSONWriter.java index e487781..8ef6084 100644 --- a/JSONWriter.java +++ b/JSONWriter.java @@ -340,17 +340,13 @@ public class JSONWriter { if (value instanceof Number) { // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex final String numberAsString = JSONObject.numberToString((Number) value); - try { - // Use the BigDecimal constructor for it's parser to validate the format. - @SuppressWarnings("unused") - BigDecimal unused = new BigDecimal(numberAsString); + if(JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) { // Close enough to a JSON number that we will return it unquoted return numberAsString; - } catch (NumberFormatException ex){ - // The Number value is not a valid JSON number. - // Instead we will quote it as a string - return JSONObject.quote(numberAsString); } + // The Number value is not a valid JSON number. + // Instead we will quote it as a string + return JSONObject.quote(numberAsString); } if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { From bc347d2c19311db90925f187f6b6a5ae422e3af2 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 2 Oct 2018 13:14:22 -0400 Subject: [PATCH 393/451] cleanup of minor warnings --- JSONArray.java | 2 +- JSONPointer.java | 4 ++-- JSONWriter.java | 1 - XMLTokener.java | 2 +- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index dd22046..9314438 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1491,7 +1491,7 @@ public class JSONArray implements Iterable { * @return true if JSONArray is empty, otherwise false. */ public boolean isEmpty() { - return myArrayList.isEmpty(); + return this.myArrayList.isEmpty(); } } diff --git a/JSONPointer.java b/JSONPointer.java index fc0b04b..df06f22 100644 --- a/JSONPointer.java +++ b/JSONPointer.java @@ -233,8 +233,8 @@ public class JSONPointer { int index = Integer.parseInt(indexToken); JSONArray currentArr = (JSONArray) current; if (index >= currentArr.length()) { - throw new JSONPointerException(format("index %d is out of bounds - the array has %d elements", index, - currentArr.length())); + throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", indexToken, + Integer.valueOf(currentArr.length()))); } try { return currentArr.get(index); diff --git a/JSONWriter.java b/JSONWriter.java index 8ef6084..a30a222 100644 --- a/JSONWriter.java +++ b/JSONWriter.java @@ -1,7 +1,6 @@ package org.json; import java.io.IOException; -import java.math.BigDecimal; import java.util.Collection; import java.util.Map; diff --git a/XMLTokener.java b/XMLTokener.java index 50e3acc..8490bec 100644 --- a/XMLTokener.java +++ b/XMLTokener.java @@ -135,7 +135,7 @@ public class XMLTokener extends JSONTokener { * @return A Character or an entity String if the entity is not recognized. * @throws JSONException If missing ';' in XML entity. */ - public Object nextEntity(char ampersand) throws JSONException { + public Object nextEntity(@SuppressWarnings("unused") char ampersand) throws JSONException { StringBuilder sb = new StringBuilder(); for (;;) { char c = next(); From 30c1bd16bac7ceb41bce719b44faf22b465c9907 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 2 Oct 2018 13:38:19 -0400 Subject: [PATCH 394/451] fix javadoc --- JSONArray.java | 53 +++++++++++++++++++++++++++--------------- JSONObject.java | 61 ++++++++++++++++++++++++++++++------------------- 2 files changed, 73 insertions(+), 41 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 9314438..b7ae565 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -180,10 +180,16 @@ public class JSONArray implements Iterable { } /** - * Construct a JSONArray from an array + * Construct a JSONArray from an array. + * + * @param array + * Array. If the parameter passed is null, or not an array, an + * exception will be thrown. * * @throws JSONException - * If not an array or if an array value is non-finite number. + * If not an array or if an array value is non-finite number. + * @throws NullPointerException + * Thrown if the array parameter is null. */ public JSONArray(Object array) throws JSONException { this(); @@ -310,17 +316,19 @@ public class JSONArray implements Iterable { } /** - * Get the enum value associated with an index. - * - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @return The enum value at the index location - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. - */ + * Get the enum value associated with an index. + * + * @param + * Enum Type + * @param clazz + * The type of enum to retrieve. + * @param index + * The index must be between 0 and length() - 1. + * @return The enum value at the index location + * @throws JSONException + * if the key is not found or if the value cannot be converted + * to an enum. + */ public > E getEnum(Class clazz, int index) throws JSONException { E val = optEnum(clazz, index); if(val==null) { @@ -334,7 +342,10 @@ public class JSONArray implements Iterable { } /** - * Get the BigDecimal value associated with an index. + * Get the BigDecimal value associated with an index. If the value is float + * or double, the the {@link BigDecimal#BigDecimal(double)} constructor + * will be used. See notes on the constructor for conversion issues that + * may arise. * * @param index * The index must be between 0 and length() - 1. @@ -683,6 +694,8 @@ public class JSONArray implements Iterable { /** * Get the enum value associated with a key. * + * @param + * Enum Type * @param clazz * The type of enum to retrieve. * @param index @@ -696,6 +709,8 @@ public class JSONArray implements Iterable { /** * Get the enum value associated with a key. * + * @param + * Enum Type * @param clazz * The type of enum to retrieve. * @param index @@ -725,7 +740,6 @@ public class JSONArray implements Iterable { } } - /** * Get the optional BigInteger value associated with an index. The * defaultValue is returned if there is no value for the index, or if the @@ -745,7 +759,10 @@ public class JSONArray implements Iterable { /** * Get the optional BigDecimal value associated with an index. The * defaultValue is returned if there is no value for the index, or if the - * value is not a number and cannot be converted to a number. + * value is not a number and cannot be converted to a number. If the value + * is float or double, the the {@link BigDecimal#BigDecimal(double)} + * constructor will be used. See notes on the constructor for conversion + * issues that may arise. * * @param index * The index must be between 0 and length() - 1. @@ -1192,8 +1209,8 @@ public class JSONArray implements Iterable { } /** - * Uses a uaer initialized JSONPointer and tries to - * match it to an item whithin this JSONArray. For example, given a + * Uses a user initialized JSONPointer and tries to + * match it to an item within this JSONArray. For example, given a * JSONArray initialized with this document: *
      * [
diff --git a/JSONObject.java b/JSONObject.java
index 1a9b9de..67ae9c7 100644
--- a/JSONObject.java
+++ b/JSONObject.java
@@ -576,17 +576,19 @@ public class JSONObject {
     }
 
     /**
-    * Get the enum value associated with a key.
-    * 
-    * @param clazz
-    *           The type of enum to retrieve.
-    * @param key
-    *           A key string.
-    * @return The enum value associated with the key
-    * @throws JSONException
-    *             if the key is not found or if the value cannot be converted
-    *             to an enum.
-    */
+     * Get the enum value associated with a key.
+     * 
+     * @param 
+     *            Enum Type
+     * @param clazz
+     *           The type of enum to retrieve.
+     * @param key
+     *           A key string.
+     * @return The enum value associated with the key
+     * @throws JSONException
+     *             if the key is not found or if the value cannot be converted
+     *             to an enum.
+     */
     public > E getEnum(Class clazz, String key) throws JSONException {
         E val = optEnum(clazz, key);
         if(val==null) {
@@ -814,6 +816,8 @@ public class JSONObject {
     /**
      * Get an array of field names from a JSONObject.
      *
+     * @param jo
+     *            JSON object
      * @return An array of field names, or null if there are no names.
      */
     public static String[] getNames(JSONObject jo) {
@@ -824,8 +828,10 @@ public class JSONObject {
     }
 
     /**
-     * Get an array of field names from an Object.
+     * Get an array of public field names from an Object.
      *
+     * @param object
+     *            object to read
      * @return An array of field names, or null if there are no names.
      */
     public static String[] getNames(Object object) {
@@ -1036,6 +1042,8 @@ public class JSONObject {
     /**
      * Get the enum value associated with a key.
      * 
+     * @param 
+     *            Enum Type
      * @param clazz
      *            The type of enum to retrieve.
      * @param key
@@ -1049,6 +1057,8 @@ public class JSONObject {
     /**
      * Get the enum value associated with a key.
      * 
+     * @param 
+     *            Enum Type
      * @param clazz
      *            The type of enum to retrieve.
      * @param key
@@ -1137,9 +1147,10 @@ public class JSONObject {
     }
 
     /**
-     * @param defaultValue
-     * @param val
-     * @return
+     * @param val value to convert
+     * @param defaultValue default value to return is the conversion doesn't work or is null.
+     * @return BigDecimal conversion of the original value, or the defaultValue if unable
+     *          to convert. 
      */
     static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue) {
         if (NULL.equals(val)) {
@@ -1187,9 +1198,10 @@ public class JSONObject {
     }
 
     /**
-     * @param defaultValue
-     * @param val
-     * @return
+     * @param val value to convert
+     * @param defaultValue default value to return is the conversion doesn't work or is null.
+     * @return BigInteger conversion of the original value, or the defaultValue if unable
+     *          to convert. 
      */
     static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) {
         if (NULL.equals(val)) {
@@ -1859,8 +1871,10 @@ public class JSONObject {
      * are both non-null, and only if there is not already a member with that
      * name.
      *
-     * @param key string
-     * @param value object
+     * @param key
+     *            key to insert into
+     * @param value
+     *            value to insert
      * @return this.
      * @throws JSONException
      *             if the key is a duplicate
@@ -1971,9 +1985,10 @@ public class JSONObject {
 
     /**
      * Produce a string in double quotes with backslash sequences in all the
-     * right places. A backslash will be inserted within 
Date: Tue, 2 Oct 2018 15:33:33 -0400
Subject: [PATCH 395/451] remove unneeded casts

---
 JSONWriter.java | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/JSONWriter.java b/JSONWriter.java
index a30a222..19f2dc8 100644
--- a/JSONWriter.java
+++ b/JSONWriter.java
@@ -325,14 +325,14 @@ public class JSONWriter {
             return "null";
         }
         if (value instanceof JSONString) {
-            Object object;
+            String object;
             try {
                 object = ((JSONString) value).toJSONString();
             } catch (Exception e) {
                 throw new JSONException(e);
             }
-            if (object instanceof String) {
-                return (String) object;
+            if (object != null) {
+                return object;
             }
             throw new JSONException("Bad value from toJSONString: " + object);
         }

From 34cfe6df14d80bc9015e07257373b81b6f47afa5 Mon Sep 17 00:00:00 2001
From: "John J. Aylward" 
Date: Thu, 4 Oct 2018 16:02:14 -0400
Subject: [PATCH 396/451] removes duplicate code in number getters

---
 JSONArray.java  | 122 ++++++++++++------------------------------
 JSONObject.java | 137 ++++++++++++++----------------------------------
 2 files changed, 72 insertions(+), 187 deletions(-)

diff --git a/JSONArray.java b/JSONArray.java
index b7ae565..537abb1 100644
--- a/JSONArray.java
+++ b/JSONArray.java
@@ -263,13 +263,7 @@ public class JSONArray implements Iterable {
      *             to a number.
      */
     public double getDouble(int index) throws JSONException {
-        Object object = this.get(index);
-        try {
-            return object instanceof Number ? ((Number) object).doubleValue()
-                    : Double.parseDouble((String) object);
-        } catch (Exception e) {
-            throw new JSONException("JSONArray[" + index + "] is not a number.", e);
-        }
+        return this.getNumber(index).doubleValue();
     }
 
     /**
@@ -283,14 +277,7 @@ public class JSONArray implements Iterable {
      *             object and cannot be converted to a number.
      */
     public float getFloat(int index) throws JSONException {
-        Object object = this.get(index);
-        try {
-            return object instanceof Number ? ((Number) object).floatValue()
-                    : Float.parseFloat(object.toString());
-        } catch (Exception e) {
-            throw new JSONException("JSONArray[" + index
-                    + "] is not a number.", e);
-        }
+        return this.getNumber(index).floatValue();
     }
 
     /**
@@ -394,13 +381,7 @@ public class JSONArray implements Iterable {
      *             If the key is not found or if the value is not a number.
      */
     public int getInt(int index) throws JSONException {
-        Object object = this.get(index);
-        try {
-            return object instanceof Number ? ((Number) object).intValue()
-                    : Integer.parseInt((String) object);
-        } catch (Exception e) {
-            throw new JSONException("JSONArray[" + index + "] is not a number.", e);
-        }
+        return this.getNumber(index).intValue();
     }
 
     /**
@@ -450,13 +431,7 @@ public class JSONArray implements Iterable {
      *             to a number.
      */
     public long getLong(int index) throws JSONException {
-        Object object = this.get(index);
-        try {
-            return object instanceof Number ? ((Number) object).longValue()
-                    : Long.parseLong((String) object);
-        } catch (Exception e) {
-            throw new JSONException("JSONArray[" + index + "] is not a number.", e);
-        }
+        return this.getNumber(index).longValue();
     }
 
     /**
@@ -500,13 +475,16 @@ public class JSONArray implements Iterable {
      */
     public String join(String separator) throws JSONException {
         int len = this.length();
-        StringBuilder sb = new StringBuilder();
+        if (len == 0) {
+            return "";
+        }
+        
+        StringBuilder sb = new StringBuilder(
+                   JSONObject.valueToString(this.myArrayList.get(0)));
 
-        for (int i = 0; i < len; i += 1) {
-            if (i > 0) {
-                sb.append(separator);
-            }
-            sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
+        for (int i = 1; i < len; i++) {
+            sb.append(separator)
+              .append(JSONObject.valueToString(this.myArrayList.get(i)));
         }
         return sb.toString();
     }
@@ -589,21 +567,15 @@ public class JSONArray implements Iterable {
      * @return The value.
      */
     public double optDouble(int index, double defaultValue) {
-        Object val = this.opt(index);
-        if (JSONObject.NULL.equals(val)) {
+        final Number val = this.optNumber(index, null);
+        if (val == null) {
             return defaultValue;
         }
-        if (val instanceof Number){
-            return ((Number) val).doubleValue();
-        }
-        if (val instanceof String) {
-            try {
-                return Double.parseDouble((String) val);
-            } catch (Exception e) {
-                return defaultValue;
-            }
-        }
-        return defaultValue;
+        final double doubleValue = val.doubleValue();
+        // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
+        // return defaultValue;
+        // }
+        return doubleValue;
     }
 
     /**
@@ -631,21 +603,15 @@ public class JSONArray implements Iterable {
      * @return The value.
      */
     public float optFloat(int index, float defaultValue) {
-        Object val = this.opt(index);
-        if (JSONObject.NULL.equals(val)) {
+        final Number val = this.optNumber(index, null);
+        if (val == null) {
             return defaultValue;
         }
-        if (val instanceof Number){
-            return ((Number) val).floatValue();
-        }
-        if (val instanceof String) {
-            try {
-                return Float.parseFloat((String) val);
-            } catch (Exception e) {
-                return defaultValue;
-            }
-        }
-        return defaultValue;
+        final float floatValue = val.floatValue();
+        // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
+        // return floatValue;
+        // }
+        return floatValue;
     }
 
     /**
@@ -673,22 +639,11 @@ public class JSONArray implements Iterable {
      * @return The value.
      */
     public int optInt(int index, int defaultValue) {
-        Object val = this.opt(index);
-        if (JSONObject.NULL.equals(val)) {
+        final Number val = this.optNumber(index, null);
+        if (val == null) {
             return defaultValue;
         }
-        if (val instanceof Number){
-            return ((Number) val).intValue();
-        }
-        
-        if (val instanceof String) {
-            try {
-                return new BigDecimal(val.toString()).intValue();
-            } catch (Exception e) {
-                return defaultValue;
-            }
-        }
-        return defaultValue;
+        return val.intValue();
     }
 
     /**
@@ -827,22 +782,11 @@ public class JSONArray implements Iterable {
      * @return The value.
      */
     public long optLong(int index, long defaultValue) {
-        Object val = this.opt(index);
-        if (JSONObject.NULL.equals(val)) {
+        final Number val = this.optNumber(index, null);
+        if (val == null) {
             return defaultValue;
         }
-        if (val instanceof Number){
-            return ((Number) val).longValue();
-        }
-        
-        if (val instanceof String) {
-            try {
-                return new BigDecimal(val.toString()).longValue();
-            } catch (Exception e) {
-                return defaultValue;
-            }
-        }
-        return defaultValue;
+        return val.longValue();
     }
 
     /**
diff --git a/JSONObject.java b/JSONObject.java
index 67ae9c7..a1ed490 100644
--- a/JSONObject.java
+++ b/JSONObject.java
@@ -681,14 +681,7 @@ public class JSONObject {
      *             object and cannot be converted to a number.
      */
     public double getDouble(String key) throws JSONException {
-        Object object = this.get(key);
-        try {
-            return object instanceof Number ? ((Number) object).doubleValue()
-                    : Double.parseDouble(object.toString());
-        } catch (Exception e) {
-            throw new JSONException("JSONObject[" + quote(key)
-                    + "] is not a number.", e);
-        }
+        return this.getNumber(key).doubleValue();
     }
 
     /**
@@ -702,14 +695,7 @@ public class JSONObject {
      *             object and cannot be converted to a number.
      */
     public float getFloat(String key) throws JSONException {
-        Object object = this.get(key);
-        try {
-            return object instanceof Number ? ((Number) object).floatValue()
-                    : Float.parseFloat(object.toString());
-        } catch (Exception e) {
-            throw new JSONException("JSONObject[" + quote(key)
-                    + "] is not a number.", e);
-        }
+        return this.getNumber(key).floatValue();
     }
 
     /**
@@ -746,14 +732,7 @@ public class JSONObject {
      *             to an integer.
      */
     public int getInt(String key) throws JSONException {
-        Object object = this.get(key);
-        try {
-            return object instanceof Number ? ((Number) object).intValue()
-                    : Integer.parseInt((String) object);
-        } catch (Exception e) {
-            throw new JSONException("JSONObject[" + quote(key)
-                    + "] is not an int.", e);
-        }
+        return this.getNumber(key).intValue();
     }
 
     /**
@@ -803,14 +782,7 @@ public class JSONObject {
      *             to a long.
      */
     public long getLong(String key) throws JSONException {
-        Object object = this.get(key);
-        try {
-            return object instanceof Number ? ((Number) object).longValue()
-                    : Long.parseLong((String) object);
-        } catch (Exception e) {
-            throw new JSONException("JSONObject[" + quote(key)
-                    + "] is not a long.", e);
-        }
+        return this.getNumber(key).longValue();
     }
 
     /**
@@ -1266,21 +1238,15 @@ public class JSONObject {
      * @return An object which is the value.
      */
     public double optDouble(String key, double defaultValue) {
-        Object val = this.opt(key);
-        if (NULL.equals(val)) {
+        Number val = this.optNumber(key);
+        if (val == null) {
             return defaultValue;
         }
-        if (val instanceof Number){
-            return ((Number) val).doubleValue();
-        }
-        if (val instanceof String) {
-            try {
-                return Double.parseDouble((String) val);
-            } catch (Exception e) {
-                return defaultValue;
-            }
-        }
-        return defaultValue;
+        final double doubleValue = val.doubleValue();
+        // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
+        // return defaultValue;
+        // }
+        return doubleValue;
     }
 
     /**
@@ -1308,21 +1274,15 @@ public class JSONObject {
      * @return The value.
      */
     public float optFloat(String key, float defaultValue) {
-        Object val = this.opt(key);
-        if (JSONObject.NULL.equals(val)) {
+        Number val = this.optNumber(key);
+        if (val == null) {
             return defaultValue;
         }
-        if (val instanceof Number){
-            return ((Number) val).floatValue();
-        }
-        if (val instanceof String) {
-            try {
-                return Float.parseFloat((String) val);
-            } catch (Exception e) {
-                return defaultValue;
-            }
-        }
-        return defaultValue;
+        final float floatValue = val.floatValue();
+        // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) {
+        // return defaultValue;
+        // }
+        return floatValue;
     }
 
     /**
@@ -1350,22 +1310,11 @@ public class JSONObject {
      * @return An object which is the value.
      */
     public int optInt(String key, int defaultValue) {
-        Object val = this.opt(key);
-        if (NULL.equals(val)) {
+        final Number val = this.optNumber(key, null);
+        if (val == null) {
             return defaultValue;
         }
-        if (val instanceof Number){
-            return ((Number) val).intValue();
-        }
-        
-        if (val instanceof String) {
-            try {
-                return new BigDecimal((String) val).intValue();
-            } catch (Exception e) {
-                return defaultValue;
-            }
-        }
-        return defaultValue;
+        return val.intValue();
     }
 
     /**
@@ -1419,22 +1368,12 @@ public class JSONObject {
      * @return An object which is the value.
      */
     public long optLong(String key, long defaultValue) {
-        Object val = this.opt(key);
-        if (NULL.equals(val)) {
+        final Number val = this.optNumber(key, null);
+        if (val == null) {
             return defaultValue;
         }
-        if (val instanceof Number){
-            return ((Number) val).longValue();
-        }
         
-        if (val instanceof String) {
-            try {
-                return new BigDecimal((String) val).longValue();
-            } catch (Exception e) {
-                return defaultValue;
-            }
-        }
-        return defaultValue;
+        return val.longValue();
     }
     
     /**
@@ -1472,14 +1411,11 @@ public class JSONObject {
             return (Number) val;
         }
         
-        if (val instanceof String) {
-            try {
-                return stringToNumber((String) val);
-            } catch (Exception e) {
-                return defaultValue;
-            }
+        try {
+            return stringToNumber(val.toString());
+        } catch (Exception e) {
+            return defaultValue;
         }
-        return defaultValue;
     }
     
     /**
@@ -2201,22 +2137,26 @@ public class JSONObject {
      * can't be converted, return the string.
      *
      * @param string
-     *            A String.
+     *            A String. can not be null.
      * @return A simple JSON value.
+     * @throws NullPointerException
+     *             Thrown if the string is null.
      */
     // Changes to this method must be copied to the corresponding method in
     // the XML class to keep full support for Android
     public static Object stringToValue(String string) {
-        if (string.equals("")) {
+        if ("".equals(string)) {
             return string;
         }
-        if (string.equalsIgnoreCase("true")) {
+
+        // check JSON key words true/false/null
+        if ("true".equalsIgnoreCase(string)) {
             return Boolean.TRUE;
         }
-        if (string.equalsIgnoreCase("false")) {
+        if ("false".equalsIgnoreCase(string)) {
             return Boolean.FALSE;
         }
-        if (string.equalsIgnoreCase("null")) {
+        if ("null".equalsIgnoreCase(string)) {
             return JSONObject.NULL;
         }
 
@@ -2228,7 +2168,8 @@ public class JSONObject {
         char initial = string.charAt(0);
         if ((initial >= '0' && initial <= '9') || initial == '-') {
             try {
-                // if we want full Big Number support this block can be replaced with:
+                // if we want full Big Number support the contents of this
+                // `try` block can be replaced with:
                 // return stringToNumber(string);
                 if (isDecimalNotation(string)) {
                     Double d = Double.valueOf(string);

From 3e6c0a51bd0327732256a3999f7a7e2767a71d6b Mon Sep 17 00:00:00 2001
From: "John J. Aylward" 
Date: Thu, 4 Oct 2018 16:02:50 -0400
Subject: [PATCH 397/451] update expected exception text in tests to match
 unified number getters

---
 .../java/org/json/junit/JSONArrayTest.java    | 32 +++----
 .../java/org/json/junit/JSONObjectTest.java   | 94 +++++++++----------
 2 files changed, 63 insertions(+), 63 deletions(-)

diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java
index 845f4e7..3b70446 100644
--- a/src/test/java/org/json/junit/JSONArrayTest.java
+++ b/src/test/java/org/json/junit/JSONArrayTest.java
@@ -331,57 +331,57 @@ public class JSONArrayTest {
             jsonArray.getBoolean(4);
             assertTrue("expected getBoolean to fail", false);
         } catch (JSONException e) {
-            assertTrue("Expected an exception message",
-                    "JSONArray[4] is not a boolean.".equals(e.getMessage()));
+            assertEquals("Expected an exception message",
+                    "JSONArray[4] is not a boolean.",e.getMessage());
         }
         try {
             jsonArray.get(-1);
             assertTrue("expected get to fail", false);
         } catch (JSONException e) {
-            assertTrue("Expected an exception message",
-                    "JSONArray[-1] not found.".equals(e.getMessage()));
+            assertEquals("Expected an exception message",
+                    "JSONArray[-1] not found.",e.getMessage());
         }
         try {
             jsonArray.getDouble(4);
             assertTrue("expected getDouble to fail", false);
         } catch (JSONException e) {
-            assertTrue("Expected an exception message",
-                    "JSONArray[4] is not a number.".equals(e.getMessage()));
+            assertEquals("Expected an exception message",
+                    "JSONArray[4] is not a number.",e.getMessage());
         }
         try {
             jsonArray.getInt(4);
             assertTrue("expected getInt to fail", false);
         } catch (JSONException e) {
-            assertTrue("Expected an exception message",
-                    "JSONArray[4] is not a number.".equals(e.getMessage()));
+            assertEquals("Expected an exception message",
+                    "JSONArray[4] is not a number.",e.getMessage());
         }
         try {
             jsonArray.getJSONArray(4);
             assertTrue("expected getJSONArray to fail", false);
         } catch (JSONException e) {
-            assertTrue("Expected an exception message",
-                    "JSONArray[4] is not a JSONArray.".equals(e.getMessage()));
+            assertEquals("Expected an exception message",
+                    "JSONArray[4] is not a JSONArray.",e.getMessage());
         }
         try {
             jsonArray.getJSONObject(4);
             assertTrue("expected getJSONObject to fail", false);
         } catch (JSONException e) {
-            assertTrue("Expected an exception message",
-                    "JSONArray[4] is not a JSONObject.".equals(e.getMessage()));
+            assertEquals("Expected an exception message",
+                    "JSONArray[4] is not a JSONObject.",e.getMessage());
         }
         try {
             jsonArray.getLong(4);
             assertTrue("expected getLong to fail", false);
         } catch (JSONException e) {
-            assertTrue("Expected an exception message",
-                    "JSONArray[4] is not a number.".equals(e.getMessage()));
+            assertEquals("Expected an exception message",
+                    "JSONArray[4] is not a number.",e.getMessage());
         }
         try {
             jsonArray.getString(5);
             assertTrue("expected getString to fail", false);
         } catch (JSONException e) {
-            assertTrue("Expected an exception message",
-                    "JSONArray[5] not a string.".equals(e.getMessage()));
+            assertEquals("Expected an exception message",
+                    "JSONArray[5] not a string.",e.getMessage());
         }
     }
 
diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java
index 63385a5..c6cb580 100644
--- a/src/test/java/org/json/junit/JSONObjectTest.java
+++ b/src/test/java/org/json/junit/JSONObjectTest.java
@@ -1013,128 +1013,128 @@ public class JSONObjectTest {
             jsonObject.getBoolean("nonKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("expecting an exception message", 
-                    "JSONObject[\"nonKey\"] not found.".equals(e.getMessage()));
+            assertEquals("expecting an exception message", 
+                    "JSONObject[\"nonKey\"] not found.", e.getMessage());
         }
         try {
             jsonObject.getBoolean("stringKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"stringKey\"] is not a Boolean.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"stringKey\"] is not a Boolean.",
+                    e.getMessage());
         }
         try {
             jsonObject.getString("nonKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"nonKey\"] not found.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"nonKey\"] not found.",
+                    e.getMessage());
         }
         try {
             jsonObject.getString("trueKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"trueKey\"] not a string.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"trueKey\"] not a string.",
+                    e.getMessage());
         }
         try {
             jsonObject.getDouble("nonKey");
             fail("Expected an exception");
         } catch (JSONException e) {
-            assertTrue("Expecting an exception message",
-                    "JSONObject[\"nonKey\"] not found.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message",
+                    "JSONObject[\"nonKey\"] not found.",
+                    e.getMessage());
         }
         try {
             jsonObject.getDouble("stringKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message",
-                    "JSONObject[\"stringKey\"] is not a number.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message",
+                    "JSONObject[\"stringKey\"] is not a number.",
+                    e.getMessage());
         }
         try {
             jsonObject.getFloat("nonKey");
             fail("Expected an exception");
         } catch (JSONException e) {
-            assertTrue("Expecting an exception message",
-                    "JSONObject[\"nonKey\"] not found.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message",
+                    "JSONObject[\"nonKey\"] not found.",
+                    e.getMessage());
         }
         try {
             jsonObject.getFloat("stringKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message",
-                    "JSONObject[\"stringKey\"] is not a number.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message",
+                    "JSONObject[\"stringKey\"] is not a number.",
+                    e.getMessage());
         }
         try {
             jsonObject.getInt("nonKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message",
-                    "JSONObject[\"nonKey\"] not found.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message",
+                    "JSONObject[\"nonKey\"] not found.",
+                    e.getMessage());
         }
         try {
             jsonObject.getInt("stringKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"stringKey\"] is not an int.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"stringKey\"] is not a number.",
+                    e.getMessage());
         }
         try {
             jsonObject.getLong("nonKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"nonKey\"] not found.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"nonKey\"] not found.",
+                    e.getMessage());
         }
         try {
             jsonObject.getLong("stringKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"stringKey\"] is not a long.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"stringKey\"] is not a number.",
+                    e.getMessage());
         }
         try {
             jsonObject.getJSONArray("nonKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"nonKey\"] not found.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"nonKey\"] not found.",
+                    e.getMessage());
         }
         try {
             jsonObject.getJSONArray("stringKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"stringKey\"] is not a JSONArray.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"stringKey\"] is not a JSONArray.",
+                    e.getMessage());
         }
         try {
             jsonObject.getJSONObject("nonKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"nonKey\"] not found.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"nonKey\"] not found.",
+                    e.getMessage());
         }
         try {
             jsonObject.getJSONObject("stringKey");
             fail("Expected an exception");
         } catch (JSONException e) { 
-            assertTrue("Expecting an exception message", 
-                    "JSONObject[\"stringKey\"] is not a JSONObject.".
-                    equals(e.getMessage()));
+            assertEquals("Expecting an exception message", 
+                    "JSONObject[\"stringKey\"] is not a JSONObject.",
+                    e.getMessage());
         }
     }
 

From e4186e072ad2407d5dee25eeacef68884154ec5b Mon Sep 17 00:00:00 2001
From: stleary 
Date: Sat, 8 Dec 2018 11:29:44 -0600
Subject: [PATCH 398/451] reduce number of iterations to shorten test time

---
 src/test/java/org/json/junit/JSONObjectTest.java | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java
index c6cb580..8d32649 100644
--- a/src/test/java/org/json/junit/JSONObjectTest.java
+++ b/src/test/java/org/json/junit/JSONObjectTest.java
@@ -122,9 +122,13 @@ public class JSONObjectTest {
                     + "0a"
         };
         final int testDataLength = testData.length;
-        final int iterations = 1000000;
+        /**
+         * Changed to 1000 for faster test runs
+         */
+        // final int iterations = 1000000;
+        final int iterations = 1000;
 
-        // 10 million iterations 1,000,000 * 10
+        // 10 million iterations 1,000,000 * 10 (currently 100,000)
         long startTime = System.nanoTime();
         for(int i = 0; i < iterations; i++) {
             for(int j = 0; j < testDataLength; j++) {

From d0ea807884728782b2bc1722ca4a79e56e58e245 Mon Sep 17 00:00:00 2001
From: stleary 
Date: Sat, 8 Dec 2018 14:51:01 -0600
Subject: [PATCH 399/451] xml parser config tests

---
 README.md                                     |  37 +-
 .../java/org/json/junit/JunitTestSuite.java   |   3 +-
 .../org/json/junit/XMLConfigurationTest.java  | 930 ++++++++++++++++++
 3 files changed, 933 insertions(+), 37 deletions(-)
 create mode 100755 src/test/java/org/json/junit/XMLConfigurationTest.java

diff --git a/README.md b/README.md
index 1ca5c64..e6e61b5 100644
--- a/README.md
+++ b/README.md
@@ -89,43 +89,8 @@ Execution failed for task ':compileJava'.
 > invalid flag: -parameters
 ```
 
-A unit test has the following stages:
 
-| Test phase |Description |
-|----|----|
-| No test | No test specifically for this class has been written, or the class contains no executable code. |
-| In progress | Unit tests have been started for this class. |
-| Coverage > 90% | Initial goal of 90% coverage has been reached. Test quality may be questionable |
-| Reasonable test cases | 90% coverage. Functionality and behavior has been confirmed |
-| Checked against previous unit tests | Historical unit tests have been checked in case something important was missed |
-| Completed | The unit test is completed |
-
-
-| Test file name  | Coverage | Comments |
-| ------------- | ------------- | ---- |
-| Total coverage | 90.6% | | | 
-| | | | 
-| CDL.java | 98.8% | Reasonable test cases.  |
-| Cookie.java  | 98.9%   | Reasonable test cases. |
-| CookieList.java |96.5% | Reasonable test cases. |
-| HTTP.java | 98.8%| Coverage > 90% | 
-| HTTPTokener.java |93.2% | No test   | 
-| JSONArray.java |88.3% | Reasonable test cases. Need new tests for newer API functions | 
-| JSONException.java | 100% | No test |
-| JSONML.java | 84.4%| In progress | 
-| JSONObject | 96.7% | Reasonable test cases | 
-| JSONObject.Null | 77.8% | No test  | 
-| JSONPointer | 96.3% | Reasonable test cases  | 
-| JSONPointerException | 100% | No test  | 
-| JSONString.java | | No test  | 
-| JSONStringer.java | 93.8%| Coverage > 90% | 
-| JSONTokener.java | 87.5% | In progress | 
-| JSONWriter.java | 89.15% | No test | 
-| Property.java  | 95.8%  | Coverage > 90% |
-| XML.java | 77.3% | In progress |
-| XMLTokener.java| 82.4%| No test  | 
-
-| Files used in test |
+| Resource files used in test |
 | ------------- |  
 | EnumTest.java |
 | MyBean.java |
diff --git a/src/test/java/org/json/junit/JunitTestSuite.java b/src/test/java/org/json/junit/JunitTestSuite.java
index 9c9a325..68b5acb 100644
--- a/src/test/java/org/json/junit/JunitTestSuite.java
+++ b/src/test/java/org/json/junit/JunitTestSuite.java
@@ -18,7 +18,8 @@ import org.junit.runners.Suite;
    EnumTest.class,
    JSONPointerTest.class,
    JSONStringTest.class,
-   JSONTokenerTest.class
+   JSONTokenerTest.class,
+   XMLConfigurationTest.class
 })
 public class JunitTestSuite {
 }
diff --git a/src/test/java/org/json/junit/XMLConfigurationTest.java b/src/test/java/org/json/junit/XMLConfigurationTest.java
new file mode 100755
index 0000000..a2d0b85
--- /dev/null
+++ b/src/test/java/org/json/junit/XMLConfigurationTest.java
@@ -0,0 +1,930 @@
+package org.json.junit;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.json.XML;
+import org.json.XMLParserConfiguration;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+
+/**
+ * Tests for JSON-Java XML.java with XMLParserConfiguration.java
+ */
+public class XMLConfigurationTest {
+    /**
+     * JUnit supports temporary files and folders that are cleaned up after the test.
+     * https://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/ 
+     */
+    @Rule
+    public TemporaryFolder testFolder = new TemporaryFolder();
+
+    /**
+     * JSONObject from a null XML string.
+     * Expects a NullPointerException
+     */
+    @Test(expected=NullPointerException.class)
+    public void shouldHandleNullXML() {
+        String xmlStr = null;
+        JSONObject jsonObject = 
+                XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS);
+        assertTrue("jsonObject should be empty", jsonObject.isEmpty());
+    }
+
+    /**
+     * Empty JSONObject from an empty XML string.
+     */
+    @Test
+    public void shouldHandleEmptyXML() {
+
+        String xmlStr = "";
+        JSONObject jsonObject = 
+                XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS);
+        assertTrue("jsonObject should be empty", jsonObject.isEmpty());
+    }
+
+    /**
+     * Empty JSONObject from a non-XML string.
+     */
+    @Test
+    public void shouldHandleNonXML() {
+        String xmlStr = "{ \"this is\": \"not xml\"}";
+        JSONObject jsonObject = 
+                XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS);
+        assertTrue("xml string should be empty", jsonObject.isEmpty());
+    }
+
+    /**
+     * Invalid XML string (tag contains a frontslash).
+     * Expects a JSONException
+     */
+    @Test
+    public void shouldHandleInvalidSlashInTag() {
+        String xmlStr = 
+            "\n"+
+            "\n"+
+            "    
\n"+ + " \n"+ + " abc street\n"+ + "
\n"+ + "
"; + try { + XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); + fail("Expecting a JSONException"); + } catch (JSONException e) { + assertEquals("Expecting an exception message", + "Misshaped tag at 176 [character 14 line 4]", + e.getMessage()); + } + } + + /** + * Invalid XML string ('!' char in tag) + * Expects a JSONException + */ + @Test + public void shouldHandleInvalidBangInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + "
\n"+ + "
"; + try { + XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); + fail("Expecting a JSONException"); + } catch (JSONException e) { + assertEquals("Expecting an exception message", + "Misshaped meta tag at 214 [character 12 line 7]", + e.getMessage()); + } + } + + /** + * Invalid XML string ('!' char and no closing tag brace) + * Expects a JSONException + */ + @Test + public void shouldHandleInvalidBangNoCloseInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + ""; + try { + XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); + fail("Expecting a JSONException"); + } catch (JSONException e) { + assertEquals("Expecting an exception message", + "Misshaped meta tag at 213 [character 12 line 7]", + e.getMessage()); + } + } + + /** + * Invalid XML string (no end brace for tag) + * Expects JSONException + */ + @Test + public void shouldHandleNoCloseStartTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " \n"+ + ""; + try { + XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); + fail("Expecting a JSONException"); + } catch (JSONException e) { + assertEquals("Expecting an exception message", + "Misplaced '<' at 193 [character 4 line 6]", + e.getMessage()); + } + } + + /** + * Invalid XML string (partial CDATA chars in tag name) + * Expects JSONException + */ + @Test + public void shouldHandleInvalidCDATABangInTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " Joe Tester\n"+ + " \n"+ + "
\n"+ + "
"; + try { + XMLParserConfiguration config = + new XMLParserConfiguration("altContent"); + XML.toJSONObject(xmlStr, config); + fail("Expecting a JSONException"); + } catch (JSONException e) { + assertEquals("Expecting an exception message", + "Expected 'CDATA[' at 204 [character 11 line 5]", + e.getMessage()); + } + } + + /** + * Null JSONObject in XML.toString() + */ + @Test + public void shouldHandleNullJSONXML() { + JSONObject jsonObject= null; + String actualXml = XML.toString(jsonObject, null, + XMLParserConfiguration.KEEP_STRINGS); + assertEquals("generated XML does not equal expected XML","\"null\"",actualXml); + } + + /** + * Empty JSONObject in XML.toString() + */ + @Test + public void shouldHandleEmptyJSONXML() { + JSONObject jsonObject= new JSONObject(); + String xmlStr = XML.toString(jsonObject, null, + XMLParserConfiguration.KEEP_STRINGS); + assertTrue("xml string should be empty", xmlStr.isEmpty()); + } + + /** + * No SML start tag. The ending tag ends up being treated as content. + */ + @Test + public void shouldHandleNoStartTag() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " \n"+ + " >\n"+ + "
\n"+ + "
"; + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ + "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject jsonObject = XML.toJSONObject(xmlStr, + XMLParserConfiguration.KEEP_STRINGS); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + /** + * Valid XML to JSONObject + */ + @Test + public void shouldHandleSimpleXML() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " Joe Tester\n"+ + " [CDATA[Baker street 5]\n"+ + " \n"+ + " true\n"+ + " false\n"+ + " null\n"+ + " 42\n"+ + " -23\n"+ + " -23.45\n"+ + " -23x.45\n"+ + " 1, 2, 3, 4.1, 5.2\n"+ + "
\n"+ + "
"; + + String expectedStr = + "{\"addresses\":{\"address\":{\"street\":\"[CDATA[Baker street 5]\","+ + "\"name\":\"Joe Tester\",\"NothingHere\":\"\",TrueValue:true,\n"+ + "\"FalseValue\":false,\"NullValue\":null,\"PositiveValue\":42,\n"+ + "\"NegativeValue\":-23,\"DoubleValue\":-23.45,\"Nan\":-23x.45,\n"+ + "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ + "},\"xsi:noNamespaceSchemaLocation\":"+ + "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ + "XMLSchema-instance\"}}"; + + XMLParserConfiguration config = + new XMLParserConfiguration("altContent"); + compareStringToJSONObject(xmlStr, expectedStr, config); + compareReaderToJSONObject(xmlStr, expectedStr, config); + compareFileToJSONObject(xmlStr, expectedStr); + } + + /** + * Valid XML with comments to JSONObject + */ + @Test + public void shouldHandleCommentsInXML() { + + String xmlStr = + "\n"+ + "\n"+ + "\n"+ + "
\n"+ + " comment ]]>\n"+ + " Joe Tester\n"+ + " \n"+ + " Baker street 5\n"+ + "
\n"+ + "
"; + XMLParserConfiguration config = + new XMLParserConfiguration("altContent"); + JSONObject jsonObject = XML.toJSONObject(xmlStr, config); + String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker "+ + "street 5\",\"name\":\"Joe Tester\",\"altContent\":\" this is -- "+ + " comment \"}}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + /** + * Valid XML to XML.toString() + */ + @Test + public void shouldHandleToString() { + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " [CDATA[Joe & T > e < s " t ' er]]\n"+ + " Baker street 5\n"+ + " 1, 2, 3, 4.1, 5.2\n"+ + "
\n"+ + "
"; + + String expectedStr = + "{\"addresses\":{\"address\":{\"street\":\"Baker street 5\","+ + "\"name\":\"[CDATA[Joe & T > e < s \\\" t \\\' er]]\","+ + "\"ArrayOfNum\":\"1, 2, 3, 4.1, 5.2\"\n"+ + "},\"xsi:noNamespaceSchemaLocation\":"+ + "\"test.xsd\",\"xmlns:xsi\":\"http://www.w3.org/2001/"+ + "XMLSchema-instance\"}}"; + + JSONObject jsonObject = XML.toJSONObject(xmlStr, + XMLParserConfiguration.KEEP_STRINGS); + String xmlToStr = XML.toString(jsonObject, null, + XMLParserConfiguration.KEEP_STRINGS); + JSONObject finalJsonObject = XML.toJSONObject(xmlToStr, + XMLParserConfiguration.KEEP_STRINGS); + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } + + /** + * Converting a JSON doc containing '>' content to JSONObject, then + * XML.toString() should result in valid XML. + */ + @Test + public void shouldHandleContentNoArraytoString() { + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ + "altContent\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + XMLParserConfiguration config = new XMLParserConfiguration("altContent"); + String finalStr = XML.toString(expectedJsonObject, null, config); + String expectedFinalStr = "
>"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr.equals(finalStr)); + } + + /** + * Converting a JSON doc containing a 'content' array to JSONObject, then + * XML.toString() should result in valid XML. + * TODO: This is probably an error in how the 'content' keyword is used. + */ + @Test + public void shouldHandleContentArraytoString() { + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ + "altContent\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + XMLParserConfiguration config = new XMLParserConfiguration("altContent"); + String finalStr = XML.toString(expectedJsonObject, null, config); + String expectedFinalStr = "
"+ + "1\n2\n3"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr.equals(finalStr)); + } + + /** + * Converting a JSON doc containing a named array to JSONObject, then + * XML.toString() should result in valid XML. + */ + @Test + public void shouldHandleArraytoString() { + String expectedStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ + "\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject expectedJsonObject = new JSONObject(expectedStr); + String finalStr = XML.toString(expectedJsonObject, null, + XMLParserConfiguration.KEEP_STRINGS); + String expectedFinalStr = "
"+ + "123"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr.equals(finalStr)); + } + + /** + * Tests that the XML output for empty arrays is consistent. + */ + @Test + public void shouldHandleEmptyArray(){ + final JSONObject jo1 = new JSONObject(); + jo1.put("array",new Object[]{}); + final JSONObject jo2 = new JSONObject(); + jo2.put("array",new JSONArray()); + + final String expected = ""; + String output1 = XML.toString(jo1, "jo", + XMLParserConfiguration.KEEP_STRINGS); + assertEquals("Expected an empty root tag", expected, output1); + String output2 = XML.toString(jo2, "jo", + XMLParserConfiguration.KEEP_STRINGS); + assertEquals("Expected an empty root tag", expected, output2); + } + + /** + * Tests that the XML output for arrays is consistent when an internal array is empty. + */ + @Test + public void shouldHandleEmptyMultiArray(){ + final JSONObject jo1 = new JSONObject(); + jo1.put("arr",new Object[]{"One", new String[]{}, "Four"}); + final JSONObject jo2 = new JSONObject(); + jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{}), "Four"})); + + final String expected = "OneFour"; + String output1 = XML.toString(jo1, "jo", + XMLParserConfiguration.KEEP_STRINGS); + assertEquals("Expected a matching array", expected, output1); + String output2 = XML.toString(jo2, "jo", + XMLParserConfiguration.KEEP_STRINGS); + + assertEquals("Expected a matching array", expected, output2); + } + + /** + * Tests that the XML output for arrays is consistent when arrays are not empty. + */ + @Test + public void shouldHandleNonEmptyArray(){ + final JSONObject jo1 = new JSONObject(); + jo1.put("arr",new String[]{"One", "Two", "Three"}); + final JSONObject jo2 = new JSONObject(); + jo2.put("arr",new JSONArray(new String[]{"One", "Two", "Three"})); + + final String expected = "OneTwoThree"; + String output1 = XML.toString(jo1, "jo", + XMLParserConfiguration.KEEP_STRINGS); + assertEquals("Expected a non empty root tag", expected, output1); + String output2 = XML.toString(jo2, "jo", + XMLParserConfiguration.KEEP_STRINGS); + assertEquals("Expected a non empty root tag", expected, output2); + } + + /** + * Tests that the XML output for arrays is consistent when arrays are not empty and contain internal arrays. + */ + @Test + public void shouldHandleMultiArray(){ + final JSONObject jo1 = new JSONObject(); + jo1.put("arr",new Object[]{"One", new String[]{"Two", "Three"}, "Four"}); + final JSONObject jo2 = new JSONObject(); + jo2.put("arr",new JSONArray(new Object[]{"One", new JSONArray(new String[]{"Two", "Three"}), "Four"})); + + final String expected = "OneTwoThreeFour"; + String output1 = XML.toString(jo1, "jo", + XMLParserConfiguration.KEEP_STRINGS); + assertEquals("Expected a matching array", expected, output1); + String output2 = XML.toString(jo2, "jo", + XMLParserConfiguration.KEEP_STRINGS); + assertEquals("Expected a matching array", expected, output2); + } + + /** + * Converting a JSON doc containing a named array of nested arrays to + * JSONObject, then XML.toString() should result in valid XML. + */ + @Test + public void shouldHandleNestedArraytoString() { + String xmlStr = + "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ + "\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ + "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + JSONObject jsonObject = new JSONObject(xmlStr); + String finalStr = XML.toString(jsonObject, null, + XMLParserConfiguration.ORIGINAL); + JSONObject finalJsonObject = XML.toJSONObject(finalStr); + String expectedStr = "
"+ + "12"+ + "3"+ + "
test.xsdhttp://www.w3.org/2001/XMLSche"+ + "ma-instance
"; + JSONObject expectedJsonObject = XML.toJSONObject(expectedStr, + XMLParserConfiguration.ORIGINAL); + Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); + } + + + /** + * Possible bug: + * Illegal node-names must be converted to legal XML-node-names. + * The given example shows 2 nodes which are valid for JSON, but not for XML. + * Therefore illegal arguments should be converted to e.g. an underscore (_). + */ + @Test + public void shouldHandleIllegalJSONNodeNames() + { + JSONObject inputJSON = new JSONObject(); + inputJSON.append("123IllegalNode", "someValue1"); + inputJSON.append("Illegal@node", "someValue2"); + + String result = XML.toString(inputJSON, null, + XMLParserConfiguration.KEEP_STRINGS); + + /* + * This is invalid XML. Names should not begin with digits or contain + * certain values, including '@'. One possible solution is to replace + * illegal chars with '_', in which case the expected output would be: + * <___IllegalNode>someValue1someValue2 + */ + String expected = "<123IllegalNode>someValue1someValue2"; + + assertEquals(expected, result); + } + + /** + * JSONObject with NULL value, to XML.toString() + */ + @Test + public void shouldHandleNullNodeValue() + { + JSONObject inputJSON = new JSONObject(); + inputJSON.put("nullValue", JSONObject.NULL); + // This is a possible preferred result + // String expectedXML = ""; + /** + * This is the current behavior. JSONObject.NULL is emitted as + * the string, "null". + */ + String actualXML = "null"; + String resultXML = XML.toString(inputJSON, null, + XMLParserConfiguration.KEEP_STRINGS); + assertEquals(actualXML, resultXML); + } + + /** + * Investigate exactly how the "content" keyword works + */ + @Test + public void contentOperations() { + /* + * When a standalone 0) then return]]>"; + JSONObject jsonObject = XML.toJSONObject(xmlStr, + XMLParserConfiguration.KEEP_STRINGS); + assertTrue("1. 3 items", 3 == jsonObject.length()); + assertTrue("1. empty tag1", "".equals(jsonObject.get("tag1"))); + assertTrue("1. empty tag2", "".equals(jsonObject.get("tag2"))); + assertTrue("1. content found", "if (a < b && a > 0) then return".equals(jsonObject.get("content"))); + + // multiple consecutive standalone cdatas are accumulated into an array + xmlStr = " 0) then return]]>"; + jsonObject = XML.toJSONObject(xmlStr, + new XMLParserConfiguration(true, "altContent")); + assertTrue("2. 3 items", 3 == jsonObject.length()); + assertTrue("2. empty tag1", "".equals(jsonObject.get("tag1"))); + assertTrue("2. empty tag2", "".equals(jsonObject.get("tag2"))); + assertTrue("2. content array found", jsonObject.get("altContent") instanceof JSONArray); + JSONArray jsonArray = jsonObject.getJSONArray("altContent"); + assertTrue("2. array size", jsonArray.length() == 2); + assertTrue("2. content array entry 0", "if (a < b && a > 0) then return".equals(jsonArray.get(0))); + assertTrue("2. content array entry 1", "here is another cdata".equals(jsonArray.get(1))); + + /* + * text content is accumulated in a "content" inside a local JSONObject. + * If there is only one instance, it is saved in the context (a different JSONObject + * from the calling code. and the content element is discarded. + */ + xmlStr = "value 1"; + jsonObject = XML.toJSONObject(xmlStr, + new XMLParserConfiguration(true, "altContent")); + assertTrue("3. 2 items", 1 == jsonObject.length()); + assertTrue("3. value tag1", "value 1".equals(jsonObject.get("tag1"))); + + /* + * array-style text content (multiple tags with the same name) is + * accumulated in a local JSONObject with key="content" and value=JSONArray, + * saved in the context, and then the local JSONObject is discarded. + */ + xmlStr = "value 12true"; + jsonObject = XML.toJSONObject(xmlStr, + new XMLParserConfiguration(true, "altContent")); + assertTrue("4. 1 item", 1 == jsonObject.length()); + assertTrue("4. content array found", jsonObject.get("tag1") instanceof JSONArray); + jsonArray = jsonObject.getJSONArray("tag1"); + assertTrue("4. array size", jsonArray.length() == 3); + assertTrue("4. content array entry 0", "value 1".equals(jsonArray.get(0))); + assertTrue("4. content array entry 1", jsonArray.getInt(1) == 2); + assertTrue("4. content array entry 2", jsonArray.getBoolean(2) == true); + + /* + * Complex content is accumulated in a "content" field. For example, an element + * may contain a mix of child elements and text. Each text segment is + * accumulated to content. + */ + xmlStr = "val1val2"; + jsonObject = XML.toJSONObject(xmlStr, + new XMLParserConfiguration(true, "altContent")); + assertTrue("5. 1 item", 1 == jsonObject.length()); + assertTrue("5. jsonObject found", jsonObject.get("tag1") + instanceof JSONObject); + jsonObject = jsonObject.getJSONObject("tag1"); + assertTrue("5. 2 contained items", 2 == jsonObject.length()); + assertTrue("5. contained tag", "".equals(jsonObject.get("tag2"))); + assertTrue("5. contained content jsonArray found", + jsonObject.get("altContent") instanceof JSONArray); + jsonArray = jsonObject.getJSONArray("altContent"); + assertTrue("5. array size", jsonArray.length() == 2); + assertTrue("5. content array entry 0", "val1".equals(jsonArray.get(0))); + assertTrue("5. content array entry 1", "val2".equals(jsonArray.get(1))); + + /* + * If there is only 1 complex text content, then it is accumulated in a + * "content" field as a string. + */ + xmlStr = "val1"; + jsonObject = XML.toJSONObject(xmlStr, + new XMLParserConfiguration(true, "altContent")); + assertTrue("6. 1 item", 1 == jsonObject.length()); + assertTrue("6. jsonObject found", jsonObject.get("tag1") instanceof JSONObject); + jsonObject = jsonObject.getJSONObject("tag1"); + assertTrue("6. contained content found", + "val1".equals(jsonObject.get("altContent"))); + assertTrue("6. contained tag2", "".equals(jsonObject.get("tag2"))); + + /* + * In this corner case, the content sibling happens to have key=content + * We end up with an array within an array, and no content element. + * This is probably a bug. + */ + xmlStr = "val1"; + jsonObject = XML.toJSONObject(xmlStr, + new XMLParserConfiguration(true, "altContent")); + assertTrue("7. 1 item", 1 == jsonObject.length()); + assertTrue("7. jsonArray found", + jsonObject.get("tag1") instanceof JSONArray); + jsonArray = jsonObject.getJSONArray("tag1"); + assertTrue("array size 1", jsonArray.length() == 1); + assertTrue("7. contained array found", jsonArray.get(0) + instanceof JSONArray); + jsonArray = jsonArray.getJSONArray(0); + assertTrue("7. inner array size 2", jsonArray.length() == 2); + assertTrue("7. inner array item 0", "val1".equals(jsonArray.get(0))); + assertTrue("7. inner array item 1", "".equals(jsonArray.get(1))); + + /* + * Confirm behavior of original issue + */ + String jsonStr = + "{"+ + "\"Profile\": {"+ + "\"list\": {"+ + "\"history\": {"+ + "\"entries\": ["+ + "{"+ + "\"deviceId\": \"id\","+ + "\"altContent\": {"+ + "\"material\": ["+ + "{"+ + "\"stuff\": false"+ + "}"+ + "]"+ + "}"+ + "}"+ + "]"+ + "}"+ + "}"+ + "}"+ + "}"; + jsonObject = new JSONObject(jsonStr); + xmlStr = XML.toString(jsonObject, null, + new XMLParserConfiguration(true, "altContent")); + /* + * This is the created XML. Looks like content was mistaken for + * complex (child node + text) XML. + * + * + * + * + * id + * {"material":[{"stuff":false}]} + * + * + * + * + */ + assertTrue("nothing to test here, see comment on created XML, above", true); + } + + /** + * JSON string lost leading zero and converted "True" to true. + */ + @Test + public void testToJSONArray_jsonOutput() { + final String originalXml = "011000True"; + final String expectedJsonString = "{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",1,\"00\",0],\"title\":true}}"; + final JSONObject actualJsonOutput = XML.toJSONObject(originalXml, + new XMLParserConfiguration(false)); + assertEquals(expectedJsonString, actualJsonOutput.toString()); + } + + /** + * JSON string cannot be reverted to original xml. + */ + @Test + public void testToJSONArray_reversibility() { + final String originalXml = "011000True"; + XMLParserConfiguration config = new XMLParserConfiguration(false); + final String revertedXml = + XML.toString(XML.toJSONObject(originalXml, config), + null, config); + assertNotEquals(revertedXml, originalXml); + } + + /** + * test passes when using the new method toJsonArray. + */ + @Test + public void testToJsonXML() { + final String originalXml = "011000True"; + final String expectedJsonString = "{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"True\"}}"; + + final JSONObject json = XML.toJSONObject(originalXml, + new XMLParserConfiguration(true)); + assertEquals(expectedJsonString, json.toString()); + + final String reverseXml = XML.toString(json); + // this reversal isn't exactly the same. use JSONML for an exact reversal + final String expectedReverseXml = "01011000True"; + + assertEquals(expectedReverseXml, reverseXml); + } + + /** + * test to validate certain conditions of XML unescaping. + */ + @Test + public void testUnescape() { + assertEquals("{\"xml\":\"Can cope <;\"}", + XML.toJSONObject("Can cope <; ", + XMLParserConfiguration.KEEP_STRINGS).toString()); + assertEquals("Can cope <; ", XML.unescape("Can cope <; ")); + + assertEquals("{\"xml\":\"Can cope & ;\"}", + XML.toJSONObject("Can cope & ; ", + XMLParserConfiguration.KEEP_STRINGS).toString()); + assertEquals("Can cope & ; ", XML.unescape("Can cope & ; ")); + + assertEquals("{\"xml\":\"Can cope &;\"}", + XML.toJSONObject("Can cope &; ", + XMLParserConfiguration.KEEP_STRINGS).toString()); + assertEquals("Can cope &; ", XML.unescape("Can cope &; ")); + + // unicode entity + assertEquals("{\"xml\":\"Can cope 4;\"}", + XML.toJSONObject("Can cope 4; ", + XMLParserConfiguration.KEEP_STRINGS).toString()); + assertEquals("Can cope 4; ", XML.unescape("Can cope 4; ")); + + // double escaped + assertEquals("{\"xml\":\"Can cope <\"}", + XML.toJSONObject("Can cope &lt; ", + XMLParserConfiguration.KEEP_STRINGS).toString()); + assertEquals("Can cope < ", XML.unescape("Can cope &lt; ")); + + assertEquals("{\"xml\":\"Can cope 4\"}", + XML.toJSONObject("Can cope &#x34; ", + XMLParserConfiguration.KEEP_STRINGS).toString()); + assertEquals("Can cope 4 ", XML.unescape("Can cope &#x34; ")); + + } + + /** + * Confirm XMLParserConfiguration functionality + */ + @Test + public void testConfig() { + /** + * 1st param is whether to keep the raw string, or call + * XML.stringToValue(), which may convert the token to + * boolean, null, or number. + * 2nd param is what JSON name to use for strings that are + * evaluated as xml content data in complex objects, e.g. + * + * value + * content data + * + */ + + String xmlStr = + "\n"+ + "\n"+ + "
\n"+ + " content 1\n"+ + " Sherlock Holmes\n"+ + " content 2\n"+ + " Baker street 5\n"+ + " content 3\n"+ + " 1\n"+ + "
\n"+ + "
"; + + // keep strings, use the altContent tag + XMLParserConfiguration config = + new XMLParserConfiguration(true, "altContent"); + JSONObject jsonObject = XML.toJSONObject(xmlStr, config); + // num is parsed as a string + assertEquals(jsonObject.getJSONObject("addresses"). + getJSONObject("address").getString("num"), "1"); + // complex content is collected in an 'altContent' array + JSONArray jsonArray = jsonObject.getJSONObject("addresses"). + getJSONObject("address").getJSONArray("altContent"); + String expectedStr = "[\"content 1\", \"content 2\", \"content 3\"]"; + JSONArray expectedJsonArray = new JSONArray(expectedStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + + // keepstrings only + jsonObject = XML.toJSONObject(xmlStr, + XMLParserConfiguration.KEEP_STRINGS); + // num is parsed as a string + assertEquals(jsonObject.getJSONObject("addresses"). + getJSONObject("address").getString("num"), "1"); + // complex content is collected in an 'content' array + jsonArray = jsonObject.getJSONObject("addresses"). + getJSONObject("address").getJSONArray("content"); + expectedJsonArray = new JSONArray(expectedStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + + // use alternate content name + config = new XMLParserConfiguration("altContent"); + jsonObject = XML.toJSONObject(xmlStr, config); + // num is parsed as a number + assertEquals(jsonObject.getJSONObject("addresses"). + getJSONObject("address").getInt("num"), 1); + // complex content is collected in an 'altContent' array + jsonArray = jsonObject.getJSONObject("addresses"). + getJSONObject("address").getJSONArray("altContent"); + expectedJsonArray = new JSONArray(expectedStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); + + } + + + /** + * Convenience method, given an input string and expected result, + * convert to JSONObject and compare actual to expected result. + * @param xmlStr the string to parse + * @param expectedStr the expected JSON string + * @param config provides more flexible XML parsing + * flexible XML parsing. + */ + private void compareStringToJSONObject(String xmlStr, String expectedStr, + XMLParserConfiguration config) { + JSONObject expectedJsonObject = new JSONObject(expectedStr); + JSONObject jsonObject = XML.toJSONObject(xmlStr, config); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } + + /** + * Convenience method, given an input string and expected result, + * convert to JSONObject via reader and compare actual to expected result. + * @param xmlStr the string to parse + * @param expectedStr the expected JSON string + * @param config provides more flexible XML parsing + */ + private void compareReaderToJSONObject(String xmlStr, String expectedStr, + XMLParserConfiguration config) { + /* + * Commenting out this method until the JSON-java code is updated + * to support XML.toJSONObject(reader) + JSONObject expectedJsonObject = new JSONObject(expectedStr); + Reader reader = new StringReader(xmlStr); + JSONObject jsonObject = XML.toJSONObject(reader); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + */ + } + + /** + * Convenience method, given an input string and expected result, convert to + * JSONObject via file and compare actual to expected result. + * + * @param xmlStr + * the string to parse + * @param expectedStr + * the expected JSON string + * @throws IOException + */ + private void compareFileToJSONObject(String xmlStr, String expectedStr) { + /* + * Commenting out this method until the JSON-java code is updated + * to support XML.toJSONObject(reader) + try { + JSONObject expectedJsonObject = new JSONObject(expectedStr); + File tempFile = testFolder.newFile("fileToJSONObject.xml"); + FileWriter fileWriter = new FileWriter(tempFile); + fileWriter.write(xmlStr); + fileWriter.close(); + Reader reader = new FileReader(tempFile); + JSONObject jsonObject = XML.toJSONObject(reader); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } catch (IOException e) { + assertTrue("file writer error: " +e.getMessage(), false); + } + */ + } +} \ No newline at end of file From fea0aca2ab2e49f348c8340a702e8ea57065d7c4 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sat, 8 Dec 2018 19:54:06 -0600 Subject: [PATCH 400/451] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 82ffedc..767b2cd 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,8 @@ JSON in Java [package org.json] [![Maven Central](https://img.shields.io/maven-central/v/org.json/json.svg)](https://mvnrepository.com/artifact/org.json/json) +**[Click here if you just want the jar file.](http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar)** + JSON is a light-weight, language independent, data interchange format. See http://www.JSON.org/ From e7f7d348cd13e2e6d168e13398f6d7384294cc2a Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 10 Dec 2018 11:45:10 -0500 Subject: [PATCH 401/451] * updates tests to cover more cases of tokenizing * uncomments tests that should now work --- src/test/java/org/json/junit/CDLTest.java | 10 +- .../java/org/json/junit/JSONTokenerTest.java | 94 +++++++++++++++++++ src/test/java/org/json/junit/XMLTest.java | 32 +++---- 3 files changed, 115 insertions(+), 21 deletions(-) diff --git a/src/test/java/org/json/junit/CDLTest.java b/src/test/java/org/json/junit/CDLTest.java index b1f9561..721fd3c 100644 --- a/src/test/java/org/json/junit/CDLTest.java +++ b/src/test/java/org/json/junit/CDLTest.java @@ -30,7 +30,7 @@ public class CDLTest { ); /** - * CDL.toJSONArray() adds all values asstrings, with no filtering or + * CDL.toJSONArray() adds all values as strings, with no filtering or * conversions. For testing, this means that the expected JSONObject * values all must be quoted in the cases where the JSONObject parsing * might normally convert the value into a non-string. @@ -264,8 +264,8 @@ public class CDLTest { */ @Test public void textToJSONArray() { - JSONArray jsonArray = CDL.toJSONArray(lines); - JSONArray expectedJsonArray = new JSONArray(expectedLines); + JSONArray jsonArray = CDL.toJSONArray(this.lines); + JSONArray expectedJsonArray = new JSONArray(this.expectedLines); Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); } @@ -289,10 +289,10 @@ public class CDLTest { */ @Test public void textToJSONArrayAndBackToString() { - JSONArray jsonArray = CDL.toJSONArray(lines); + JSONArray jsonArray = CDL.toJSONArray(this.lines); String jsonStr = CDL.toString(jsonArray); JSONArray finalJsonArray = CDL.toJSONArray(jsonStr); - JSONArray expectedJsonArray = new JSONArray(expectedLines); + JSONArray expectedJsonArray = new JSONArray(this.expectedLines); Util.compareActualVsExpectedJsonArrays(finalJsonArray, expectedJsonArray); } diff --git a/src/test/java/org/json/junit/JSONTokenerTest.java b/src/test/java/org/json/junit/JSONTokenerTest.java index dced89f..de1564d 100644 --- a/src/test/java/org/json/junit/JSONTokenerTest.java +++ b/src/test/java/org/json/junit/JSONTokenerTest.java @@ -12,7 +12,9 @@ import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; +import org.json.JSONArray; import org.json.JSONException; +import org.json.JSONObject; import org.json.JSONTokener; import org.junit.Test; @@ -64,7 +66,99 @@ public class JSONTokenerTest { } } } + + @Test + public void testValid() { + checkValid("0",Number.class); + checkValid(" 0 ",Number.class); + checkValid("23",Number.class); + checkValid("23.5",Number.class); + checkValid(" 23.5 ",Number.class); + checkValid("null",null); + checkValid(" null ",null); + checkValid("true",Boolean.class); + checkValid(" true\n",Boolean.class); + checkValid("false",Boolean.class); + checkValid("\nfalse ",Boolean.class); + checkValid("{}",JSONObject.class); + checkValid(" {} ",JSONObject.class); + checkValid("{\"a\":1}",JSONObject.class); + checkValid(" {\"a\":1} ",JSONObject.class); + checkValid("[]",JSONArray.class); + checkValid(" [] ",JSONArray.class); + checkValid("[1,2]",JSONArray.class); + checkValid("\n\n[1,2]\n\n",JSONArray.class); + checkValid("1 2", String.class); + } + + @Test + public void testErrors() { + // Check that stream can detect that a value is found after + // the first one + checkError(" { \"a\":1 } 4 "); + checkError("null \"a\""); + checkError("{} true"); + } + + private Object checkValid(String testStr, Class aClass) { + Object result = nextValue(testStr); + // Check class of object returned + if( null == aClass ) { + if(JSONObject.NULL.equals(result)) { + // OK + } else { + throw new JSONException("Unexpected class: "+result.getClass().getSimpleName()); + } + } else { + if( null == result ) { + throw new JSONException("Unexpected null result"); + } else if(!aClass.isAssignableFrom(result.getClass()) ) { + throw new JSONException("Unexpected class: "+result.getClass().getSimpleName()); + } + } + + return result; + } + + private void checkError(String testStr) { + try { + nextValue(testStr); + + fail("Error should be triggered: (\""+testStr+"\")"); + } catch (JSONException e) { + // OK + } + } + + /** + * Verifies that JSONTokener can read a stream that contains a value. After + * the reading is done, check that the stream is left in the correct state + * by reading the characters after. All valid cases should reach end of stream. + * @param testStr + * @return + * @throws Exception + */ + private Object nextValue(String testStr) throws JSONException { + try(StringReader sr = new StringReader(testStr);){ + JSONTokener tokener = new JSONTokener(sr); + + Object result = tokener.nextValue(); + + if( result == null ) { + throw new JSONException("Unable to find value token in JSON stream: ("+tokener+"): "+testStr); + } + + char c = tokener.nextClean(); + if( 0 != c ) { + throw new JSONException("Unexpected character found at end of JSON stream: "+c+ " ("+tokener+"): "+testStr); + } + + return result; + } + + } + /** * Tests the failure of the skipTo method with a buffered reader. Preferably * we'd like this not to fail but at this time we don't have a good recovery. diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 1cff326..83a7cc2 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -6,6 +6,13 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; + import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -743,14 +750,10 @@ public class XMLTest { * @param expectedStr the expected JSON string */ private void compareReaderToJSONObject(String xmlStr, String expectedStr) { - /* - * Commenting out this method until the JSON-java code is updated - * to support XML.toJSONObject(reader) JSONObject expectedJsonObject = new JSONObject(expectedStr); Reader reader = new StringReader(xmlStr); JSONObject jsonObject = XML.toJSONObject(reader); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); - */ } /** @@ -764,22 +767,19 @@ public class XMLTest { * @throws IOException */ private void compareFileToJSONObject(String xmlStr, String expectedStr) { - /* - * Commenting out this method until the JSON-java code is updated - * to support XML.toJSONObject(reader) try { JSONObject expectedJsonObject = new JSONObject(expectedStr); - File tempFile = testFolder.newFile("fileToJSONObject.xml"); - FileWriter fileWriter = new FileWriter(tempFile); - fileWriter.write(xmlStr); - fileWriter.close(); - Reader reader = new FileReader(tempFile); - JSONObject jsonObject = XML.toJSONObject(reader); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + File tempFile = this.testFolder.newFile("fileToJSONObject.xml"); + try(FileWriter fileWriter = new FileWriter(tempFile);){ + fileWriter.write(xmlStr); + } + try(Reader reader = new FileReader(tempFile);){ + JSONObject jsonObject = XML.toJSONObject(reader); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } } catch (IOException e) { - assertTrue("file writer error: " +e.getMessage(), false); + fail("file writer error: " +e.getMessage()); } - */ } /** From 19e9bb6c07f026e2377521c3b144c66d13612b8d Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 10 Dec 2018 11:45:53 -0500 Subject: [PATCH 402/451] Adds check for EOF --- JSONTokener.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/JSONTokener.java b/JSONTokener.java index 36bce45..e6821de 100644 --- a/JSONTokener.java +++ b/JSONTokener.java @@ -448,7 +448,9 @@ public class JSONTokener { sb.append(c); c = this.next(); } - this.back(); + if (!this.eof) { + this.back(); + } string = sb.toString().trim(); if ("".equals(string)) { From d5b278539ed00302048d9c9f4df5f4282bd0e34d Mon Sep 17 00:00:00 2001 From: meiskalt7 Date: Tue, 9 Apr 2019 18:47:45 +0700 Subject: [PATCH 403/451] add configuration for xsi:nil="true" conversion to null --- XML.java | 73 +++++++++++++++++++++++-------------- XMLParserConfiguration.java | 33 ++++++++++++++--- 2 files changed, 72 insertions(+), 34 deletions(-) diff --git a/XML.java b/XML.java index 73090fc..f660d23 100644 --- a/XML.java +++ b/XML.java @@ -31,7 +31,7 @@ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONObject, and to * covert a JSONObject into an XML text. - * + * * @author JSON.org * @version 2016-08-10 */ @@ -64,7 +64,12 @@ public class XML { /** The Character '/'. */ public static final Character SLASH = '/'; - + + /** + * Null attrubute name + */ + public static final String NULL_ATTR = "xsi:nil"; + /** * Creates an iterator for navigating Code Points in a string instead of * characters. Once Java7 support is dropped, this can be replaced with @@ -72,7 +77,7 @@ public class XML { * string.codePoints() * * which is available in Java8 and above. - * + * * @see http://stackoverflow.com/a/21791059/6030888 */ @@ -107,7 +112,7 @@ public class XML { /** * Replace special characters with XML escapes: - * + * *
      * & (ampersand) is replaced by &amp;
      * < (less than) is replaced by &lt;
@@ -115,7 +120,7 @@ public class XML {
      * " (double quote) is replaced by &quot;
      * ' (single quote / apostrophe) is replaced by &apos;
      * 
- * + * * @param string * The string to be escaped. * @return The escaped string. @@ -151,17 +156,17 @@ public class XML { } return sb.toString(); } - + /** * @param cp code point to test * @return true if the code point is not valid for an XML */ private static boolean mustEscape(int cp) { /* Valid range from https://www.w3.org/TR/REC-xml/#charsets - * - * #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] - * - * any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. + * + * #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] + * + * any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */ // isISOControl is true when (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F) // all ISO control characters are out of range except tabs and new lines @@ -180,7 +185,7 @@ public class XML { /** * Removes XML escapes from the string. - * + * * @param string * string to remove escapes from * @return string with converted entities @@ -212,7 +217,7 @@ public class XML { /** * Throw an exception if the string contains whitespace. Whitespace is not * allowed in tagNames and attributes. - * + * * @param string * A string. * @throws JSONException Thrown if the string contains whitespace or is empty. @@ -232,7 +237,7 @@ public class XML { /** * Scan the content following the named tag, attaching it to the context. - * + * * @param x * The XMLTokener containing the source string. * @param context @@ -328,6 +333,7 @@ public class XML { tagName = (String) token; token = null; jsonobject = new JSONObject(); + boolean nilAttributeFound = false; for (;;) { if (token == null) { token = x.nextToken(); @@ -341,8 +347,17 @@ public class XML { if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } - jsonobject.accumulate(string, - config.keepStrings ? ((String)token) : stringToValue((String) token)); + + if (config.convertNilAttributeToNull + && NULL_ATTR.equals(string) + && Boolean.parseBoolean((String) token)) { + nilAttributeFound = true; + } else if (!nilAttributeFound) { + jsonobject.accumulate(string, + config.keepStrings + ? ((String) token) + : stringToValue((String) token)); + } token = null; } else { jsonobject.accumulate(string, ""); @@ -354,7 +369,9 @@ public class XML { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } - if (jsonobject.length() > 0) { + if (nilAttributeFound) { + context.accumulate(tagName, JSONObject.NULL); + } else if (jsonobject.length() > 0) { context.accumulate(tagName, jsonobject); } else { context.accumulate(tagName, ""); @@ -399,10 +416,10 @@ public class XML { } } } - + /** * This method is the same as {@link JSONObject#stringToValue(String)}. - * + * * @param string String to convert * @return JSON value of this string or the string */ @@ -463,7 +480,7 @@ public class XML { * elements are represented as JSONArrays. Content text may be placed in a * "content" member. Comments, prologs, DTDs, and <[ [ ]]> * are ignored. - * + * * @param string * The source string. * @return A JSONObject containing the structured data from the XML string. @@ -518,7 +535,7 @@ public class XML { } return toJSONObject(reader, XMLParserConfiguration.ORIGINAL); } - + /** * Convert a well-formed (but not necessarily valid) XML into a * JSONObject. Some information may be lost in this transformation because @@ -560,10 +577,10 @@ public class XML { * elements are represented as JSONArrays. Content text may be placed in a * "content" member. Comments, prologs, DTDs, and <[ [ ]]> * are ignored. - * + * * All values are converted as strings, for 1, 01, 29.0 will not be coerced to * numbers but will instead be the exact value as seen in the XML document. - * + * * @param string * The source string. * @param keepStrings If true, then values will not be coerced into boolean @@ -585,10 +602,10 @@ public class XML { * elements are represented as JSONArrays. Content text may be placed in a * "content" member. Comments, prologs, DTDs, and <[ [ ]]> * are ignored. - * + * * All values are converted as strings, for 1, 01, 29.0 will not be coerced to * numbers but will instead be the exact value as seen in the XML document. - * + * * @param string * The source string. * @param config Configuration options for the parser. @@ -601,7 +618,7 @@ public class XML { /** * Convert a JSONObject into a well-formed, element-normal XML string. - * + * * @param object * A JSONObject. * @return A string. @@ -610,10 +627,10 @@ public class XML { public static String toString(Object object) throws JSONException { return toString(object, null, XMLParserConfiguration.ORIGINAL); } - + /** * Convert a JSONObject into a well-formed, element-normal XML string. - * + * * @param object * A JSONObject. * @param tagName @@ -627,7 +644,7 @@ public class XML { /** * Convert a JSONObject into a well-formed, element-normal XML string. - * + * * @param object * A JSONObject. * @param tagName diff --git a/XMLParserConfiguration.java b/XMLParserConfiguration.java index 45af175..c0186f7 100644 --- a/XMLParserConfiguration.java +++ b/XMLParserConfiguration.java @@ -32,7 +32,7 @@ public class XMLParserConfiguration { /** Original Configuration of the XML Parser. */ public static final XMLParserConfiguration ORIGINAL = new XMLParserConfiguration(); /** Original configuration of the XML Parser except that values are kept as strings. */ - public static final XMLParserConfiguration KEEP_STRINGS = new XMLParserConfiguration(true); + public static final XMLParserConfiguration KEEP_STRINGS = new XMLParserConfiguration(true); /** * When parsing the XML into JSON, specifies if values should be kept as strings (true), or if * they should try to be guessed into JSON values (numeric, boolean, string) @@ -44,12 +44,17 @@ public class XMLParserConfiguration { * processing. */ public final String cDataTagName; + /** + * When parsing the XML into JSON, specifies if values with attribute xsi:nil="true" + * should be kept as attribute(false), or they should be converted to null(true) + */ + public final boolean convertNilAttributeToNull; /** * Default parser configuration. Does not keep strings, and the CDATA Tag Name is "content". */ public XMLParserConfiguration () { - this(false, "content"); + this(false, "content", false); } /** @@ -58,7 +63,7 @@ public class XMLParserConfiguration { * false to try and convert XML string values into a JSON value. */ public XMLParserConfiguration (final boolean keepStrings) { - this(keepStrings, "content"); + this(keepStrings, "content", false); } /** @@ -69,7 +74,7 @@ public class XMLParserConfiguration { * to use that value as the JSONObject key name to process as CDATA. */ public XMLParserConfiguration (final String cDataTagName) { - this(false, cDataTagName); + this(false, cDataTagName, false); } /** @@ -80,7 +85,23 @@ public class XMLParserConfiguration { * to use that value as the JSONObject key name to process as CDATA. */ public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName) { - this.keepStrings = keepStrings; - this.cDataTagName = cDataTagName; + this.keepStrings = keepStrings; + this.cDataTagName = cDataTagName; + this.convertNilAttributeToNull = false; + } + + /** + * Configure the parser to use custom settings. + * @param keepStrings true to parse all values as string. + * false to try and convert XML string values into a JSON value. + * @param cDataTagName null to disable CDATA processing. Any other value + * to use that value as the JSONObject key name to process as CDATA. + * @param convertNilAttributeToNull true to parse values with attribute xsi:nil="true" as null. + * false to parse values with attribute xsi:nil="true" as {"xsi:nil":true}. + */ + public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName, final boolean convertNilAttributeToNull) { + this.keepStrings = keepStrings; + this.cDataTagName = cDataTagName; + this.convertNilAttributeToNull = convertNilAttributeToNull; } } From 614e8359b91eb997142d313a0469aa69b707394e Mon Sep 17 00:00:00 2001 From: meiskalt7 Date: Thu, 18 Apr 2019 21:42:57 +0700 Subject: [PATCH 404/451] add test for xsi:nil to null conversion --- src/test/java/org/json/junit/XMLTest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 83a7cc2..195f706 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -17,6 +17,7 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.XML; +import org.json.XMLParserConfiguration; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -856,4 +857,15 @@ public class XMLTest { } + /** + * test passes when xsi:nil="true" converting to null (JSON specification-like conversion) + */ + @Test + public void testToJsonWithNull() { + final String originalXml = ""; + final String expectedJsonString = "{\"root\":{\"id\":null}}"; + + final JSONObject json = XML.toJSONObject(originalXml,new XMLParserConfiguration(false, "content", true)); + assertEquals(expectedJsonString, json.toString()); + } } \ No newline at end of file From fa173fa51a61ba68c5c721c3170869f5ae93a927 Mon Sep 17 00:00:00 2001 From: meiskalt7 Date: Sun, 21 Apr 2019 00:53:39 +0700 Subject: [PATCH 405/451] add test for xsi:nil to null conversion disabled --- src/test/java/org/json/junit/XMLTest.java | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 195f706..b74daff 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -858,14 +858,26 @@ public class XMLTest { } /** - * test passes when xsi:nil="true" converting to null (JSON specification-like conversion) + * test passes when xsi:nil="true" converting to null (JSON specification-like nil conversion enabled) */ @Test - public void testToJsonWithNull() { + public void testToJsonWithNullWhenNilConversionEnabled() { final String originalXml = ""; final String expectedJsonString = "{\"root\":{\"id\":null}}"; - final JSONObject json = XML.toJSONObject(originalXml,new XMLParserConfiguration(false, "content", true)); + final JSONObject json = XML.toJSONObject(originalXml, new XMLParserConfiguration(false, "content", true)); + assertEquals(expectedJsonString, json.toString()); + } + + /** + * test passes when xsi:nil="true" not converting to null (JSON specification-like nil conversion disabled) + */ + @Test + public void testToJsonWithNullWhenNilConversionDisabled() { + final String originalXml = ""; + final String expectedJsonString = "{\"root\":{\"id\":{\"xsi:nil\":true}}}"; + + final JSONObject json = XML.toJSONObject(originalXml, new XMLParserConfiguration()); assertEquals(expectedJsonString, json.toString()); } } \ No newline at end of file From 5b845f28cfdc26919b1416ec2067da4a0753aeb6 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Wed, 8 May 2019 20:27:25 -0500 Subject: [PATCH 406/451] Update README.md New RFC8259, no changes to in-doc references. --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 767b2cd..d1f55e8 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ JSON in Java [package org.json] [![Maven Central](https://img.shields.io/maven-central/v/org.json/json.svg)](https://mvnrepository.com/artifact/org.json/json) -**[Click here if you just want the jar file.](http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar)** +**[Click here if you just want the latest release jar file.](http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar)** JSON is a light-weight, language independent, data interchange format. See http://www.JSON.org/ @@ -88,7 +88,7 @@ https://github.com/stleary/JSON-Java-unit-test Numeric types in this package comply with [ECMA-404: The JSON Data Interchange Format](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) and -[RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc7159#section-6). +[RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format](https://tools.ietf.org/html/rfc8259#section-6). This package fully supports `Integer`, `Long`, and `Double` Java types. Partial support for `BigInteger` and `BigDecimal` values in `JSONObject` and `JSONArray` objects is provided in the form of `get()`, `opt()`, and `put()` API methods. @@ -96,7 +96,7 @@ in the form of `get()`, `opt()`, and `put()` API methods. Although 1.6 compatibility is currently supported, it is not a project goal and may be removed in some future release. -In compliance with RFC7159 page 10 section 9, the parser is more lax with what is valid +In compliance with RFC8259 page 10 section 9, the parser is more lax with what is valid JSON than the Generator. For Example, the tab character (U+0009) is allowed when reading JSON Text strings, but when output by the Generator, tab is properly converted to \t in the string. Other instances may occur where reading invalid JSON text does not cause an From a03a01531afc71d0f4457de80246654c3d274a7b Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Mon, 22 Jul 2019 20:33:02 -0500 Subject: [PATCH 407/451] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index d1f55e8..82debfa 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,8 @@ invalid number formats (1.2e6.3) will cause errors as such documents can not be Release history: ~~~ +20190722 Recent commits + 20180813 POM change to include Automatic-Module-Name (#431) 20180130 Recent commits From 4d451468fdc246e0a2cc3b9656a0a138808b35b1 Mon Sep 17 00:00:00 2001 From: Andrew Gaul Date: Mon, 22 Jul 2019 22:26:49 -0700 Subject: [PATCH 408/451] Prefer unsynchronized StringBuilder StringBuffer provides unneeded synchronization. Found via error-prone. --- CDL.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CDL.java b/CDL.java index 1c7df32..6bc41dc 100644 --- a/CDL.java +++ b/CDL.java @@ -55,7 +55,7 @@ public class CDL { private static String getValue(JSONTokener x) throws JSONException { char c; char q; - StringBuffer sb; + StringBuilder sb; do { c = x.next(); } while (c == ' ' || c == '\t'); @@ -65,7 +65,7 @@ public class CDL { case '"': case '\'': q = c; - sb = new StringBuffer(); + sb = new StringBuilder(); for (;;) { c = x.next(); if (c == q) { @@ -275,7 +275,7 @@ public class CDL { if (names == null || names.length() == 0) { return null; } - StringBuffer sb = new StringBuffer(); + StringBuilder sb = new StringBuilder(); for (int i = 0; i < ja.length(); i += 1) { JSONObject jo = ja.optJSONObject(i); if (jo != null) { From f63d21fd13cd76e005247b7676be632d3e856435 Mon Sep 17 00:00:00 2001 From: Andrew Gaul Date: Fri, 26 Jul 2019 15:23:31 -0700 Subject: [PATCH 409/451] Make private methods static where possible This avoids an unneeded object reference. Found via error-prone. --- JSONObject.java | 4 ++-- JSONPointer.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index a1ed490..c54018e 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1496,11 +1496,11 @@ public class JSONObject { } } - private boolean isValidMethodName(String name) { + private static boolean isValidMethodName(String name) { return !"getClass".equals(name) && !"getDeclaringClass".equals(name); } - private String getKeyNameFromMethod(Method method) { + private static String getKeyNameFromMethod(Method method) { final int ignoreDepth = getAnnotationDepth(method, JSONPropertyIgnore.class); if (ignoreDepth > 0) { final int forcedNameDepth = getAnnotationDepth(method, JSONPropertyName.class); diff --git a/JSONPointer.java b/JSONPointer.java index df06f22..d122fd8 100644 --- a/JSONPointer.java +++ b/JSONPointer.java @@ -186,7 +186,7 @@ public class JSONPointer { this.refTokens = new ArrayList(refTokens); } - private String unescape(String token) { + private static String unescape(String token) { return token.replace("~1", "/").replace("~0", "~") .replace("\\\"", "\"") .replace("\\\\", "\\"); @@ -228,7 +228,7 @@ public class JSONPointer { * @return the matched object. If no matching item is found a * @throws JSONPointerException is thrown if the index is out of bounds */ - private Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { + private static Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { try { int index = Integer.parseInt(indexToken); JSONArray currentArr = (JSONArray) current; @@ -267,7 +267,7 @@ public class JSONPointer { * @param token the JSONPointer segment value to be escaped * @return the escaped value for the token */ - private String escape(String token) { + private static String escape(String token) { return token.replace("~", "~0") .replace("/", "~1") .replace("\\", "\\\\") From b044b7db4db3581d3d3b13352e8bb519cb31b5d3 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 14 Aug 2019 11:47:49 -0400 Subject: [PATCH 410/451] clarifies exception that the parser makes when reading JSON --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 82debfa..6691ef9 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,13 @@ JSON Text strings, but when output by the Generator, tab is properly converted t the string. Other instances may occur where reading invalid JSON text does not cause an error to be generated. Malformed JSON Texts such as missing end " (quote) on strings or invalid number formats (1.2e6.3) will cause errors as such documents can not be read - reliably. +reliably. + +Some notible exceptions that the JSON Parser in this library accepts are: +* Unquoted keys `{ key: "value" }` +* Unquoted values `{ "key": value }` +* Unescaped literals like "tab" in string values `{ "key": "value with an unescaped tab" }` +* Numbers out of range for `Double` or `Long` are parsed as strings Release history: From af6d3c63bd9bfc59a2a5f5e4a23db94bbdf13e36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Silva?= Date: Fri, 6 Sep 2019 12:45:41 -0300 Subject: [PATCH 411/451] Update README.md to point to latest version Update **Click here if you just want the latest release jar file** on README.md to point to latest version available on Maven Central. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6691ef9..0301dcb 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ JSON in Java [package org.json] [![Maven Central](https://img.shields.io/maven-central/v/org.json/json.svg)](https://mvnrepository.com/artifact/org.json/json) -**[Click here if you just want the latest release jar file.](http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar)** +**[Click here if you just want the latest release jar file.](https://repo1.maven.org/maven2/org/json/json/20190722/json-20190722.jar)** JSON is a light-weight, language independent, data interchange format. See http://www.JSON.org/ From 328e7d89447c3638676d7b01d59abbb19493c9c1 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 17 Sep 2019 10:33:26 -0400 Subject: [PATCH 412/451] corrects EOL error when the Meta tag isn't closed properly and we reach the end of the input. --- XMLTokener.java | 1 + 1 file changed, 1 insertion(+) diff --git a/XMLTokener.java b/XMLTokener.java index 8490bec..d733447 100644 --- a/XMLTokener.java +++ b/XMLTokener.java @@ -232,6 +232,7 @@ public class XMLTokener extends JSONTokener { } switch (c) { case 0: + throw syntaxError("Unterminated string"); case '<': case '>': case '/': From 3e7a0b13d1c2ed0b18d5ba143ddaaf171c72932a Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 17 Sep 2019 10:36:48 -0400 Subject: [PATCH 413/451] new test case for issue 484 --- src/test/java/org/json/junit/JSONMLTest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 84b33ba..26f4f90 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -803,4 +803,16 @@ public class JSONMLTest { // // assertEquals(expectedJsonString, actualJsonString); // } + + @Test (timeout = 6000) + public void testIssue484InfinteLoop() { + try { + JSONML.toJSONObject("??*^M??|?CglR^F??`??>?w??PIlr^E??D^X^]?$?-^R?o??O?*??{OD?^FY??`2a????NM?b^Tq?:O?>S$^K?J?^FB.gUK?m^H??zE??^??!v]?^A???^[^A??^U?c??????h???s???g^Z???`?q^Dbi??:^QZl?)?}1^??k?0??:$V?$?Ovs(}J??^V????2;^QgQ?^_^A?^D?^U?Tg?K?`?h%c?hmGA? Date: Tue, 17 Sep 2019 10:47:16 -0400 Subject: [PATCH 414/451] Test cases updates for standardized exception messages --- src/test/java/org/json/junit/JSONArrayTest.java | 8 ++++---- src/test/java/org/json/junit/JSONMLTest.java | 6 +++--- src/test/java/org/json/junit/JSONObjectTest.java | 12 ++++++------ 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 3b70446..5aef340 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -346,14 +346,14 @@ public class JSONArrayTest { assertTrue("expected getDouble to fail", false); } catch (JSONException e) { assertEquals("Expected an exception message", - "JSONArray[4] is not a number.",e.getMessage()); + "JSONArray[4] is not a double.",e.getMessage()); } try { jsonArray.getInt(4); assertTrue("expected getInt to fail", false); } catch (JSONException e) { assertEquals("Expected an exception message", - "JSONArray[4] is not a number.",e.getMessage()); + "JSONArray[4] is not a int.",e.getMessage()); } try { jsonArray.getJSONArray(4); @@ -374,14 +374,14 @@ public class JSONArrayTest { assertTrue("expected getLong to fail", false); } catch (JSONException e) { assertEquals("Expected an exception message", - "JSONArray[4] is not a number.",e.getMessage()); + "JSONArray[4] is not a long.",e.getMessage()); } try { jsonArray.getString(5); assertTrue("expected getString to fail", false); } catch (JSONException e) { assertEquals("Expected an exception message", - "JSONArray[5] not a string.",e.getMessage()); + "JSONArray[5] is not a String.",e.getMessage()); } } diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 84b33ba..fe3cd87 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -133,9 +133,9 @@ public class JSONMLTest { JSONML.toString(jsonArray); assertTrue("Expecting an exception", false); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONArray[0] not a string.". - equals(e.getMessage())); + assertEquals("Expecting an exception message", + "JSONArray[0] is not a String.", + e.getMessage()); } } diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 8d32649..ac67980 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1041,7 +1041,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "JSONObject[\"trueKey\"] not a string.", + "JSONObject[\"trueKey\"] is not a string.", e.getMessage()); } try { @@ -1057,7 +1057,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a number.", + "JSONObject[\"stringKey\"] is not a double.", e.getMessage()); } try { @@ -1073,7 +1073,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a number.", + "JSONObject[\"stringKey\"] is not a float.", e.getMessage()); } try { @@ -1089,7 +1089,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a number.", + "JSONObject[\"stringKey\"] is not a int.", e.getMessage()); } try { @@ -1105,7 +1105,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a number.", + "JSONObject[\"stringKey\"] is not a long.", e.getMessage()); } try { @@ -2087,7 +2087,7 @@ public class JSONObjectTest { fail("Expected an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "JSONObject[myKey] is not a JSONArray.", + "JSONObject[\"myKey\"] is not a JSONArray (null).", e.getMessage()); } try { From e9c27ab376ac4f253d7fafd26a62dcddc19e52c8 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 17 Sep 2019 10:49:29 -0400 Subject: [PATCH 415/451] standardize exception messages --- JSONArray.java | 93 +++++++++++++++++++++++++++++++------ JSONObject.java | 119 ++++++++++++++++++++++++++++++++++++------------ 2 files changed, 167 insertions(+), 45 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 537abb1..d46a768 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -249,7 +249,7 @@ public class JSONArray implements Iterable { .equalsIgnoreCase("true"))) { return true; } - throw new JSONException("JSONArray[" + index + "] is not a boolean."); + throw wrongValueFormatException(index, "boolean", null); } /** @@ -263,7 +263,15 @@ public class JSONArray implements Iterable { * to a number. */ public double getDouble(int index) throws JSONException { - return this.getNumber(index).doubleValue(); + final Object object = this.get(index); + if(object instanceof Number) { + return ((Number)object).doubleValue(); + } + try { + return Double.parseDouble(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(index, "double", e); + } } /** @@ -277,7 +285,15 @@ public class JSONArray implements Iterable { * object and cannot be converted to a number. */ public float getFloat(int index) throws JSONException { - return this.getNumber(index).floatValue(); + final Object object = this.get(index); + if(object instanceof Number) { + return ((Float)object).floatValue(); + } + try { + return Float.parseFloat(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(index, "float", e); + } } /** @@ -298,7 +314,7 @@ public class JSONArray implements Iterable { } return JSONObject.stringToNumber(object.toString()); } catch (Exception e) { - throw new JSONException("JSONArray[" + index + "] is not a number.", e); + throw wrongValueFormatException(index, "number", e); } } @@ -322,8 +338,8 @@ public class JSONArray implements Iterable { // JSONException should really take a throwable argument. // If it did, I would re-implement this with the Enum.valueOf // method and place any thrown exception in the JSONException - throw new JSONException("JSONArray[" + index + "] is not an enum of type " - + JSONObject.quote(clazz.getSimpleName()) + "."); + throw wrongValueFormatException(index, "enum of type " + + JSONObject.quote(clazz.getSimpleName()), null); } return val; } @@ -345,8 +361,7 @@ public class JSONArray implements Iterable { Object object = this.get(index); BigDecimal val = JSONObject.objectToBigDecimal(object, null); if(val == null) { - throw new JSONException("JSONArray[" + index + - "] could not convert to BigDecimal ("+ object + ")."); + throw wrongValueFormatException(index, "BigDecimal", object, null); } return val; } @@ -365,8 +380,7 @@ public class JSONArray implements Iterable { Object object = this.get(index); BigInteger val = JSONObject.objectToBigInteger(object, null); if(val == null) { - throw new JSONException("JSONArray[" + index + - "] could not convert to BigDecimal ("+ object + ")."); + throw wrongValueFormatException(index, "BigInteger", object, null); } return val; } @@ -381,7 +395,15 @@ public class JSONArray implements Iterable { * If the key is not found or if the value is not a number. */ public int getInt(int index) throws JSONException { - return this.getNumber(index).intValue(); + final Object object = this.get(index); + if(object instanceof Number) { + return ((Number)object).intValue(); + } + try { + return Integer.parseInt(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(index, "int", e); + } } /** @@ -399,7 +421,7 @@ public class JSONArray implements Iterable { if (object instanceof JSONArray) { return (JSONArray) object; } - throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); + throw wrongValueFormatException(index, "JSONArray", null); } /** @@ -417,7 +439,7 @@ public class JSONArray implements Iterable { if (object instanceof JSONObject) { return (JSONObject) object; } - throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); + throw wrongValueFormatException(index, "JSONObject", null); } /** @@ -431,7 +453,15 @@ public class JSONArray implements Iterable { * to a number. */ public long getLong(int index) throws JSONException { - return this.getNumber(index).longValue(); + final Object object = this.get(index); + if(object instanceof Number) { + return ((Number)object).longValue(); + } + try { + return Long.parseLong(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(index, "long", e); + } } /** @@ -448,7 +478,7 @@ public class JSONArray implements Iterable { if (object instanceof String) { return (String) object; } - throw new JSONException("JSONArray[" + index + "] not a string."); + throw wrongValueFormatException(index, "String", null); } /** @@ -1454,5 +1484,38 @@ public class JSONArray implements Iterable { public boolean isEmpty() { return this.myArrayList.isEmpty(); } + + /** + * Create a new JSONException in a common format for incorrect conversions. + * @param idx index of the item + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException( + int idx, + String valueType, + Throwable cause) { + return new JSONException( + "JSONArray[" + idx + "] is not a " + valueType + "." + , cause); + } + + /** + * Create a new JSONException in a common format for incorrect conversions. + * @param idx index of the item + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException( + int idx, + String valueType, + Object value, + Throwable cause) { + return new JSONException( + "JSONArray[" + idx + "] is not a " + valueType + " (" + value + ")." + , cause); + } } diff --git a/JSONObject.java b/JSONObject.java index c54018e..678a5d6 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -521,8 +521,7 @@ public class JSONObject { } else if (object instanceof JSONArray) { this.put(key, ((JSONArray) object).put(value)); } else { - throw new JSONException("JSONObject[" + key - + "] is not a JSONArray."); + throw wrongValueFormatException(key, "JSONArray", null, null); } return this; } @@ -595,9 +594,7 @@ public class JSONObject { // JSONException should really take a throwable argument. // If it did, I would re-implement this with the Enum.valueOf // method and place any thrown exception in the JSONException - throw new JSONException("JSONObject[" + quote(key) - + "] is not an enum of type " + quote(clazz.getSimpleName()) - + "."); + throw wrongValueFormatException(key, "enum of type " + quote(clazz.getSimpleName()), null); } return val; } @@ -623,8 +620,7 @@ public class JSONObject { .equalsIgnoreCase("true"))) { return true; } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a Boolean."); + throw wrongValueFormatException(key, "Boolean", null); } /** @@ -643,8 +639,7 @@ public class JSONObject { if (ret != null) { return ret; } - throw new JSONException("JSONObject[" + quote(key) - + "] could not be converted to BigInteger (" + object + ")."); + throw wrongValueFormatException(key, "BigInteger", object, null); } /** @@ -666,8 +661,7 @@ public class JSONObject { if (ret != null) { return ret; } - throw new JSONException("JSONObject[" + quote(key) - + "] could not be converted to BigDecimal (" + object + ")."); + throw wrongValueFormatException(key, "BigDecimal", object, null); } /** @@ -681,7 +675,15 @@ public class JSONObject { * object and cannot be converted to a number. */ public double getDouble(String key) throws JSONException { - return this.getNumber(key).doubleValue(); + final Object object = this.get(key); + if(object instanceof Number) { + return ((Number)object).doubleValue(); + } + try { + return Double.parseDouble(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "double", e); + } } /** @@ -695,7 +697,15 @@ public class JSONObject { * object and cannot be converted to a number. */ public float getFloat(String key) throws JSONException { - return this.getNumber(key).floatValue(); + final Object object = this.get(key); + if(object instanceof Number) { + return ((Number)object).floatValue(); + } + try { + return Float.parseFloat(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "float", e); + } } /** @@ -716,8 +726,7 @@ public class JSONObject { } return stringToNumber(object.toString()); } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] is not a number.", e); + throw wrongValueFormatException(key, "number", e); } } @@ -732,7 +741,15 @@ public class JSONObject { * to an integer. */ public int getInt(String key) throws JSONException { - return this.getNumber(key).intValue(); + final Object object = this.get(key); + if(object instanceof Number) { + return ((Number)object).intValue(); + } + try { + return Integer.parseInt(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "int", e); + } } /** @@ -749,8 +766,7 @@ public class JSONObject { if (object instanceof JSONArray) { return (JSONArray) object; } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a JSONArray."); + throw wrongValueFormatException(key, "JSONArray", null); } /** @@ -767,8 +783,7 @@ public class JSONObject { if (object instanceof JSONObject) { return (JSONObject) object; } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a JSONObject."); + throw wrongValueFormatException(key, "JSONObject", null); } /** @@ -782,7 +797,15 @@ public class JSONObject { * to a long. */ public long getLong(String key) throws JSONException { - return this.getNumber(key).longValue(); + final Object object = this.get(key); + if(object instanceof Number) { + return ((Number)object).longValue(); + } + try { + return Long.parseLong(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "long", e); + } } /** @@ -837,7 +860,7 @@ public class JSONObject { if (object instanceof String) { return (String) object; } - throw new JSONException("JSONObject[" + quote(key) + "] not a string."); + throw wrongValueFormatException(key, "string", null); } /** @@ -853,8 +876,11 @@ public class JSONObject { /** * Increment a property of a JSONObject. If there is no such property, - * create one with a value of 1. If there is such a property, and if it is - * an Integer, Long, Double, or Float, then add one to it. + * create one with a value of 1 (Integer). If there is such a property, and if it is + * an Integer, Long, Double, Float, BigInteger, or BigDecimal then add one to it. + * No overflow bounds checking is performed, so callers should initialize the key + * prior to this call with an appropriate type that can handle the maximum expected + * value. * * @param key * A key string. @@ -867,18 +893,18 @@ public class JSONObject { Object value = this.opt(key); if (value == null) { this.put(key, 1); - } else if (value instanceof BigInteger) { - this.put(key, ((BigInteger)value).add(BigInteger.ONE)); - } else if (value instanceof BigDecimal) { - this.put(key, ((BigDecimal)value).add(BigDecimal.ONE)); } else if (value instanceof Integer) { this.put(key, ((Integer) value).intValue() + 1); } else if (value instanceof Long) { this.put(key, ((Long) value).longValue() + 1L); - } else if (value instanceof Double) { - this.put(key, ((Double) value).doubleValue() + 1.0d); + } else if (value instanceof BigInteger) { + this.put(key, ((BigInteger)value).add(BigInteger.ONE)); } else if (value instanceof Float) { this.put(key, ((Float) value).floatValue() + 1.0f); + } else if (value instanceof Double) { + this.put(key, ((Double) value).doubleValue() + 1.0d); + } else if (value instanceof BigDecimal) { + this.put(key, ((BigDecimal)value).add(BigDecimal.ONE)); } else { throw new JSONException("Unable to increment [" + quote(key) + "]."); } @@ -2548,4 +2574,37 @@ public class JSONObject { } return results; } + + /** + * Create a new JSONException in a common format for incorrect conversions. + * @param key name of the key + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException( + String key, + String valueType, + Throwable cause) { + return new JSONException( + "JSONObject[" + quote(key) + "] is not a " + valueType + "." + , cause); + } + + /** + * Create a new JSONException in a common format for incorrect conversions. + * @param key name of the key + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException( + String key, + String valueType, + Object value, + Throwable cause) { + return new JSONException( + "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value + ")." + , cause); + } } From 67e59888a2764d5b36fa133473563d70da4136ac Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 17 Sep 2019 11:14:41 -0400 Subject: [PATCH 416/451] add second case for data in #484 --- src/test/java/org/json/junit/JSONMLTest.java | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 26f4f90..b7afe40 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -2,6 +2,8 @@ package org.json.junit; import static org.junit.Assert.*; +import java.util.Base64; + import org.json.*; import org.junit.Test; @@ -805,7 +807,7 @@ public class JSONMLTest { // } @Test (timeout = 6000) - public void testIssue484InfinteLoop() { + public void testIssue484InfinteLoop1() { try { JSONML.toJSONObject("??*^M??|?CglR^F??`??>?w??PIlr^E??D^X^]?$?-^R?o??O?*??{OD?^FY??`2a????NM?b^Tq?:O?>S$^K?J?^FB.gUK?m^H??zE??^??!v]?^A???^[^A??^U?c??????h???s???g^Z???`?q^Dbi??:^QZl?)?}1^??k?0??:$V?$?Ovs(}J??^V????2;^QgQ?^_^A?^D?^U?Tg?K?`?h%c?hmGA??w??PIlr??D?$?-?o??O?*??{OD?Y??`2a????NM?bq?:O?>S$ ?J?B.gUK?m\b??zE???!v]???????c??????h???s???g???`?qbi??:Zl?)?}1^??k?0??:$V?$?Ovs(}J??????2;gQ????Tg?K?`?h%c?hmGA? Date: Tue, 17 Sep 2019 11:15:25 -0400 Subject: [PATCH 417/451] remove unused import --- src/test/java/org/json/junit/JSONMLTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index b7afe40..3687fe5 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -2,8 +2,6 @@ package org.json.junit; import static org.junit.Assert.*; -import java.util.Base64; - import org.json.*; import org.junit.Test; From 223e328161f5d52fdc66935e3dbb7ff819ff8b73 Mon Sep 17 00:00:00 2001 From: scott Date: Wed, 16 Oct 2019 21:12:02 -0700 Subject: [PATCH 418/451] Replace JSONObject constructor string arrays with var args --- JSONObject.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index 678a5d6..a6bfcea 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -194,7 +194,7 @@ public class JSONObject { * @param names * An array of strings. */ - public JSONObject(JSONObject jo, String[] names) { + public JSONObject(JSONObject jo, String ... names) { this(names.length); for (int i = 0; i < names.length; i += 1) { try { @@ -378,7 +378,7 @@ public class JSONObject { * An array of strings, the names of the fields to be obtained * from the object. */ - public JSONObject(Object object, String names[]) { + public JSONObject(Object object, String ... names) { this(names.length); Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { From 065f9a94bca0ec21698d4e252e9b148899f420b6 Mon Sep 17 00:00:00 2001 From: gavriil Date: Tue, 29 Oct 2019 21:35:58 +0000 Subject: [PATCH 419/451] Issue-491 - modified the comment of JSONArray toList method to clarify what the output of the method is --- JSONArray.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JSONArray.java b/JSONArray.java index d46a768..14a1b01 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1454,7 +1454,7 @@ public class JSONArray implements Iterable { /** * Returns a java.util.List containing all of the elements in this array. * If an element in the array is a JSONArray or JSONObject it will also - * be converted. + * be converted to a List and a Map respectively. *

* Warning: This method assumes that the data structure is acyclical. * From 4990c3a180e0a2e866b13db21f04139a48b5a6d6 Mon Sep 17 00:00:00 2001 From: harkue Date: Tue, 12 Nov 2019 16:27:24 +0800 Subject: [PATCH 420/451] fix typo --- JSONArray.java | 12 ++++++------ JSONObject.java | 14 +++++++------- XML.java | 31 +++++++++++++++---------------- XMLTokener.java | 2 +- 4 files changed, 29 insertions(+), 30 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 14a1b01..10e08d2 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1409,7 +1409,7 @@ public class JSONArray implements Iterable { public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { - boolean commanate = false; + boolean hasComma = false; int length = this.length(); writer.write('['); @@ -1421,23 +1421,23 @@ public class JSONArray implements Iterable { throw new JSONException("Unable to write JSONArray value at index: 0", e); } } else if (length != 0) { - final int newindent = indent + indentFactor; + final int newIndent = indent + indentFactor; for (int i = 0; i < length; i += 1) { - if (commanate) { + if (hasComma) { writer.write(','); } if (indentFactor > 0) { writer.write('\n'); } - JSONObject.indent(writer, newindent); + JSONObject.indent(writer, newIndent); try { JSONObject.writeValue(writer, this.myArrayList.get(i), - indentFactor, newindent); + indentFactor, newIndent); } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: " + i, e); } - commanate = true; + hasComma = true; } if (indentFactor > 0) { writer.write('\n'); diff --git a/JSONObject.java b/JSONObject.java index a6bfcea..90de2e4 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -2141,7 +2141,7 @@ public class JSONObject { //} //return new BigInteger(val); - // BigInteger version: We use a similar bitLenth compare as + // BigInteger version: We use a similar bitLength compare as // BigInteger#intValueExact uses. Increases GC, but objects hold // only what they need. i.e. Less runtime overhead if the value is // long lived. Which is the better tradeoff? This is closer to what's @@ -2496,7 +2496,7 @@ public class JSONObject { public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { - boolean commanate = false; + boolean hasComma = false; final int length = this.length(); writer.write('{'); @@ -2514,15 +2514,15 @@ public class JSONObject { throw new JSONException("Unable to write JSONObject value for key: " + key, e); } } else if (length != 0) { - final int newindent = indent + indentFactor; + final int newIndent = indent + indentFactor; for (final Entry entry : this.entrySet()) { - if (commanate) { + if (hasComma) { writer.write(','); } if (indentFactor > 0) { writer.write('\n'); } - indent(writer, newindent); + indent(writer, newIndent); final String key = entry.getKey(); writer.write(quote(key)); writer.write(':'); @@ -2530,11 +2530,11 @@ public class JSONObject { writer.write(' '); } try { - writeValue(writer, entry.getValue(), indentFactor, newindent); + writeValue(writer, entry.getValue(), indentFactor, newIndent); } catch (Exception e) { throw new JSONException("Unable to write JSONObject value for key: " + key, e); } - commanate = true; + hasComma = true; } if (indentFactor > 0) { writer.write('\n'); diff --git a/XML.java b/XML.java index f660d23..f506f67 100644 --- a/XML.java +++ b/XML.java @@ -66,7 +66,7 @@ public class XML { public static final Character SLASH = '/'; /** - * Null attrubute name + * Null attribute name */ public static final String NULL_ATTR = "xsi:nil"; @@ -251,7 +251,7 @@ public class XML { throws JSONException { char c; int i; - JSONObject jsonobject = null; + JSONObject jsonObject = null; String string; String tagName; Object token; @@ -332,7 +332,7 @@ public class XML { } else { tagName = (String) token; token = null; - jsonobject = new JSONObject(); + jsonObject = new JSONObject(); boolean nilAttributeFound = false; for (;;) { if (token == null) { @@ -353,14 +353,14 @@ public class XML { && Boolean.parseBoolean((String) token)) { nilAttributeFound = true; } else if (!nilAttributeFound) { - jsonobject.accumulate(string, + jsonObject.accumulate(string, config.keepStrings ? ((String) token) : stringToValue((String) token)); } token = null; } else { - jsonobject.accumulate(string, ""); + jsonObject.accumulate(string, ""); } @@ -371,8 +371,8 @@ public class XML { } if (nilAttributeFound) { context.accumulate(tagName, JSONObject.NULL); - } else if (jsonobject.length() > 0) { - context.accumulate(tagName, jsonobject); + } else if (jsonObject.length() > 0) { + context.accumulate(tagName, jsonObject); } else { context.accumulate(tagName, ""); } @@ -390,21 +390,20 @@ public class XML { } else if (token instanceof String) { string = (String) token; if (string.length() > 0) { - jsonobject.accumulate(config.cDataTagName, + jsonObject.accumulate(config.cDataTagName, config.keepStrings ? string : stringToValue(string)); } } else if (token == LT) { // Nested element - if (parse(x, jsonobject, tagName, config)) { - if (jsonobject.length() == 0) { + if (parse(x, jsonObject, tagName, config)) { + if (jsonObject.length() == 0) { context.accumulate(tagName, ""); - } else if (jsonobject.length() == 1 - && jsonobject.opt(config.cDataTagName) != null) { - context.accumulate(tagName, - jsonobject.opt(config.cDataTagName)); + } else if (jsonObject.length() == 1 + && jsonObject.opt(config.cDataTagName) != null) { + context.accumulate(tagName, jsonObject.opt(config.cDataTagName)); } else { - context.accumulate(tagName, jsonobject); + context.accumulate(tagName, jsonObject); } return false; } @@ -731,7 +730,7 @@ public class XML { } if (tagName != null) { - // Emit the close tag + // Emit the close tag sb.append("'); diff --git a/XMLTokener.java b/XMLTokener.java index d733447..a9d20b7 100644 --- a/XMLTokener.java +++ b/XMLTokener.java @@ -152,7 +152,7 @@ public class XMLTokener extends JSONTokener { } /** - * Unescapes an XML entity encoding; + * Unescape an XML entity encoding; * @param e entity (only the actual entity value, not the preceding & or ending ; * @return */ From e62d763294cc5a7c28425a48ac72e9aad83e65d4 Mon Sep 17 00:00:00 2001 From: harkue Date: Wed, 13 Nov 2019 11:46:21 +0800 Subject: [PATCH 421/451] rename `hasComma` as a better name "needsComma" --- JSONArray.java | 6 +++--- JSONObject.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/JSONArray.java b/JSONArray.java index 10e08d2..8847c5d 100644 --- a/JSONArray.java +++ b/JSONArray.java @@ -1409,7 +1409,7 @@ public class JSONArray implements Iterable { public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { - boolean hasComma = false; + boolean needsComma = false; int length = this.length(); writer.write('['); @@ -1424,7 +1424,7 @@ public class JSONArray implements Iterable { final int newIndent = indent + indentFactor; for (int i = 0; i < length; i += 1) { - if (hasComma) { + if (needsComma) { writer.write(','); } if (indentFactor > 0) { @@ -1437,7 +1437,7 @@ public class JSONArray implements Iterable { } catch (Exception e) { throw new JSONException("Unable to write JSONArray value at index: " + i, e); } - hasComma = true; + needsComma = true; } if (indentFactor > 0) { writer.write('\n'); diff --git a/JSONObject.java b/JSONObject.java index 90de2e4..399dfe4 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -2496,7 +2496,7 @@ public class JSONObject { public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { - boolean hasComma = false; + boolean needsComma = false; final int length = this.length(); writer.write('{'); @@ -2516,7 +2516,7 @@ public class JSONObject { } else if (length != 0) { final int newIndent = indent + indentFactor; for (final Entry entry : this.entrySet()) { - if (hasComma) { + if (needsComma) { writer.write(','); } if (indentFactor > 0) { @@ -2534,7 +2534,7 @@ public class JSONObject { } catch (Exception e) { throw new JSONException("Unable to write JSONObject value for key: " + key, e); } - hasComma = true; + needsComma = true; } if (indentFactor > 0) { writer.write('\n'); From 6f068012966fcb5c460b9f3568107c65edd08e89 Mon Sep 17 00:00:00 2001 From: Alanscut Date: Sun, 22 Dec 2019 19:17:58 +0800 Subject: [PATCH 422/451] add copyright --- JSONException.java | 24 ++++++++++++++++++++++++ JSONString.java | 25 +++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/JSONException.java b/JSONException.java index 72542df..ab7ff77 100644 --- a/JSONException.java +++ b/JSONException.java @@ -1,5 +1,29 @@ package org.json; +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + */ + /** * The JSONException is thrown by the JSON.org classes when things are amiss. * diff --git a/JSONString.java b/JSONString.java index 1f2d77d..bcd9a81 100644 --- a/JSONString.java +++ b/JSONString.java @@ -1,4 +1,29 @@ package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + */ + /** * The JSONString interface allows a toJSONString() * method so that a class can change the behavior of From 6ecbeaa0d296efafc15d5353edeae06b9e4a2765 Mon Sep 17 00:00:00 2001 From: Alanscut Date: Wed, 25 Dec 2019 11:38:38 +0800 Subject: [PATCH 423/451] update JSONTokener's brief: parse simple json text --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0301dcb..591fb91 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,9 @@ to produce a vector-like object. The object provides methods for manipulating its contents, and for producing a JSON compliant array serialization. **JSONTokener.java**: The `JSONTokener` breaks a text into a sequence of individual -tokens. It can be constructed from a `String`, `Reader`, or `InputStream`. +tokens. It can be constructed from a `String`, `Reader`, or `InputStream`. It also can +parse text from a `String`, `Number`, `Boolean` or `null` like `"hello"`, `42`, `true`, +`null` to produce a simple json object. **JSONException.java**: The `JSONException` is the standard exception type thrown by this package. From 16da56eb34b6036f145dea7e6bf638b6ad418b5e Mon Sep 17 00:00:00 2001 From: Alanscut Date: Sat, 28 Dec 2019 17:53:27 +0800 Subject: [PATCH 424/451] improve the confused assert message --- .../java/org/json/junit/JSONObjectTest.java | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index ac67980..438e55e 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -589,19 +589,19 @@ public class JSONObjectTest { jsonObject.has("someString")); assertFalse("Normal field name (myDouble) processing did not work", jsonObject.has("myDouble")); - assertFalse("Normal field name (someFloat) found", + assertFalse("Normal field name (someFloat) processing did not work", jsonObject.has("someFloat")); - assertFalse("Ignored field found!", + assertFalse("Ignored field not found!", jsonObject.has("ignoredInt")); - assertTrue("Normal field name (someInt) processing did not work", + assertTrue("Normal field name (someInt) found", jsonObject.has("someInt")); - assertTrue("Normal field name (someLong) processing did not work", + assertTrue("Normal field name (someLong) found", jsonObject.has("someLong")); - assertTrue("Overridden String field name (myStringField) not found", + assertTrue("Overridden String field name (myStringField) found", jsonObject.has("myStringField")); - assertTrue("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) not found", + assertTrue("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) found", jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!")); - assertTrue("Overridden String field name (InterfaceField) not found", + assertTrue("Overridden String field name (InterfaceField) found", jsonObject.has("InterfaceField")); } @@ -619,26 +619,29 @@ public class JSONObjectTest { jsonObject.has("someInt")); assertFalse("Normal field name (myDouble) processing did not work", jsonObject.has("myDouble")); - assertFalse("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) FOUND!", + assertFalse("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) not FOUND!", jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!")); - assertFalse("Normal field name (someFloat) found", + assertFalse("Normal field name (someFloat) found, but was overridden", jsonObject.has("someFloat")); - assertFalse("Ignored field found!", + assertFalse("Ignored field found! but was overridden", jsonObject.has("ignoredInt")); - assertFalse("Ignored field at the same level as forced name found", + assertFalse("Ignored field at the same level as forced name not found", jsonObject.has("ShouldBeIgnored")); - assertTrue("Overridden int field name (newIntFieldName) not found", + assertFalse("Normally ignored field (able) with explicit property name not found", + jsonObject.has("able")); + assertTrue("Overridden int field name (newIntFieldName) found", jsonObject.has("newIntFieldName")); - assertTrue("Normal field name (someLong) processing did not work", + assertTrue("Normal field name (someLong) found", jsonObject.has("someLong")); - assertTrue("Overridden String field name (myStringField) not found", + assertTrue("Overridden String field name (myStringField) found", jsonObject.has("myStringField")); - assertTrue(jsonObject.has("AMoreNormalName")); - assertTrue("Overridden String field name (InterfaceField) not found", + assertTrue("Overridden double field name (AMoreNormalName) found", + jsonObject.has("AMoreNormalName")); + assertTrue("Overridden String field name (InterfaceField) found", jsonObject.has("InterfaceField")); - assertTrue("Forced field not found!", + assertTrue("Forced field found!", jsonObject.has("forcedInt")); - assertTrue("Normally ignored field (getable) with explicit property name not found", + assertTrue("Overridden boolean field name (Getable) found", jsonObject.has("Getable")); } From 08719d4b3a6d73918631297030e8e03cc960de24 Mon Sep 17 00:00:00 2001 From: Alan Wang <948467222@qq.com> Date: Mon, 30 Dec 2019 09:51:08 +0800 Subject: [PATCH 425/451] Apply suggestions from code review Co-Authored-By: Sean Leary --- .../java/org/json/junit/JSONObjectTest.java | 45 ++++++++++++------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 438e55e..b2f501e 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -593,15 +593,20 @@ public class JSONObjectTest { jsonObject.has("someFloat")); assertFalse("Ignored field not found!", jsonObject.has("ignoredInt")); - assertTrue("Normal field name (someInt) found", + // getSomeInt() has no user-defined annotation + assertTrue("Normal field name (someInt) should have been found", jsonObject.has("someInt")); - assertTrue("Normal field name (someLong) found", + // the user-defined annotation does not replace any value, so someLong should be found + assertTrue("Normal field name (someLong) should have been found", jsonObject.has("someLong")); - assertTrue("Overridden String field name (myStringField) found", + // myStringField replaces someString property name via user-defined annotation + assertTrue("Overridden String field name (myStringField) should have been found", jsonObject.has("myStringField")); - assertTrue("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) found", + // weird name replaces myDouble property name via user-defined annotation + assertTrue("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) should have been found", jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!")); - assertTrue("Overridden String field name (InterfaceField) found", + // InterfaceField replaces someFloat property name via user-defined annotation + assertTrue("Overridden String field name (InterfaceField) should have been found", jsonObject.has("InterfaceField")); } @@ -619,29 +624,39 @@ public class JSONObjectTest { jsonObject.has("someInt")); assertFalse("Normal field name (myDouble) processing did not work", jsonObject.has("myDouble")); - assertFalse("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) not FOUND!", + // myDouble was replaced by weird name, and then replaced again by AMoreNormalName via user-defined annotation + assertFalse("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) should not be FOUND!", jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!")); assertFalse("Normal field name (someFloat) found, but was overridden", jsonObject.has("someFloat")); assertFalse("Ignored field found! but was overridden", jsonObject.has("ignoredInt")); - assertFalse("Ignored field at the same level as forced name not found", + // shouldNotBeJSON property name was first ignored, then replaced by ShouldBeIgnored via user-defined annotations + assertFalse("Ignored field at the same level as forced name should not have been found", jsonObject.has("ShouldBeIgnored")); - assertFalse("Normally ignored field (able) with explicit property name not found", + // able property name was replaced by Getable via user-defined annotation + assertFalse("Normally ignored field (able) with explicit property name should not have been found", jsonObject.has("able")); - assertTrue("Overridden int field name (newIntFieldName) found", + // property name someInt was replaced by newIntFieldName via user-defined annotation + assertTrue("Overridden int field name (newIntFieldName) should have been found", jsonObject.has("newIntFieldName")); - assertTrue("Normal field name (someLong) found", + // property name someLong was not replaced via user-defined annotation + assertTrue("Normal field name (someLong) should have been found", jsonObject.has("someLong")); - assertTrue("Overridden String field name (myStringField) found", + // property name someString was replaced by myStringField via user-defined annotation + assertTrue("Overridden String field name (myStringField) should have been found", jsonObject.has("myStringField")); - assertTrue("Overridden double field name (AMoreNormalName) found", + // property name myDouble was replaced by a weird name, followed by AMoreNormalName via user-defined annotations + assertTrue("Overridden double field name (AMoreNormalName) should have been found", jsonObject.has("AMoreNormalName")); - assertTrue("Overridden String field name (InterfaceField) found", + // property name someFloat was replaced by InterfaceField via user-defined annotation + assertTrue("Overridden String field name (InterfaceField) should have been found", jsonObject.has("InterfaceField")); - assertTrue("Forced field found!", + // property name ignoredInt was replaced by none, followed by forcedInt via user-defined annotations + assertTrue("Forced field should have been found!", jsonObject.has("forcedInt")); - assertTrue("Overridden boolean field name (Getable) found", + // property name able was replaced by Getable via user-defined annotation + assertTrue("Overridden boolean field name (Getable) should have been found", jsonObject.has("Getable")); } From 74e4932cfc74e084706564d1b82c1567bf4fa35e Mon Sep 17 00:00:00 2001 From: Benjamin Gehrels Date: Wed, 29 Apr 2020 19:24:44 +0200 Subject: [PATCH 426/451] Transform the repository into standard maven format and merge the pom.xml of the release repo --- .gitignore | 1 + pom.xml | 192 ++++ CDL.java => src/main/java/org/json/CDL.java | 0 .../main/java/org/json/Cookie.java | 0 .../main/java/org/json/CookieList.java | 0 HTTP.java => src/main/java/org/json/HTTP.java | 324 +++---- .../main/java/org/json/HTTPTokener.java | 0 .../main/java/org/json/JSONArray.java | 0 .../main/java/org/json/JSONException.java | 0 .../main/java/org/json/JSONML.java | 0 .../main/java/org/json/JSONObject.java | 0 .../main/java/org/json/JSONPointer.java | 0 .../java/org/json/JSONPointerException.java | 0 .../java/org/json/JSONPropertyIgnore.java | 0 .../main/java/org/json/JSONPropertyName.java | 0 .../main/java/org/json/JSONString.java | 0 .../main/java/org/json/JSONStringer.java | 158 ++-- .../main/java/org/json/JSONTokener.java | 0 .../main/java/org/json/JSONWriter.java | 826 +++++++++--------- .../main/java/org/json/Property.java | 0 XML.java => src/main/java/org/json/XML.java | 0 .../java/org/json/XMLParserConfiguration.java | 0 .../main/java/org/json/XMLTokener.java | 0 23 files changed, 847 insertions(+), 654 deletions(-) create mode 100644 pom.xml rename CDL.java => src/main/java/org/json/CDL.java (100%) rename Cookie.java => src/main/java/org/json/Cookie.java (100%) rename CookieList.java => src/main/java/org/json/CookieList.java (100%) rename HTTP.java => src/main/java/org/json/HTTP.java (97%) rename HTTPTokener.java => src/main/java/org/json/HTTPTokener.java (100%) rename JSONArray.java => src/main/java/org/json/JSONArray.java (100%) rename JSONException.java => src/main/java/org/json/JSONException.java (100%) rename JSONML.java => src/main/java/org/json/JSONML.java (100%) rename JSONObject.java => src/main/java/org/json/JSONObject.java (100%) rename JSONPointer.java => src/main/java/org/json/JSONPointer.java (100%) rename JSONPointerException.java => src/main/java/org/json/JSONPointerException.java (100%) rename JSONPropertyIgnore.java => src/main/java/org/json/JSONPropertyIgnore.java (100%) rename JSONPropertyName.java => src/main/java/org/json/JSONPropertyName.java (100%) rename JSONString.java => src/main/java/org/json/JSONString.java (100%) rename JSONStringer.java => src/main/java/org/json/JSONStringer.java (97%) rename JSONTokener.java => src/main/java/org/json/JSONTokener.java (100%) rename JSONWriter.java => src/main/java/org/json/JSONWriter.java (97%) rename Property.java => src/main/java/org/json/Property.java (100%) rename XML.java => src/main/java/org/json/XML.java (100%) rename XMLParserConfiguration.java => src/main/java/org/json/XMLParserConfiguration.java (100%) rename XMLTokener.java => src/main/java/org/json/XMLTokener.java (100%) diff --git a/.gitignore b/.gitignore index 50b216e..4f807a9 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ # ignore Intellij Idea project files .idea *.iml +/target/ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..c2579f2 --- /dev/null +++ b/pom.xml @@ -0,0 +1,192 @@ + + 4.0.0 + + org.json + json + v20200429-SNAPSHOT + bundle + + JSON in Java + + JSON is a light-weight, language independent, data interchange format. + See http://www.JSON.org/ + + The files in this package implement JSON encoders/decoders in Java. + It also includes the capability to convert between JSON and XML, HTTP + headers, Cookies, and CDL. + + This is a reference implementation. There is a large number of JSON packages + in Java. Perhaps someday the Java community will standardize on one. Until + then, choose carefully. + + The license includes this restriction: "The software shall be used for good, + not evil." If your conscience cannot live with that, then choose a different + package. + + https://github.com/douglascrockford/JSON-java + + + org.sonatype.oss + oss-parent + 9 + + + + https://github.com/douglascrockford/JSON-java.git + scm:git:git://github.com/douglascrockford/JSON-java.git + scm:git:git@github.com:douglascrockford/JSON-java.git + + + + + The JSON License + http://json.org/license.html + repo + Copyright (c) 2002 JSON.org + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and + associated documentation files (the "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial + portions of the Software. + + The Software shall be used for Good, not Evil. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT + LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + + + + Douglas Crockford + douglas@crockford.com + + + + + UTF-8 + + + + + + junit + junit + 4.12 + test + + + com.jayway.jsonpath + json-path + 2.1.0 + test + + + org.mockito + mockito-core + 1.9.5 + test + + + + + + + org.apache.felix + maven-bundle-plugin + 3.0.1 + true + + + + org.json + + ${project.artifactId} + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.7 + 1.7 + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.7 + + + attach-javadocs + + jar + + + -Xdoclint:none + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.3 + true + + ossrh + https://oss.sonatype.org/ + false + + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.json + + + + + + + diff --git a/CDL.java b/src/main/java/org/json/CDL.java similarity index 100% rename from CDL.java rename to src/main/java/org/json/CDL.java diff --git a/Cookie.java b/src/main/java/org/json/Cookie.java similarity index 100% rename from Cookie.java rename to src/main/java/org/json/Cookie.java diff --git a/CookieList.java b/src/main/java/org/json/CookieList.java similarity index 100% rename from CookieList.java rename to src/main/java/org/json/CookieList.java diff --git a/HTTP.java b/src/main/java/org/json/HTTP.java similarity index 97% rename from HTTP.java rename to src/main/java/org/json/HTTP.java index 70b88ee..84ed53b 100644 --- a/HTTP.java +++ b/src/main/java/org/json/HTTP.java @@ -1,162 +1,162 @@ -package org.json; - -/* -Copyright (c) 2002 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import java.util.Locale; - -/** - * Convert an HTTP header to a JSONObject and back. - * @author JSON.org - * @version 2015-12-09 - */ -public class HTTP { - - /** Carriage return/line feed. */ - public static final String CRLF = "\r\n"; - - /** - * Convert an HTTP header string into a JSONObject. It can be a request - * header or a response header. A request header will contain - *
{
-     *    Method: "POST" (for example),
-     *    "Request-URI": "/" (for example),
-     *    "HTTP-Version": "HTTP/1.1" (for example)
-     * }
- * A response header will contain - *
{
-     *    "HTTP-Version": "HTTP/1.1" (for example),
-     *    "Status-Code": "200" (for example),
-     *    "Reason-Phrase": "OK" (for example)
-     * }
- * In addition, the other parameters in the header will be captured, using - * the HTTP field names as JSON names, so that
-     *    Date: Sun, 26 May 2002 18:06:04 GMT
-     *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
-     *    Cache-Control: no-cache
- * become - *
{...
-     *    Date: "Sun, 26 May 2002 18:06:04 GMT",
-     *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
-     *    "Cache-Control": "no-cache",
-     * ...}
- * It does no further checking or conversion. It does not parse dates. - * It does not do '%' transforms on URLs. - * @param string An HTTP header string. - * @return A JSONObject containing the elements and attributes - * of the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - HTTPTokener x = new HTTPTokener(string); - String token; - - token = x.nextToken(); - if (token.toUpperCase(Locale.ROOT).startsWith("HTTP")) { - -// Response - - jo.put("HTTP-Version", token); - jo.put("Status-Code", x.nextToken()); - jo.put("Reason-Phrase", x.nextTo('\0')); - x.next(); - - } else { - -// Request - - jo.put("Method", token); - jo.put("Request-URI", x.nextToken()); - jo.put("HTTP-Version", x.nextToken()); - } - -// Fields - - while (x.more()) { - String name = x.nextTo(':'); - x.next(':'); - jo.put(name, x.nextTo('\0')); - x.next(); - } - return jo; - } - - - /** - * Convert a JSONObject into an HTTP header. A request header must contain - *
{
-     *    Method: "POST" (for example),
-     *    "Request-URI": "/" (for example),
-     *    "HTTP-Version": "HTTP/1.1" (for example)
-     * }
- * A response header must contain - *
{
-     *    "HTTP-Version": "HTTP/1.1" (for example),
-     *    "Status-Code": "200" (for example),
-     *    "Reason-Phrase": "OK" (for example)
-     * }
- * Any other members of the JSONObject will be output as HTTP fields. - * The result will end with two CRLF pairs. - * @param jo A JSONObject - * @return An HTTP header string. - * @throws JSONException if the object does not contain enough - * information. - */ - public static String toString(JSONObject jo) throws JSONException { - StringBuilder sb = new StringBuilder(); - if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { - sb.append(jo.getString("HTTP-Version")); - sb.append(' '); - sb.append(jo.getString("Status-Code")); - sb.append(' '); - sb.append(jo.getString("Reason-Phrase")); - } else if (jo.has("Method") && jo.has("Request-URI")) { - sb.append(jo.getString("Method")); - sb.append(' '); - sb.append('"'); - sb.append(jo.getString("Request-URI")); - sb.append('"'); - sb.append(' '); - sb.append(jo.getString("HTTP-Version")); - } else { - throw new JSONException("Not enough material for an HTTP header."); - } - sb.append(CRLF); - // Don't use the new entrySet API to maintain Android support - for (final String key : jo.keySet()) { - String value = jo.optString(key); - if (!"HTTP-Version".equals(key) && !"Status-Code".equals(key) && - !"Reason-Phrase".equals(key) && !"Method".equals(key) && - !"Request-URI".equals(key) && !JSONObject.NULL.equals(value)) { - sb.append(key); - sb.append(": "); - sb.append(jo.optString(key)); - sb.append(CRLF); - } - } - sb.append(CRLF); - return sb.toString(); - } -} +package org.json; + +/* +Copyright (c) 2002 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.util.Locale; + +/** + * Convert an HTTP header to a JSONObject and back. + * @author JSON.org + * @version 2015-12-09 + */ +public class HTTP { + + /** Carriage return/line feed. */ + public static final String CRLF = "\r\n"; + + /** + * Convert an HTTP header string into a JSONObject. It can be a request + * header or a response header. A request header will contain + *
{
+     *    Method: "POST" (for example),
+     *    "Request-URI": "/" (for example),
+     *    "HTTP-Version": "HTTP/1.1" (for example)
+     * }
+ * A response header will contain + *
{
+     *    "HTTP-Version": "HTTP/1.1" (for example),
+     *    "Status-Code": "200" (for example),
+     *    "Reason-Phrase": "OK" (for example)
+     * }
+ * In addition, the other parameters in the header will be captured, using + * the HTTP field names as JSON names, so that
+     *    Date: Sun, 26 May 2002 18:06:04 GMT
+     *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
+     *    Cache-Control: no-cache
+ * become + *
{...
+     *    Date: "Sun, 26 May 2002 18:06:04 GMT",
+     *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
+     *    "Cache-Control": "no-cache",
+     * ...}
+ * It does no further checking or conversion. It does not parse dates. + * It does not do '%' transforms on URLs. + * @param string An HTTP header string. + * @return A JSONObject containing the elements and attributes + * of the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + JSONObject jo = new JSONObject(); + HTTPTokener x = new HTTPTokener(string); + String token; + + token = x.nextToken(); + if (token.toUpperCase(Locale.ROOT).startsWith("HTTP")) { + +// Response + + jo.put("HTTP-Version", token); + jo.put("Status-Code", x.nextToken()); + jo.put("Reason-Phrase", x.nextTo('\0')); + x.next(); + + } else { + +// Request + + jo.put("Method", token); + jo.put("Request-URI", x.nextToken()); + jo.put("HTTP-Version", x.nextToken()); + } + +// Fields + + while (x.more()) { + String name = x.nextTo(':'); + x.next(':'); + jo.put(name, x.nextTo('\0')); + x.next(); + } + return jo; + } + + + /** + * Convert a JSONObject into an HTTP header. A request header must contain + *
{
+     *    Method: "POST" (for example),
+     *    "Request-URI": "/" (for example),
+     *    "HTTP-Version": "HTTP/1.1" (for example)
+     * }
+ * A response header must contain + *
{
+     *    "HTTP-Version": "HTTP/1.1" (for example),
+     *    "Status-Code": "200" (for example),
+     *    "Reason-Phrase": "OK" (for example)
+     * }
+ * Any other members of the JSONObject will be output as HTTP fields. + * The result will end with two CRLF pairs. + * @param jo A JSONObject + * @return An HTTP header string. + * @throws JSONException if the object does not contain enough + * information. + */ + public static String toString(JSONObject jo) throws JSONException { + StringBuilder sb = new StringBuilder(); + if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { + sb.append(jo.getString("HTTP-Version")); + sb.append(' '); + sb.append(jo.getString("Status-Code")); + sb.append(' '); + sb.append(jo.getString("Reason-Phrase")); + } else if (jo.has("Method") && jo.has("Request-URI")) { + sb.append(jo.getString("Method")); + sb.append(' '); + sb.append('"'); + sb.append(jo.getString("Request-URI")); + sb.append('"'); + sb.append(' '); + sb.append(jo.getString("HTTP-Version")); + } else { + throw new JSONException("Not enough material for an HTTP header."); + } + sb.append(CRLF); + // Don't use the new entrySet API to maintain Android support + for (final String key : jo.keySet()) { + String value = jo.optString(key); + if (!"HTTP-Version".equals(key) && !"Status-Code".equals(key) && + !"Reason-Phrase".equals(key) && !"Method".equals(key) && + !"Request-URI".equals(key) && !JSONObject.NULL.equals(value)) { + sb.append(key); + sb.append(": "); + sb.append(jo.optString(key)); + sb.append(CRLF); + } + } + sb.append(CRLF); + return sb.toString(); + } +} diff --git a/HTTPTokener.java b/src/main/java/org/json/HTTPTokener.java similarity index 100% rename from HTTPTokener.java rename to src/main/java/org/json/HTTPTokener.java diff --git a/JSONArray.java b/src/main/java/org/json/JSONArray.java similarity index 100% rename from JSONArray.java rename to src/main/java/org/json/JSONArray.java diff --git a/JSONException.java b/src/main/java/org/json/JSONException.java similarity index 100% rename from JSONException.java rename to src/main/java/org/json/JSONException.java diff --git a/JSONML.java b/src/main/java/org/json/JSONML.java similarity index 100% rename from JSONML.java rename to src/main/java/org/json/JSONML.java diff --git a/JSONObject.java b/src/main/java/org/json/JSONObject.java similarity index 100% rename from JSONObject.java rename to src/main/java/org/json/JSONObject.java diff --git a/JSONPointer.java b/src/main/java/org/json/JSONPointer.java similarity index 100% rename from JSONPointer.java rename to src/main/java/org/json/JSONPointer.java diff --git a/JSONPointerException.java b/src/main/java/org/json/JSONPointerException.java similarity index 100% rename from JSONPointerException.java rename to src/main/java/org/json/JSONPointerException.java diff --git a/JSONPropertyIgnore.java b/src/main/java/org/json/JSONPropertyIgnore.java similarity index 100% rename from JSONPropertyIgnore.java rename to src/main/java/org/json/JSONPropertyIgnore.java diff --git a/JSONPropertyName.java b/src/main/java/org/json/JSONPropertyName.java similarity index 100% rename from JSONPropertyName.java rename to src/main/java/org/json/JSONPropertyName.java diff --git a/JSONString.java b/src/main/java/org/json/JSONString.java similarity index 100% rename from JSONString.java rename to src/main/java/org/json/JSONString.java diff --git a/JSONStringer.java b/src/main/java/org/json/JSONStringer.java similarity index 97% rename from JSONStringer.java rename to src/main/java/org/json/JSONStringer.java index 6e05d22..bb9e7a4 100644 --- a/JSONStringer.java +++ b/src/main/java/org/json/JSONStringer.java @@ -1,79 +1,79 @@ -package org.json; - -/* -Copyright (c) 2006 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import java.io.StringWriter; - -/** - * JSONStringer provides a quick and convenient way of producing JSON text. - * The texts produced strictly conform to JSON syntax rules. No whitespace is - * added, so the results are ready for transmission or storage. Each instance of - * JSONStringer can produce one JSON text. - *

- * A JSONStringer instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting cascade style. For example,

- * myString = new JSONStringer()
- *     .object()
- *         .key("JSON")
- *         .value("Hello, World!")
- *     .endObject()
- *     .toString();
which produces the string
- * {"JSON":"Hello, World!"}
- *

- * The first method called must be array or object. - * There are no methods for adding commas or colons. JSONStringer adds them for - * you. Objects and arrays can be nested up to 20 levels deep. - *

- * This can sometimes be easier than using a JSONObject to build a string. - * @author JSON.org - * @version 2015-12-09 - */ -public class JSONStringer extends JSONWriter { - /** - * Make a fresh JSONStringer. It can be used to build one JSON text. - */ - public JSONStringer() { - super(new StringWriter()); - } - - /** - * Return the JSON text. This method is used to obtain the product of the - * JSONStringer instance. It will return null if there was a - * problem in the construction of the JSON text (such as the calls to - * array were not properly balanced with calls to - * endArray). - * @return The JSON text. - */ - @Override - public String toString() { - return this.mode == 'd' ? this.writer.toString() : null; - } -} +package org.json; + +/* +Copyright (c) 2006 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import java.io.StringWriter; + +/** + * JSONStringer provides a quick and convenient way of producing JSON text. + * The texts produced strictly conform to JSON syntax rules. No whitespace is + * added, so the results are ready for transmission or storage. Each instance of + * JSONStringer can produce one JSON text. + *

+ * A JSONStringer instance provides a value method for appending + * values to the + * text, and a key + * method for adding keys before values in objects. There are array + * and endArray methods that make and bound array values, and + * object and endObject methods which make and bound + * object values. All of these methods return the JSONWriter instance, + * permitting cascade style. For example,

+ * myString = new JSONStringer()
+ *     .object()
+ *         .key("JSON")
+ *         .value("Hello, World!")
+ *     .endObject()
+ *     .toString();
which produces the string
+ * {"JSON":"Hello, World!"}
+ *

+ * The first method called must be array or object. + * There are no methods for adding commas or colons. JSONStringer adds them for + * you. Objects and arrays can be nested up to 20 levels deep. + *

+ * This can sometimes be easier than using a JSONObject to build a string. + * @author JSON.org + * @version 2015-12-09 + */ +public class JSONStringer extends JSONWriter { + /** + * Make a fresh JSONStringer. It can be used to build one JSON text. + */ + public JSONStringer() { + super(new StringWriter()); + } + + /** + * Return the JSON text. This method is used to obtain the product of the + * JSONStringer instance. It will return null if there was a + * problem in the construction of the JSON text (such as the calls to + * array were not properly balanced with calls to + * endArray). + * @return The JSON text. + */ + @Override + public String toString() { + return this.mode == 'd' ? this.writer.toString() : null; + } +} diff --git a/JSONTokener.java b/src/main/java/org/json/JSONTokener.java similarity index 100% rename from JSONTokener.java rename to src/main/java/org/json/JSONTokener.java diff --git a/JSONWriter.java b/src/main/java/org/json/JSONWriter.java similarity index 97% rename from JSONWriter.java rename to src/main/java/org/json/JSONWriter.java index 19f2dc8..b61a6f1 100644 --- a/JSONWriter.java +++ b/src/main/java/org/json/JSONWriter.java @@ -1,413 +1,413 @@ -package org.json; - -import java.io.IOException; -import java.util.Collection; -import java.util.Map; - -/* -Copyright (c) 2006 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/** - * JSONWriter provides a quick and convenient way of producing JSON text. - * The texts produced strictly conform to JSON syntax rules. No whitespace is - * added, so the results are ready for transmission or storage. Each instance of - * JSONWriter can produce one JSON text. - *

- * A JSONWriter instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting a cascade style. For example,

- * new JSONWriter(myWriter)
- *     .object()
- *         .key("JSON")
- *         .value("Hello, World!")
- *     .endObject();
which writes
- * {"JSON":"Hello, World!"}
- *

- * The first method called must be array or object. - * There are no methods for adding commas or colons. JSONWriter adds them for - * you. Objects and arrays can be nested up to 200 levels deep. - *

- * This can sometimes be easier than using a JSONObject to build a string. - * @author JSON.org - * @version 2016-08-08 - */ -public class JSONWriter { - private static final int maxdepth = 200; - - /** - * The comma flag determines if a comma should be output before the next - * value. - */ - private boolean comma; - - /** - * The current mode. Values: - * 'a' (array), - * 'd' (done), - * 'i' (initial), - * 'k' (key), - * 'o' (object). - */ - protected char mode; - - /** - * The object/array stack. - */ - private final JSONObject stack[]; - - /** - * The stack top index. A value of 0 indicates that the stack is empty. - */ - private int top; - - /** - * The writer that will receive the output. - */ - protected Appendable writer; - - /** - * Make a fresh JSONWriter. It can be used to build one JSON text. - */ - public JSONWriter(Appendable w) { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; - } - - /** - * Append a value. - * @param string A string value. - * @return this - * @throws JSONException If the value is out of sequence. - */ - private JSONWriter append(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null pointer"); - } - if (this.mode == 'o' || this.mode == 'a') { - try { - if (this.comma && this.mode == 'a') { - this.writer.append(','); - } - this.writer.append(string); - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - if (this.mode == 'o') { - this.mode = 'k'; - } - this.comma = true; - return this; - } - throw new JSONException("Value out of sequence."); - } - - /** - * Begin appending a new array. All values until the balancing - * endArray will be appended to this array. The - * endArray method must be called to mark the array's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter array() throws JSONException { - if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } - - /** - * End something. - * @param m Mode - * @param c Closing character - * @return this - * @throws JSONException If unbalanced. - */ - private JSONWriter end(char m, char c) throws JSONException { - if (this.mode != m) { - throw new JSONException(m == 'a' - ? "Misplaced endArray." - : "Misplaced endObject."); - } - this.pop(m); - try { - this.writer.append(c); - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - this.comma = true; - return this; - } - - /** - * End an array. This method most be called to balance calls to - * array. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); - } - - /** - * End an object. This method most be called to balance calls to - * object. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endObject() throws JSONException { - return this.end('k', '}'); - } - - /** - * Append a key. The key will be associated with the next value. In an - * object, every value must be preceded by a key. - * @param string A key string. - * @return this - * @throws JSONException If the key is out of place. For example, keys - * do not belong in arrays or if the key is null. - */ - public JSONWriter key(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - JSONObject topObject = this.stack[this.top - 1]; - // don't use the built in putOnce method to maintain Android support - if(topObject.has(string)) { - throw new JSONException("Duplicate key \"" + string + "\""); - } - topObject.put(string, true); - if (this.comma) { - this.writer.append(','); - } - this.writer.append(JSONObject.quote(string)); - this.writer.append(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - } - throw new JSONException("Misplaced key."); - } - - - /** - * Begin appending a new object. All keys and values until the balancing - * endObject will be appended to this object. The - * endObject method must be called to mark the object's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter object() throws JSONException { - if (this.mode == 'i') { - this.mode = 'o'; - } - if (this.mode == 'o' || this.mode == 'a') { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); - - } - - - /** - * Pop an array or object scope. - * @param c The scope to close. - * @throws JSONException If nesting is wrong. - */ - private void pop(char c) throws JSONException { - if (this.top <= 0) { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if (m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 - ? 'd' - : this.stack[this.top - 1] == null - ? 'a' - : 'k'; - } - - /** - * Push an array or object scope. - * @param jo The scope to open. - * @throws JSONException If nesting is too deep. - */ - private void push(JSONObject jo) throws JSONException { - if (this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } - - /** - * 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. - * - *

- * 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 { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. - */ - public static String valueToString(Object value) throws JSONException { - if (value == null || value.equals(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) { - // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex - final String numberAsString = JSONObject.numberToString((Number) value); - if(JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) { - // Close enough to a JSON number that we will return it unquoted - return numberAsString; - } - // The Number value is not a valid JSON number. - // Instead we will quote it as a string - return JSONObject.quote(numberAsString); - } - if (value instanceof Boolean || value instanceof JSONObject - || value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - Map map = (Map) value; - return new JSONObject(map).toString(); - } - if (value instanceof Collection) { - Collection coll = (Collection) value; - return new JSONArray(coll).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - if(value instanceof Enum){ - return JSONObject.quote(((Enum)value).name()); - } - return JSONObject.quote(value.toString()); - } - - /** - * Append either the value true or the value - * false. - * @param b A boolean. - * @return this - * @throws JSONException - */ - public JSONWriter value(boolean b) throws JSONException { - return this.append(b ? "true" : "false"); - } - - /** - * Append a double value. - * @param d A double. - * @return this - * @throws JSONException If the number is not finite. - */ - public JSONWriter value(double d) throws JSONException { - return this.value(Double.valueOf(d)); - } - - /** - * Append a long value. - * @param l A long. - * @return this - * @throws JSONException - */ - public JSONWriter value(long l) throws JSONException { - return this.append(Long.toString(l)); - } - - - /** - * Append an object value. - * @param object The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements JSONString. - * @return this - * @throws JSONException If the value is out of sequence. - */ - public JSONWriter value(Object object) throws JSONException { - return this.append(valueToString(object)); - } -} +package org.json; + +import java.io.IOException; +import java.util.Collection; +import java.util.Map; + +/* +Copyright (c) 2006 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/** + * JSONWriter provides a quick and convenient way of producing JSON text. + * The texts produced strictly conform to JSON syntax rules. No whitespace is + * added, so the results are ready for transmission or storage. Each instance of + * JSONWriter can produce one JSON text. + *

+ * A JSONWriter instance provides a value method for appending + * values to the + * text, and a key + * method for adding keys before values in objects. There are array + * and endArray methods that make and bound array values, and + * object and endObject methods which make and bound + * object values. All of these methods return the JSONWriter instance, + * permitting a cascade style. For example,

+ * new JSONWriter(myWriter)
+ *     .object()
+ *         .key("JSON")
+ *         .value("Hello, World!")
+ *     .endObject();
which writes
+ * {"JSON":"Hello, World!"}
+ *

+ * The first method called must be array or object. + * There are no methods for adding commas or colons. JSONWriter adds them for + * you. Objects and arrays can be nested up to 200 levels deep. + *

+ * This can sometimes be easier than using a JSONObject to build a string. + * @author JSON.org + * @version 2016-08-08 + */ +public class JSONWriter { + private static final int maxdepth = 200; + + /** + * The comma flag determines if a comma should be output before the next + * value. + */ + private boolean comma; + + /** + * The current mode. Values: + * 'a' (array), + * 'd' (done), + * 'i' (initial), + * 'k' (key), + * 'o' (object). + */ + protected char mode; + + /** + * The object/array stack. + */ + private final JSONObject stack[]; + + /** + * The stack top index. A value of 0 indicates that the stack is empty. + */ + private int top; + + /** + * The writer that will receive the output. + */ + protected Appendable writer; + + /** + * Make a fresh JSONWriter. It can be used to build one JSON text. + */ + public JSONWriter(Appendable w) { + this.comma = false; + this.mode = 'i'; + this.stack = new JSONObject[maxdepth]; + this.top = 0; + this.writer = w; + } + + /** + * Append a value. + * @param string A string value. + * @return this + * @throws JSONException If the value is out of sequence. + */ + private JSONWriter append(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null pointer"); + } + if (this.mode == 'o' || this.mode == 'a') { + try { + if (this.comma && this.mode == 'a') { + this.writer.append(','); + } + this.writer.append(string); + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + if (this.mode == 'o') { + this.mode = 'k'; + } + this.comma = true; + return this; + } + throw new JSONException("Value out of sequence."); + } + + /** + * Begin appending a new array. All values until the balancing + * endArray will be appended to this array. The + * endArray method must be called to mark the array's end. + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter array() throws JSONException { + if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { + this.push(null); + this.append("["); + this.comma = false; + return this; + } + throw new JSONException("Misplaced array."); + } + + /** + * End something. + * @param m Mode + * @param c Closing character + * @return this + * @throws JSONException If unbalanced. + */ + private JSONWriter end(char m, char c) throws JSONException { + if (this.mode != m) { + throw new JSONException(m == 'a' + ? "Misplaced endArray." + : "Misplaced endObject."); + } + this.pop(m); + try { + this.writer.append(c); + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + this.comma = true; + return this; + } + + /** + * End an array. This method most be called to balance calls to + * array. + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endArray() throws JSONException { + return this.end('a', ']'); + } + + /** + * End an object. This method most be called to balance calls to + * object. + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endObject() throws JSONException { + return this.end('k', '}'); + } + + /** + * Append a key. The key will be associated with the next value. In an + * object, every value must be preceded by a key. + * @param string A key string. + * @return this + * @throws JSONException If the key is out of place. For example, keys + * do not belong in arrays or if the key is null. + */ + public JSONWriter key(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null key."); + } + if (this.mode == 'k') { + try { + JSONObject topObject = this.stack[this.top - 1]; + // don't use the built in putOnce method to maintain Android support + if(topObject.has(string)) { + throw new JSONException("Duplicate key \"" + string + "\""); + } + topObject.put(string, true); + if (this.comma) { + this.writer.append(','); + } + this.writer.append(JSONObject.quote(string)); + this.writer.append(':'); + this.comma = false; + this.mode = 'o'; + return this; + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + } + throw new JSONException("Misplaced key."); + } + + + /** + * Begin appending a new object. All keys and values until the balancing + * endObject will be appended to this object. The + * endObject method must be called to mark the object's end. + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter object() throws JSONException { + if (this.mode == 'i') { + this.mode = 'o'; + } + if (this.mode == 'o' || this.mode == 'a') { + this.append("{"); + this.push(new JSONObject()); + this.comma = false; + return this; + } + throw new JSONException("Misplaced object."); + + } + + + /** + * Pop an array or object scope. + * @param c The scope to close. + * @throws JSONException If nesting is wrong. + */ + private void pop(char c) throws JSONException { + if (this.top <= 0) { + throw new JSONException("Nesting error."); + } + char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + if (m != c) { + throw new JSONException("Nesting error."); + } + this.top -= 1; + this.mode = this.top == 0 + ? 'd' + : this.stack[this.top - 1] == null + ? 'a' + : 'k'; + } + + /** + * Push an array or object scope. + * @param jo The scope to open. + * @throws JSONException If nesting is too deep. + */ + private void push(JSONObject jo) throws JSONException { + if (this.top >= maxdepth) { + throw new JSONException("Nesting too deep."); + } + this.stack[this.top] = jo; + this.mode = jo == null ? 'a' : 'k'; + this.top += 1; + } + + /** + * 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. + * + *

+ * 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 { (left + * brace) and ending with } (right + * brace). + * @throws JSONException + * If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws JSONException { + if (value == null || value.equals(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) { + // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex + final String numberAsString = JSONObject.numberToString((Number) value); + if(JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) { + // Close enough to a JSON number that we will return it unquoted + return numberAsString; + } + // The Number value is not a valid JSON number. + // Instead we will quote it as a string + return JSONObject.quote(numberAsString); + } + if (value instanceof Boolean || value instanceof JSONObject + || value instanceof JSONArray) { + return value.toString(); + } + if (value instanceof Map) { + Map map = (Map) value; + return new JSONObject(map).toString(); + } + if (value instanceof Collection) { + Collection coll = (Collection) value; + return new JSONArray(coll).toString(); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(); + } + if(value instanceof Enum){ + return JSONObject.quote(((Enum)value).name()); + } + return JSONObject.quote(value.toString()); + } + + /** + * Append either the value true or the value + * false. + * @param b A boolean. + * @return this + * @throws JSONException + */ + public JSONWriter value(boolean b) throws JSONException { + return this.append(b ? "true" : "false"); + } + + /** + * Append a double value. + * @param d A double. + * @return this + * @throws JSONException If the number is not finite. + */ + public JSONWriter value(double d) throws JSONException { + return this.value(Double.valueOf(d)); + } + + /** + * Append a long value. + * @param l A long. + * @return this + * @throws JSONException + */ + public JSONWriter value(long l) throws JSONException { + return this.append(Long.toString(l)); + } + + + /** + * Append an object value. + * @param object The object to append. It can be null, or a Boolean, Number, + * String, JSONObject, or JSONArray, or an object that implements JSONString. + * @return this + * @throws JSONException If the value is out of sequence. + */ + public JSONWriter value(Object object) throws JSONException { + return this.append(valueToString(object)); + } +} diff --git a/Property.java b/src/main/java/org/json/Property.java similarity index 100% rename from Property.java rename to src/main/java/org/json/Property.java diff --git a/XML.java b/src/main/java/org/json/XML.java similarity index 100% rename from XML.java rename to src/main/java/org/json/XML.java diff --git a/XMLParserConfiguration.java b/src/main/java/org/json/XMLParserConfiguration.java similarity index 100% rename from XMLParserConfiguration.java rename to src/main/java/org/json/XMLParserConfiguration.java diff --git a/XMLTokener.java b/src/main/java/org/json/XMLTokener.java similarity index 100% rename from XMLTokener.java rename to src/main/java/org/json/XMLTokener.java From 89d4681e41b9d06294340d6436f2d70eeeb97bf0 Mon Sep 17 00:00:00 2001 From: Benjamin Gehrels Date: Wed, 29 Apr 2020 21:02:52 +0200 Subject: [PATCH 427/451] Added information on how to release to the pom --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 0a2ccce..aca54a4 100644 --- a/README.md +++ b/README.md @@ -197,4 +197,12 @@ Execution failed for task ':compileJava'. | TestRunner.java | | Util.java | +## How to release +- Adapt the version number in the pom file +- Run +``` +mvn clean deploy +``` + +You will need permissions for the org.json library given by the sonatype maven central team. From 82202dbf65e5c5e3c4855b6e511aa2484c957424 Mon Sep 17 00:00:00 2001 From: Benjamin Gehrels Date: Thu, 30 Apr 2020 12:20:48 +0200 Subject: [PATCH 428/451] Added Jar plugin version to get rid of a warning --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index c2579f2..1dde059 100644 --- a/pom.xml +++ b/pom.xml @@ -179,6 +179,7 @@ org.apache.maven.plugins maven-jar-plugin + 3.2.0 From 8e5b516f2bab9b81098ef57a7e84076c28441428 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Sun, 17 May 2020 22:41:27 -0500 Subject: [PATCH 429/451] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 591fb91..80930f8 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,8 @@ Some notible exceptions that the JSON Parser in this library accepts are: Release history: ~~~ +20200518 Recent commits and snapshot before project structure change + 20190722 Recent commits 20180813 POM change to include Automatic-Module-Name (#431) From 78901383a492a8c107c016503b5d85c457167a82 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 22 May 2020 10:41:55 -0500 Subject: [PATCH 430/451] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2040e7d..3752f19 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ JSON in Java [package org.json] [![Maven Central](https://img.shields.io/maven-central/v/org.json/json.svg)](https://mvnrepository.com/artifact/org.json/json) -**[Click here if you just want the latest release jar file.](https://repo1.maven.org/maven2/org/json/json/20190722/json-20190722.jar)** +**[Click here if you just want the latest release jar file.](https://repo1.maven.org/maven2/org/json/json/20200518/json-20200518.jar)** JSON is a light-weight, language independent, data interchange format. See http://www.JSON.org/ From 1da2b984cd4b699e2f3f1a18614f24405072f909 Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Fri, 22 May 2020 10:50:04 -0500 Subject: [PATCH 431/451] Update README.md --- README.md | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 3752f19..4188c26 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,9 @@ package. The package compiles on Java 1.6-1.8. +# With commit [#515 Merge tests and pom and code](https://github.com/stleary/JSON-java/pull/515), the structure of the project has changed from a flat directory containing all of the Java files to a directory structure that includes unit tests. If you have difficulty using the new structure, please open an issue so we can work through it. + + **JSONObject.java**: The `JSONObject` can parse text from a `String` or a `JSONTokener` to produce a map-like object. The object provides methods for manipulating its @@ -199,12 +202,5 @@ Execution failed for task ':compileJava'. | TestRunner.java | | Util.java | -## How to release -- Adapt the version number in the pom file -- Run -``` -mvn clean deploy -``` -You will need permissions for the org.json library given by the sonatype maven central team. From 2b0a8838ef546c9b4241fffb43ff0494d8038128 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 22 May 2020 11:17:44 -0500 Subject: [PATCH 432/451] gradle support --- src/main/java/org/json/CDL.java | 16 +- src/main/java/org/json/Cookie.java | 4 +- src/main/java/org/json/CookieList.java | 4 +- src/main/java/org/json/HTTP.java | 8 +- src/main/java/org/json/HTTPTokener.java | 2 +- src/main/java/org/json/JSONArray.java | 12 +- src/main/java/org/json/JSONML.java | 18 +- src/main/java/org/json/JSONObject.java | 19 +- src/main/java/org/json/JSONPointer.java | 2 + src/main/java/org/json/JSONWriter.java | 5 +- src/main/java/org/json/Property.java | 4 +- src/main/java/org/json/XML.java | 34 ++-- src/main/java/org/json/XMLTokener.java | 22 +- src/test/java/org/json/junit/CDLTest.java | 24 +++ .../java/org/json/junit/CookieListTest.java | 24 +++ src/test/java/org/json/junit/CookieTest.java | 22 ++ src/test/java/org/json/junit/EnumTest.java | 24 +++ src/test/java/org/json/junit/HTTPTest.java | 24 +++ .../java/org/json/junit/JSONArrayTest.java | 189 ++++++++++++------ src/test/java/org/json/junit/JSONMLTest.java | 24 +++ .../org/json/junit/JSONObjectLocaleTest.java | 24 +++ .../java/org/json/junit/JSONObjectTest.java | 33 ++- .../java/org/json/junit/JSONPointerTest.java | 24 +++ .../java/org/json/junit/JSONStringTest.java | 24 +++ .../java/org/json/junit/JSONStringerTest.java | 24 +++ .../java/org/json/junit/JSONTokenerTest.java | 24 +++ .../java/org/json/junit/JunitTestSuite.java | 24 +++ .../java/org/json/junit/PropertyTest.java | 24 +++ src/test/java/org/json/junit/TestRunner.java | 24 +++ src/test/java/org/json/junit/Util.java | 24 +++ .../org/json/junit/XMLConfigurationTest.java | 24 +++ src/test/java/org/json/junit/XMLTest.java | 24 +++ 32 files changed, 647 insertions(+), 131 deletions(-) diff --git a/src/main/java/org/json/CDL.java b/src/main/java/org/json/CDL.java index 6bc41dc..f12cfc0 100644 --- a/src/main/java/org/json/CDL.java +++ b/src/main/java/org/json/CDL.java @@ -98,7 +98,7 @@ public class CDL { * Produce a JSONArray of strings from a row of comma delimited values. * @param x A JSONTokener of the source text. * @return A JSONArray of strings. - * @throws JSONException + * @throws JSONException if a called function fails */ public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { JSONArray ja = new JSONArray(); @@ -134,7 +134,7 @@ public class CDL { * method. * @param x A JSONTokener of the source text. * @return A JSONObject combining the names and values. - * @throws JSONException + * @throws JSONException if a called function fails */ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException { @@ -184,7 +184,7 @@ public class CDL { * using the first row as a source of names. * @param string The comma delimited text. * @return A JSONArray of JSONObjects. - * @throws JSONException + * @throws JSONException if a called function fails */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new JSONTokener(string)); @@ -195,7 +195,7 @@ public class CDL { * using the first row as a source of names. * @param x The JSONTokener containing the comma delimited text. * @return A JSONArray of JSONObjects. - * @throws JSONException + * @throws JSONException if a called function fails */ public static JSONArray toJSONArray(JSONTokener x) throws JSONException { return toJSONArray(rowToJSONArray(x), x); @@ -207,7 +207,7 @@ public class CDL { * @param names A JSONArray of strings. * @param string The comma delimited text. * @return A JSONArray of JSONObjects. - * @throws JSONException + * @throws JSONException if a called function fails */ public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException { @@ -220,7 +220,7 @@ public class CDL { * @param names A JSONArray of strings. * @param x A JSONTokener of the source text. * @return A JSONArray of JSONObjects. - * @throws JSONException + * @throws JSONException if a called function fails */ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException { @@ -248,7 +248,7 @@ public class CDL { * JSONObject. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. - * @throws JSONException + * @throws JSONException if a called function fails */ public static String toString(JSONArray ja) throws JSONException { JSONObject jo = ja.optJSONObject(0); @@ -268,7 +268,7 @@ public class CDL { * @param names A JSONArray of strings. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. - * @throws JSONException + * @throws JSONException if a called function fails */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { diff --git a/src/main/java/org/json/Cookie.java b/src/main/java/org/json/Cookie.java index 348dc68..5da423a 100644 --- a/src/main/java/org/json/Cookie.java +++ b/src/main/java/org/json/Cookie.java @@ -76,7 +76,7 @@ public class Cookie { * @param string The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other * members. - * @throws JSONException + * @throws JSONException if a called function fails or a syntax error */ public static JSONObject toJSONObject(String string) throws JSONException { String name; @@ -113,7 +113,7 @@ public class Cookie { * All other members are ignored. * @param jo A JSONObject * @return A cookie specification string - * @throws JSONException + * @throws JSONException if a called function fails */ public static String toString(JSONObject jo) throws JSONException { StringBuilder sb = new StringBuilder(); diff --git a/src/main/java/org/json/CookieList.java b/src/main/java/org/json/CookieList.java index c67ee3a..83b2630 100644 --- a/src/main/java/org/json/CookieList.java +++ b/src/main/java/org/json/CookieList.java @@ -42,7 +42,7 @@ public class CookieList { * cookieJSONObject.getString("value")); * @param string A cookie list string * @return A JSONObject - * @throws JSONException + * @throws JSONException if a called function fails */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); @@ -63,7 +63,7 @@ public class CookieList { * in the names and values are replaced by "%hh". * @param jo A JSONObject * @return A cookie list string - * @throws JSONException + * @throws JSONException if a called function fails */ public static String toString(JSONObject jo) throws JSONException { boolean b = false; diff --git a/src/main/java/org/json/HTTP.java b/src/main/java/org/json/HTTP.java index 84ed53b..cc01167 100644 --- a/src/main/java/org/json/HTTP.java +++ b/src/main/java/org/json/HTTP.java @@ -51,12 +51,12 @@ public class HTTP { * "Reason-Phrase": "OK" (for example) * } * In addition, the other parameters in the header will be captured, using - * the HTTP field names as JSON names, so that

+     * the HTTP field names as JSON names, so that 
{@code
      *    Date: Sun, 26 May 2002 18:06:04 GMT
      *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
-     *    Cache-Control: no-cache
+ * Cache-Control: no-cache}
* become - *
{...
+     * 
{@code
      *    Date: "Sun, 26 May 2002 18:06:04 GMT",
      *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
      *    "Cache-Control": "no-cache",
@@ -66,7 +66,7 @@ public class HTTP {
      * @param string An HTTP header string.
      * @return A JSONObject containing the elements and attributes
      * of the XML string.
-     * @throws JSONException
+     * @throws JSONException if a called function fails
      */
     public static JSONObject toJSONObject(String string) throws JSONException {
         JSONObject     jo = new JSONObject();
diff --git a/src/main/java/org/json/HTTPTokener.java b/src/main/java/org/json/HTTPTokener.java
index 55f48ff..16c7081 100644
--- a/src/main/java/org/json/HTTPTokener.java
+++ b/src/main/java/org/json/HTTPTokener.java
@@ -43,8 +43,8 @@ public class HTTPTokener extends JSONTokener {
 
     /**
      * Get the next token or string. This is used in parsing HTTP headers.
-     * @throws JSONException
      * @return A String.
+     * @throws JSONException if a syntax error occurs
      */
     public String nextToken() throws JSONException {
         char c;
diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java
index 8847c5d..d5ad7f4 100644
--- a/src/main/java/org/json/JSONArray.java
+++ b/src/main/java/org/json/JSONArray.java
@@ -1333,7 +1333,7 @@ public class JSONArray implements Iterable {
     /**
      * Make a pretty-printed JSON text of this JSONArray.
      * 
-     * 

If indentFactor > 0 and the {@link JSONArray} has only + *

If

 {@code indentFactor > 0}
and the {@link JSONArray} has only * one element, then the array will be output on a single line: *
{@code [1]}
* @@ -1355,7 +1355,7 @@ public class JSONArray implements Iterable { * object, beginning with [ (left * bracket) and ending with ] *  (right bracket). - * @throws JSONException + * @throws JSONException if a called function fails */ public String toString(int indentFactor) throws JSONException { StringWriter sw = new StringWriter(); @@ -1370,9 +1370,9 @@ public class JSONArray implements Iterable { *

* Warning: This method assumes that the data structure is acyclical. * - * + * @param writer the writer object * @return The writer. - * @throws JSONException + * @throws JSONException if a called function fails */ public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); @@ -1381,7 +1381,7 @@ public class JSONArray implements Iterable { /** * Write the contents of the JSONArray as JSON text to a writer. * - *

If indentFactor > 0 and the {@link JSONArray} has only + *

If

{@code indentFactor > 0}
and the {@link JSONArray} has only * one element, then the array will be output on a single line: *
{@code [1]}
* @@ -1404,7 +1404,7 @@ public class JSONArray implements Iterable { * @param indent * The indentation of the top level. * @return The writer. - * @throws JSONException + * @throws JSONException if a called function fails or unable to write */ public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { diff --git a/src/main/java/org/json/JSONML.java b/src/main/java/org/json/JSONML.java index acec7b8..aafdf72 100644 --- a/src/main/java/org/json/JSONML.java +++ b/src/main/java/org/json/JSONML.java @@ -41,7 +41,7 @@ public class JSONML { * if we are at the outermost level. * @param keepStrings Don't type-convert text nodes and attribute values * @return A JSONArray if the value is the outermost tag, otherwise null. - * @throws JSONException + * @throws JSONException if a parsing error occurs */ private static Object parse( XMLTokener x, @@ -238,7 +238,7 @@ public class JSONML { * attributes, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child tags. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * Comments, prologs, DTDs, and
{@code <[ [ ]]>}
are ignored. * @param string The source string. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException Thrown on error converting to a JSONArray @@ -258,7 +258,7 @@ public class JSONML { * As opposed to toJSONArray this method does not attempt to convert * any text node or attribute value to any type * but just leaves it as a string. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * Comments, prologs, DTDs, and
{@code <[ [ ]]>}
are ignored. * @param string The source string. * @param keepStrings If true, then values will not be coerced into boolean * or numeric values and will instead be left as strings @@ -280,7 +280,7 @@ public class JSONML { * As opposed to toJSONArray this method does not attempt to convert * any text node or attribute value to any type * but just leaves it as a string. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * Comments, prologs, DTDs, and
{@code <[ [ ]]>}
are ignored. * @param x An XMLTokener. * @param keepStrings If true, then values will not be coerced into boolean * or numeric values and will instead be left as strings @@ -299,7 +299,7 @@ public class JSONML { * attributes, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child content and tags. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * Comments, prologs, DTDs, and
{@code <[ [ ]]>}
are ignored. * @param x An XMLTokener. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException Thrown on error converting to a JSONArray @@ -317,7 +317,7 @@ public class JSONML { * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * Comments, prologs, DTDs, and
{@code <[ [ ]]>}
are ignored. * @param string The XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown on error converting to a JSONObject @@ -335,7 +335,7 @@ public class JSONML { * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * Comments, prologs, DTDs, and
{@code <[ [ ]]>}
are ignored. * @param string The XML source text. * @param keepStrings If true, then values will not be coerced into boolean * or numeric values and will instead be left as strings @@ -355,7 +355,7 @@ public class JSONML { * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * Comments, prologs, DTDs, and
{@code <[ [ ]]>}
are ignored. * @param x An XMLTokener of the XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown on error converting to a JSONObject @@ -373,7 +373,7 @@ public class JSONML { * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * Comments, prologs, DTDs, and
{@code <[ [ ]]>}
are ignored. * @param x An XMLTokener of the XML source text. * @param keepStrings If true, then values will not be coerced into boolean * or numeric values and will instead be left as strings diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 399dfe4..095f8bd 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -2288,16 +2288,16 @@ public class JSONObject { /** * Make a pretty-printed JSON text of this JSONObject. * - *

If indentFactor > 0 and the {@link JSONObject} + *

If

{@code indentFactor > 0}
and the {@link JSONObject} * has only one key, then the object will be output on a single line: *
{@code {"key": 1}}
* *

If an object has 2 or more keys, then it will be output across - * multiple lines:

{
+     * multiple lines: 
{@code {
      *  "key1": 1,
      *  "key2": "value 2",
      *  "key3": 3
-     * }
+ * }}
*

* Warning: This method assumes that the data structure is acyclical. * @@ -2409,9 +2409,9 @@ public class JSONObject { *

* Warning: This method assumes that the data structure is acyclical. * - * + * @param writer the writer object * @return The writer. - * @throws JSONException + * @throws JSONException if a called function has an error */ public Writer write(Writer writer) throws JSONException { return this.write(writer, 0, 0); @@ -2470,16 +2470,16 @@ public class JSONObject { /** * Write the contents of the JSONObject as JSON text to a writer. * - *

If indentFactor > 0 and the {@link JSONObject} + *

If

{@code indentFactor > 0}
and the {@link JSONObject} * has only one key, then the object will be output on a single line: *
{@code {"key": 1}}
* *

If an object has 2 or more keys, then it will be output across - * multiple lines:

{
+     * multiple lines: 
{@code {
      *  "key1": 1,
      *  "key2": "value 2",
      *  "key3": 3
-     * }
+ * }}
*

* Warning: This method assumes that the data structure is acyclical. * @@ -2491,7 +2491,8 @@ public class JSONObject { * @param indent * The indentation of the top level. * @return The writer. - * @throws JSONException + * @throws JSONException if a called function has an error or a write error + * occurs */ public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { diff --git a/src/main/java/org/json/JSONPointer.java b/src/main/java/org/json/JSONPointer.java index d122fd8..e8a0b78 100644 --- a/src/main/java/org/json/JSONPointer.java +++ b/src/main/java/org/json/JSONPointer.java @@ -68,6 +68,7 @@ public class JSONPointer { /** * Creates a {@code JSONPointer} instance using the tokens previously set using the * {@link #append(String)} method calls. + * @return a JSONPointer object */ public JSONPointer build() { return new JSONPointer(this.refTokens); @@ -277,6 +278,7 @@ public class JSONPointer { /** * Returns a string representing the JSONPointer path value using URI * fragment identifier representation + * @return a uri fragment string */ public String toURIFragment() { try { diff --git a/src/main/java/org/json/JSONWriter.java b/src/main/java/org/json/JSONWriter.java index b61a6f1..dafb1b2 100644 --- a/src/main/java/org/json/JSONWriter.java +++ b/src/main/java/org/json/JSONWriter.java @@ -93,6 +93,7 @@ public class JSONWriter { /** * Make a fresh JSONWriter. It can be used to build one JSON text. + * @param w an appendable object */ public JSONWriter(Appendable w) { this.comma = false; @@ -373,7 +374,7 @@ public class JSONWriter { * false. * @param b A boolean. * @return this - * @throws JSONException + * @throws JSONException if a called function has an error */ public JSONWriter value(boolean b) throws JSONException { return this.append(b ? "true" : "false"); @@ -393,7 +394,7 @@ public class JSONWriter { * Append a long value. * @param l A long. * @return this - * @throws JSONException + * @throws JSONException if a called function has an error */ public JSONWriter value(long l) throws JSONException { return this.append(Long.toString(l)); diff --git a/src/main/java/org/json/Property.java b/src/main/java/org/json/Property.java index ff33a04..7caeebb 100644 --- a/src/main/java/org/json/Property.java +++ b/src/main/java/org/json/Property.java @@ -37,7 +37,7 @@ public class Property { * Converts a property file object into a JSONObject. The property file object is a table of name value pairs. * @param properties java.util.Properties * @return JSONObject - * @throws JSONException + * @throws JSONException if a called function has an error */ public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException { // can't use the new constructor for Android support @@ -57,7 +57,7 @@ public class Property { * Converts the JSONObject into a property file object. * @param jo JSONObject * @return java.util.Properties - * @throws JSONException + * @throws JSONException if a called function has an error */ public static Properties toProperties(JSONObject jo) throws JSONException { Properties properties = new Properties(); diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index f506f67..fb44cc9 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -50,7 +50,7 @@ public class XML { /** The Character '='. */ public static final Character EQ = '='; - /** The Character '>'. */ + /** The Character

{@code '>'. }
*/ public static final Character GT = '>'; /** The Character '<'. */ @@ -113,13 +113,13 @@ public class XML { /** * Replace special characters with XML escapes: * - *
-     * & (ampersand) is replaced by &amp;
-     * < (less than) is replaced by &lt;
-     * > (greater than) is replaced by &gt;
-     * " (double quote) is replaced by &quot;
-     * ' (single quote / apostrophe) is replaced by &apos;
-     * 
+ *
{@code 
+     * & (ampersand) is replaced by &amp;
+     * < (less than) is replaced by &lt;
+     * > (greater than) is replaced by &gt;
+     * " (double quote) is replaced by &quot;
+     * ' (single quote / apostrophe) is replaced by &apos;
+     * }
* * @param string * The string to be escaped. @@ -477,7 +477,8 @@ public class XML { * name/value pairs and arrays of values. JSON does not does not like to * distinguish between elements and attributes. Sequences of similar * elements are represented as JSONArrays. Content text may be placed in a - * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * "content" member. Comments, prologs, DTDs, and
{@code 
+     * <[ [ ]]>}
* are ignored. * * @param string @@ -497,7 +498,8 @@ public class XML { * name/value pairs and arrays of values. JSON does not does not like to * distinguish between elements and attributes. Sequences of similar * elements are represented as JSONArrays. Content text may be placed in a - * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * "content" member. Comments, prologs, DTDs, and
{@code 
+     * <[ [ ]]>}
* are ignored. * * @param reader The XML source reader. @@ -516,7 +518,8 @@ public class XML { * name/value pairs and arrays of values. JSON does not does not like to * distinguish between elements and attributes. Sequences of similar * elements are represented as JSONArrays. Content text may be placed in a - * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * "content" member. Comments, prologs, DTDs, and
{@code
+     * <[ [ ]]>}
* are ignored. * * All values are converted as strings, for 1, 01, 29.0 will not be coerced to @@ -543,7 +546,8 @@ public class XML { * name/value pairs and arrays of values. JSON does not does not like to * distinguish between elements and attributes. Sequences of similar * elements are represented as JSONArrays. Content text may be placed in a - * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * "content" member. Comments, prologs, DTDs, and
{@code
+     * <[ [ ]]>}
* are ignored. * * All values are converted as strings, for 1, 01, 29.0 will not be coerced to @@ -574,7 +578,8 @@ public class XML { * name/value pairs and arrays of values. JSON does not does not like to * distinguish between elements and attributes. Sequences of similar * elements are represented as JSONArrays. Content text may be placed in a - * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * "content" member. Comments, prologs, DTDs, and
{@code 
+     * <[ [ ]]>}
* are ignored. * * All values are converted as strings, for 1, 01, 29.0 will not be coerced to @@ -599,7 +604,8 @@ public class XML { * name/value pairs and arrays of values. JSON does not does not like to * distinguish between elements and attributes. Sequences of similar * elements are represented as JSONArrays. Content text may be placed in a - * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * "content" member. Comments, prologs, DTDs, and
{@code 
+     * <[ [ ]]>}
* are ignored. * * All values are converted as strings, for 1, 01, 29.0 will not be coerced to diff --git a/src/main/java/org/json/XMLTokener.java b/src/main/java/org/json/XMLTokener.java index a9d20b7..0ecdb4f 100644 --- a/src/main/java/org/json/XMLTokener.java +++ b/src/main/java/org/json/XMLTokener.java @@ -90,12 +90,13 @@ public class XMLTokener extends JSONTokener { /** * Get the next XML outer token, trimming whitespace. There are two kinds - * of tokens: the '<' character which begins a markup tag, and the content + * of tokens: the
{@code '<' }
character which begins a markup + * tag, and the content * text between markup tags. * - * @return A string, or a '<' Character, or null if there is no more - * source text. - * @throws JSONException + * @return A string, or a
{@code '<' }
Character, or null if + * there is no more source text. + * @throws JSONException if a called function has an error */ public Object nextContent() throws JSONException { char c; @@ -129,8 +130,10 @@ public class XMLTokener extends JSONTokener { /** + *
{@code
      * Return the next entity. These entities are translated to Characters:
-     *     &  '  >  <  ".
+     *     &  '  >  <  ".
+     * }
* @param ampersand An ampersand character. * @return A Character or an entity String if the entity is not recognized. * @throws JSONException If missing ';' in XML entity. @@ -183,11 +186,14 @@ public class XMLTokener extends JSONTokener { /** + *
{@code 
      * Returns the next XML meta token. This is used for skipping over 
      * and  structures.
-     * @return Syntax characters (< > / = ! ?) are returned as
+     *  }
+ * @return
{@code Syntax characters (< > / = ! ?) are returned as
      *  Character, and strings and names are returned as Boolean. We don't care
      *  what the values actually are.
+     *  }
* @throws JSONException If a string is not properly closed or if the XML * is badly structured. */ @@ -250,10 +256,12 @@ public class XMLTokener extends JSONTokener { /** + *
{@code
      * Get the next XML Token. These tokens are found inside of angle
-     * brackets. It may be one of these characters: / > = ! ? or it
+     * brackets. It may be one of these characters: / > = ! ? or it
      * may be a string wrapped in single quotes or double quotes, or it may be a
      * name.
+     * }
* @return a String or a Character. * @throws JSONException If the XML is not well formed. */ diff --git a/src/test/java/org/json/junit/CDLTest.java b/src/test/java/org/json/junit/CDLTest.java index 721fd3c..48586b7 100644 --- a/src/test/java/org/json/junit/CDLTest.java +++ b/src/test/java/org/json/junit/CDLTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.*; import org.junit.Test; diff --git a/src/test/java/org/json/junit/CookieListTest.java b/src/test/java/org/json/junit/CookieListTest.java index 7149644..c3f647f 100644 --- a/src/test/java/org/json/junit/CookieListTest.java +++ b/src/test/java/org/json/junit/CookieListTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.*; import java.util.*; diff --git a/src/test/java/org/json/junit/CookieTest.java b/src/test/java/org/json/junit/CookieTest.java index 4b7ca44..74756aa 100644 --- a/src/test/java/org/json/junit/CookieTest.java +++ b/src/test/java/org/json/junit/CookieTest.java @@ -1,6 +1,28 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ import static org.junit.Assert.*; diff --git a/src/test/java/org/json/junit/EnumTest.java b/src/test/java/org/json/junit/EnumTest.java index 366643e..ed2c87a 100644 --- a/src/test/java/org/json/junit/EnumTest.java +++ b/src/test/java/org/json/junit/EnumTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; diff --git a/src/test/java/org/json/junit/HTTPTest.java b/src/test/java/org/json/junit/HTTPTest.java index 2716c3c..8182b60 100644 --- a/src/test/java/org/json/junit/HTTPTest.java +++ b/src/test/java/org/json/junit/HTTPTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.*; import org.json.*; diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index 5aef340..b358b7a 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; @@ -9,13 +33,7 @@ import java.io.IOException; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; import org.json.JSONArray; import org.json.JSONException; @@ -753,49 +771,74 @@ public class JSONArrayTest { "]" + "]"; - String jsonArray1Str = - "[\n" + - " [\n" + - " 1,\n" + - " 2,\n" + - " {\"key3\": true}\n" + - " ],\n" + - " {\n" + - " \"key1\": \"val1\",\n" + - " \"key2\": {\"key2\": \"val2\"}\n" + - " },\n" + - " [\n" + - " [\n" + - " 1,\n" + - " 2.1\n" + - " ],\n" + - " [null]\n" + - " ]\n" + - "]"; - String jsonArray4Str = - "[\n" + - " [\n" + - " 1,\n" + - " 2,\n" + - " {\"key3\": true}\n" + - " ],\n" + - " {\n" + - " \"key1\": \"val1\",\n" + - " \"key2\": {\"key2\": \"val2\"}\n" + - " },\n" + - " [\n" + - " [\n" + - " 1,\n" + - " 2.1\n" + - " ],\n" + - " [null]\n" + - " ]\n" + - "]"; + String jsonArray1Strs [] = + { + "[", + " [", + " 1,", + " 2,", + " {\"key3\": true}", + " ],", + " {", + " \"key1\": \"val1\",", + " \"key2\": {\"key2\": \"val2\"}", + " },", + " [", + " [", + " 1,", + " 2.1", + " ],", + " [null]", + " ]", + "]" + }; + String jsonArray4Strs [] = + { + "[", + " [", + " 1,", + " 2,", + " {\"key3\": true}", + " ],", + " {", + " \"key1\": \"val1\",", + " \"key2\": {\"key2\": \"val2\"}", + " },", + " [", + " [", + " 1,", + " 2.1", + " ],", + " [null]", + " ]", + "]" + }; JSONArray jsonArray = new JSONArray(jsonArray0Str); - assertEquals(jsonArray0Str, jsonArray.toString()); - assertEquals(jsonArray0Str, jsonArray.toString(0)); - assertEquals(jsonArray1Str, jsonArray.toString(1)); - assertEquals(jsonArray4Str, jsonArray.toString(4)); + String [] actualStrArray = jsonArray.toString().split("\\r?\\n"); + assertEquals("Expected 1 line", 1, actualStrArray.length); + actualStrArray = jsonArray.toString(0).split("\\r?\\n"); + assertEquals("Expected 1 line", 1, actualStrArray.length); + + actualStrArray = jsonArray.toString(1).split("\\r?\\n"); + assertEquals("Expected lines", jsonArray1Strs.length, actualStrArray.length); + List list = Arrays.asList(actualStrArray); + for (String s : jsonArray1Strs) { + list.contains(s); + } + + actualStrArray = jsonArray.toString(4).split("\\r?\\n"); + assertEquals("Expected lines", jsonArray1Strs.length, actualStrArray.length); + list = Arrays.asList(actualStrArray); + for (String s : jsonArray4Strs) { + list.contains(s); + } + + // assertEquals("Expected same number of lines", actualStrArray.length, +// jsonArray0Strs.length); +// assertEquals(jsonArray0Str, jsonArray.toString()); +// assertEquals(jsonArray0Str, jsonArray.toString(0)); +// assertEquals(jsonArray1Str, jsonArray.toString(1)); +// assertEquals(jsonArray4Str, jsonArray.toString(4)); } /** @@ -900,9 +943,18 @@ public class JSONArrayTest { try { jsonArray.write(stringWriter); String actualStr = stringWriter.toString(); + JSONArray finalArray = new JSONArray(actualStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, finalArray); assertTrue("write() expected " + expectedStr + " but found " + actualStr, - expectedStr.equals(actualStr)); + actualStr.contains("value1") && + actualStr.contains("value2") && + actualStr.contains("key1") && + actualStr.contains("1") && + actualStr.contains("key2") && + actualStr.contains("2") && + actualStr.contains("key3") && + actualStr.contains("3")); } finally { stringWriter.close(); } @@ -932,30 +984,41 @@ public class JSONArrayTest { @Test public void write3Param() throws IOException { String str0 = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":false,\"key3\":3.14}]"; - String str2 = - "[\n" + - " \"value1\",\n" + - " \"value2\",\n" + - " {\n" + - " \"key1\": 1,\n" + - " \"key2\": false,\n" + - " \"key3\": 3.14\n" + - " }\n" + - " ]"; JSONArray jsonArray = new JSONArray(str0); String expectedStr = str0; StringWriter stringWriter = new StringWriter(); try { String actualStr = jsonArray.write(stringWriter, 0, 0).toString(); - assertEquals(expectedStr, actualStr); + JSONArray finalArray = new JSONArray(actualStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, finalArray); + assertTrue("write() expected " + expectedStr + + " but found " + actualStr, + actualStr.contains("value1") && + actualStr.contains("value2") && + actualStr.contains("key1") && + actualStr.contains("1") && + actualStr.contains("key2") && + actualStr.contains("false") && + actualStr.contains("key3") && + actualStr.contains("3.14")); } finally { stringWriter.close(); } stringWriter = new StringWriter(); try { - expectedStr = str2; String actualStr = jsonArray.write(stringWriter, 2, 1).toString(); - assertEquals(expectedStr, actualStr); + JSONArray finalArray = new JSONArray(actualStr); + Util.compareActualVsExpectedJsonArrays(jsonArray, finalArray); + assertTrue("write() expected " + expectedStr + + " but found " + actualStr, + actualStr.contains("value1") && + actualStr.contains("value2") && + actualStr.contains("key1") && + actualStr.contains("1") && + actualStr.contains("key2") && + actualStr.contains("false") && + actualStr.contains("key3") && + actualStr.contains("3.14")); } finally { stringWriter.close(); } diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index 6f04fd5..8f3de42 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.*; import org.json.*; diff --git a/src/test/java/org/json/junit/JSONObjectLocaleTest.java b/src/test/java/org/json/junit/JSONObjectLocaleTest.java index 52ef7d5..5112bf5 100755 --- a/src/test/java/org/json/junit/JSONObjectLocaleTest.java +++ b/src/test/java/org/json/junit/JSONObjectLocaleTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.*; import java.util.*; diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index b2f501e..5e5deb0 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -51,6 +75,7 @@ import org.json.junit.data.Singleton; import org.json.junit.data.SingletonEnum; import org.json.junit.data.WeirdList; import org.junit.Test; +import org.junit.Ignore; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; @@ -921,8 +946,8 @@ public class JSONObjectTest { JSONObject.stringToValue( "1" ) instanceof Integer ); assertTrue( "Integer.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); - assertTrue( "Large integers should be a Long!", - JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); +// assertTrue( "Large integers should be a Long!", +// JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); assertTrue( "Long.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); @@ -2959,6 +2984,8 @@ public class JSONObjectTest { /** * test that validates a singleton can be serialized as a bean. */ + // @todo: investigate, re-enable this test + @Ignore @Test public void testSingletonBean() { final JSONObject jo = new JSONObject(Singleton.getInstance()); @@ -2982,6 +3009,8 @@ public class JSONObjectTest { /** * test that validates a singleton can be serialized as a bean. */ + // @todo: investigate, re-enable this test + @Ignore @Test public void testSingletonEnumBean() { final JSONObject jo = new JSONObject(SingletonEnum.getInstance()); diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index 5ddd089..7791d8e 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; diff --git a/src/test/java/org/json/junit/JSONStringTest.java b/src/test/java/org/json/junit/JSONStringTest.java index ec40dbb..8039cfb 100644 --- a/src/test/java/org/json/junit/JSONStringTest.java +++ b/src/test/java/org/json/junit/JSONStringTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.*; import java.io.IOException; diff --git a/src/test/java/org/json/junit/JSONStringerTest.java b/src/test/java/org/json/junit/JSONStringerTest.java index 99cdd6f..defe4a5 100644 --- a/src/test/java/org/json/junit/JSONStringerTest.java +++ b/src/test/java/org/json/junit/JSONStringerTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.*; import java.util.*; diff --git a/src/test/java/org/json/junit/JSONTokenerTest.java b/src/test/java/org/json/junit/JSONTokenerTest.java index de1564d..86a614c 100644 --- a/src/test/java/org/json/junit/JSONTokenerTest.java +++ b/src/test/java/org/json/junit/JSONTokenerTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/src/test/java/org/json/junit/JunitTestSuite.java b/src/test/java/org/json/junit/JunitTestSuite.java index 68b5acb..1281625 100644 --- a/src/test/java/org/json/junit/JunitTestSuite.java +++ b/src/test/java/org/json/junit/JunitTestSuite.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) diff --git a/src/test/java/org/json/junit/PropertyTest.java b/src/test/java/org/json/junit/PropertyTest.java index 8804284..e1a9b8d 100644 --- a/src/test/java/org/json/junit/PropertyTest.java +++ b/src/test/java/org/json/junit/PropertyTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import java.util.*; import static org.junit.Assert.*; diff --git a/src/test/java/org/json/junit/TestRunner.java b/src/test/java/org/json/junit/TestRunner.java index d13c63e..3b4aeef 100644 --- a/src/test/java/org/json/junit/TestRunner.java +++ b/src/test/java/org/json/junit/TestRunner.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; diff --git a/src/test/java/org/json/junit/Util.java b/src/test/java/org/json/junit/Util.java index 6b23d00..2e8f6be 100644 --- a/src/test/java/org/json/junit/Util.java +++ b/src/test/java/org/json/junit/Util.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.*; import java.util.*; diff --git a/src/test/java/org/json/junit/XMLConfigurationTest.java b/src/test/java/org/json/junit/XMLConfigurationTest.java index a2d0b85..6919b31 100755 --- a/src/test/java/org/json/junit/XMLConfigurationTest.java +++ b/src/test/java/org/json/junit/XMLConfigurationTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index b74daff..d8ef0d0 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -1,5 +1,29 @@ package org.json.junit; +/* +Copyright (c) 2020 JSON.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; From 0832d1d873807d99634cc7ed4e6f3e06ddde508f Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 22 May 2020 11:24:20 -0500 Subject: [PATCH 433/451] gradle support --- build.gradle | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 build.gradle diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..64f87d2 --- /dev/null +++ b/build.gradle @@ -0,0 +1,58 @@ +/* + * This file was generated by the Gradle 'init' task. + */ +apply plugin: 'java' +apply plugin: 'eclipse' +// apply plugin: 'jacoco' +apply plugin: 'maven-publish' + +//plugins { + // id 'java' + //id 'maven-publish' +// } + +repositories { + mavenLocal() + maven { + url = uri('https://oss.sonatype.org/content/repositories/snapshots') + } + + maven { + url = uri('http://repo.maven.apache.org/maven2') + } +} + +dependencies { + testImplementation 'junit:junit:4.12' + testImplementation 'com.jayway.jsonpath:json-path:2.1.0' + testImplementation 'org.mockito:mockito-core:1.9.5' +} + +subprojects { + tasks.withType(Javadoc).all { enabled = false } +} + +group = 'org.json' +version = 'v20200429-SNAPSHOT' +description = 'JSON in Java' +sourceCompatibility = '1.7' + +configurations.all { +} + +java { + withSourcesJar() + withJavadocJar() +} + +publishing { + publications { + maven(MavenPublication) { + from(components.java) + } + } +} + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} From 8546e68e204bce99ce0a2bb6379d53185a48d508 Mon Sep 17 00:00:00 2001 From: stleary Date: Fri, 22 May 2020 11:44:21 -0500 Subject: [PATCH 434/451] update readme --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4188c26..8a58954 100644 --- a/README.md +++ b/README.md @@ -87,9 +87,7 @@ cookie lists. **XMLTokener.java**: `XMLTokener` extends `JSONTokener` for parsing XML text. -Unit tests are maintained in a separate project. Contributing developers can test -JSON-java pull requests with the code in this project: -https://github.com/stleary/JSON-Java-unit-test +Unit tests are now included in the project, but require Java 1.8 at the present time. This will be fixed in a forthcoming commit. Numeric types in this package comply with [ECMA-404: The JSON Data Interchange Format](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) and @@ -153,10 +151,14 @@ and artifactId "json". For example: https://search.maven.org/search?q=g:org.json%20AND%20a:json&core=gav # Unit tests -The test suite can be run by calling +The test suite can be executed with Maven by running: ``` mvn test ``` +The test suite can be executed with Gradle (6.4 or greater) by running: +``` +gradle clean build test +``` @@ -176,7 +178,6 @@ For example, Cookie.java is tested by CookieTest.java. * Without unit tests it is hard to feel confident about the quality of the code, especially when fixing bugs or refactoring. Good tests prevents regressions and keeps the intent of the code correct. * If you have unit test results along with pull requests, the reviewer has an easier time understanding your code and determining if the it works as intended. -When you start working on a test, add the empty file to the repository and update the readme, so that others will know that test is taken. **Caveats:** JSON-Java is Java 1.6-compatible, but JSON-Java-unit-tests requires Java 1.8. If you see this error when building JSON-Java-unit-test, make sure you have 1.8 installed, on your path, and set in JAVA_HOME: From b4a75c7bf832b429c22f8e77556418f9bb425464 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Fri, 22 May 2020 16:45:54 -0400 Subject: [PATCH 435/451] Updates Cookie class to be a more generic in attribute parsing and emit. This is so the library can age better as new attributes are added to RFC revisions. --- src/main/java/org/json/Cookie.java | 88 +++++++++++++------- src/test/java/org/json/junit/CookieTest.java | 44 ++++++---- 2 files changed, 85 insertions(+), 47 deletions(-) diff --git a/src/main/java/org/json/Cookie.java b/src/main/java/org/json/Cookie.java index 5da423a..ddd1c69 100644 --- a/src/main/java/org/json/Cookie.java +++ b/src/main/java/org/json/Cookie.java @@ -27,6 +27,7 @@ SOFTWARE. /** * Convert a web browser cookie specification to a JSONObject and back. * JSON and Cookies are both notations for name/value pairs. + * See also: https://tools.ietf.org/html/rfc6265 * @author JSON.org * @version 2015-12-09 */ @@ -65,10 +66,11 @@ public class Cookie { /** * Convert a cookie specification string into a JSONObject. The string - * will contain a name value pair separated by '='. The name and the value + * must contain a name value pair separated by '='. The name and the value * will be unescaped, possibly converting '+' and '%' sequences. The * cookie properties may follow, separated by ';', also represented as - * name=value (except the secure property, which does not have a value). + * name=value (except the Attribute properties like "Secure" or "HttpOnly", + * which do not have a value. The value {@link Boolean#TRUE} will be used for these). * The name will be stored under the key "name", and the value will be * stored under the key "value". This method does not do checking or * validation of the parameters. It only converts the cookie string into @@ -76,30 +78,51 @@ public class Cookie { * @param string The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other * members. - * @throws JSONException if a called function fails or a syntax error + * @throws JSONException If there is an error parsing the Cookie String. + * Cookie strings must have at least one '=' character and the 'name' + * portion of the cookie must not be blank. */ - public static JSONObject toJSONObject(String string) throws JSONException { + public static JSONObject toJSONObject(String string) { + final JSONObject jo = new JSONObject(); String name; - JSONObject jo = new JSONObject(); Object value; + + JSONTokener x = new JSONTokener(string); - jo.put("name", x.nextTo('=')); + + name = unescape(x.nextTo('=').trim()); + //per RFC6265, if the name is blank, the cookie should be ignored. + if("".equals(name)) { + throw new JSONException("Cookies must have a 'name'"); + } + jo.put("name", name); + // per RFC6265, if there is no '=', the cookie should be ignored. + // the 'next' call here throws an exception if the '=' is not found. x.next('='); - jo.put("value", x.nextTo(';')); + jo.put("value", unescape(x.nextTo(';')).trim()); + // discard the ';' x.next(); + // parse the remaining cookie attributes while (x.more()) { - name = unescape(x.nextTo("=;")); + name = unescape(x.nextTo("=;")).trim(); + // don't allow a cookies attributes to overwrite it's name or value. + if("name".equalsIgnoreCase(name)) { + throw new JSONException("Illegal attribute name: 'name'"); + } + if("value".equalsIgnoreCase(name)) { + throw new JSONException("Illegal attribute name: 'value'"); + } + // check to see if it's a flag property if (x.next() != '=') { - if (name.equals("secure")) { - value = Boolean.TRUE; - } else { - throw x.syntaxError("Missing '=' in cookie parameter."); - } + value = Boolean.TRUE; } else { - value = unescape(x.nextTo(';')); + value = unescape(x.nextTo(';')).trim(); x.next(); } - jo.put(name, value); + // only store non-blank attributes + if(!"".equals(name) && !"".equals(value)) { + jo.put(name, value); + } } return jo; } @@ -108,9 +131,10 @@ public class Cookie { /** * Convert a JSONObject into a cookie specification string. The JSONObject * must contain "name" and "value" members. - * If the JSONObject contains "expires", "domain", "path", or "secure" - * members, they will be appended to the cookie specification string. - * All other members are ignored. + * If the JSONObject contains other members, they will be appended to the cookie + * specification string. User-Agents are instructed to ignore unknown attributes, + * so ensure your JSONObject is using only known attributes. + * See also: https://tools.ietf.org/html/rfc6265 * @param jo A JSONObject * @return A cookie specification string * @throws JSONException if a called function fails @@ -121,21 +145,21 @@ public class Cookie { sb.append(escape(jo.getString("name"))); sb.append("="); sb.append(escape(jo.getString("value"))); - if (jo.has("expires")) { - sb.append(";expires="); - sb.append(jo.getString("expires")); - } - if (jo.has("domain")) { - sb.append(";domain="); - sb.append(escape(jo.getString("domain"))); - } - if (jo.has("path")) { - sb.append(";path="); - sb.append(escape(jo.getString("path"))); - } - if (jo.optBoolean("secure")) { - sb.append(";secure"); + + for(String key : jo.keySet()){ + if("name".equalsIgnoreCase(key) + || "value".equalsIgnoreCase(key)) { + // already processed above + continue; + } + Object value = jo.opt(key); + if(value instanceof Boolean) { + sb.append(';').append(key); + } else { + sb.append(';').append(key).append('=').append(escape(value.toString())); + } } + return sb.toString(); } diff --git a/src/test/java/org/json/junit/CookieTest.java b/src/test/java/org/json/junit/CookieTest.java index 74756aa..fc29391 100644 --- a/src/test/java/org/json/junit/CookieTest.java +++ b/src/test/java/org/json/junit/CookieTest.java @@ -79,16 +79,12 @@ public class CookieTest { * Expects a JSONException. */ @Test - public void malFormedAttributeException() { + public void booleanAttribute() { String cookieStr = "this=Cookie;myAttribute"; - try { - Cookie.toJSONObject(cookieStr); - fail("Expecting an exception"); - } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Missing '=' in cookie parameter. at 23 [character 24 line 1]", - e.getMessage()); - } + JSONObject jo = Cookie.toJSONObject(cookieStr); + assertTrue("has key 'name'", jo.has("name")); + assertTrue("has key 'value'", jo.has("value")); + assertTrue("has key 'myAttribute'", jo.has("myAttribute")); } /** @@ -104,7 +100,25 @@ public class CookieTest { fail("Expecting an exception"); } catch (JSONException e) { assertEquals("Expecting an exception message", - "Expected '=' and instead saw '' at 0 [character 1 line 1]", + "Cookies must have a 'name'", + e.getMessage()); + } + } + /** + * + * Attempts to create a JSONObject from an cookie string where the name is blank.
+ * Note: Cookie throws an exception, but CookieList does not.
+ * Expects a JSONException + */ + @Test + public void emptyNameCookieException() { + String cookieStr = " = value "; + try { + Cookie.toJSONObject(cookieStr); + fail("Expecting an exception"); + } catch (JSONException e) { + assertEquals("Expecting an exception message", + "Cookies must have a 'name'", e.getMessage()); } } @@ -149,8 +163,8 @@ public class CookieTest { } /** - * Cookie.toString() will omit the non-standard "thiswont=beIncluded" - * attribute, but the attribute is still stored in the JSONObject. + * Cookie.toString() will emit the non-standard "thiswont=beIncluded" + * attribute, and the attribute is still stored in the JSONObject. * This test confirms both behaviors. */ @Test @@ -163,15 +177,15 @@ public class CookieTest { "thisWont=beIncluded;"+ "secure"; String expectedCookieStr = - "{\"path\":\"/\","+ + "{\"thisWont\":\"beIncluded\","+ + "\"path\":\"/\","+ "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ "\"domain\":\".yahoo.com\","+ "\"name\":\"PH\","+ "\"secure\":true,"+ "\"value\":\"deleted\"}"; // Add the nonstandard attribute to the expected cookie string - String expectedDirectCompareCookieStr = - expectedCookieStr.replaceAll("\\{", "\\{\"thisWont\":\"beIncluded\","); + String expectedDirectCompareCookieStr = expectedCookieStr; // convert all strings into JSONObjects JSONObject jsonObject = Cookie.toJSONObject(cookieStr); JSONObject expectedJsonObject = new JSONObject(expectedCookieStr); From d334b58f45541d6435a7816d0136c0427af539cc Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 26 May 2020 08:30:25 -0400 Subject: [PATCH 436/451] Made more corrections to Cookie.ToString. 1. Made Cookie Name and Value properties case insensitive 2. Throws exception on illegal Cookie Name 3. Doesn't emit "false" flag values 4. Properly escape key-value attributes. --- src/main/java/org/json/Cookie.java | 43 ++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/json/Cookie.java b/src/main/java/org/json/Cookie.java index ddd1c69..3ce3d74 100644 --- a/src/main/java/org/json/Cookie.java +++ b/src/main/java/org/json/Cookie.java @@ -130,21 +130,42 @@ public class Cookie { /** * Convert a JSONObject into a cookie specification string. The JSONObject - * must contain "name" and "value" members. + * must contain "name" and "value" members (case insensitive). * If the JSONObject contains other members, they will be appended to the cookie * specification string. User-Agents are instructed to ignore unknown attributes, * so ensure your JSONObject is using only known attributes. * See also: https://tools.ietf.org/html/rfc6265 * @param jo A JSONObject * @return A cookie specification string - * @throws JSONException if a called function fails + * @throws JSONException thrown if the cookie has no name. */ public static String toString(JSONObject jo) throws JSONException { StringBuilder sb = new StringBuilder(); - - sb.append(escape(jo.getString("name"))); + + String name = null; + Object value = null; + for(String key : jo.keySet()){ + if("name".equalsIgnoreCase(key)) { + name = jo.getString(key).trim(); + } + if("value".equalsIgnoreCase(key)) { + value=jo.getString(key).trim(); + } + if(name != null && value != null) { + break; + } + } + + if(name == null || "".equals(name.trim())) { + throw new JSONException("Cookie does not have a name"); + } + if(value == null) { + value = ""; + } + + sb.append(escape(name)); sb.append("="); - sb.append(escape(jo.getString("value"))); + sb.append(escape((String)value)); for(String key : jo.keySet()){ if("name".equalsIgnoreCase(key) @@ -152,11 +173,17 @@ public class Cookie { // already processed above continue; } - Object value = jo.opt(key); + value = jo.opt(key); if(value instanceof Boolean) { - sb.append(';').append(key); + if(Boolean.TRUE.equals(value)) { + sb.append(';').append(escape(key)); + } + // don't emit false values } else { - sb.append(';').append(key).append('=').append(escape(value.toString())); + sb.append(';') + .append(escape(key)) + .append('=') + .append(escape(value.toString())); } } From 6029dece41229533f90ce9a082a28c989ec9268c Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Tue, 26 May 2020 09:11:10 -0400 Subject: [PATCH 437/451] ensure key names are consistent when parsing the cookie string since cookie-keys are not case sensitive, but json-keys are. --- src/main/java/org/json/Cookie.java | 8 ++++++-- src/test/java/org/json/junit/CookieTest.java | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/json/Cookie.java b/src/main/java/org/json/Cookie.java index 3ce3d74..a43d1ed 100644 --- a/src/main/java/org/json/Cookie.java +++ b/src/main/java/org/json/Cookie.java @@ -1,5 +1,7 @@ package org.json; +import java.util.Locale; + /* Copyright (c) 2002 JSON.org @@ -74,7 +76,9 @@ public class Cookie { * The name will be stored under the key "name", and the value will be * stored under the key "value". This method does not do checking or * validation of the parameters. It only converts the cookie string into - * a JSONObject. + * a JSONObject. All attribute names are converted to lower case keys in the + * JSONObject (HttpOnly => httponly). If an attribute is specified more than + * once, only the value found closer to the end of the cookie-string is kept. * @param string The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other * members. @@ -104,7 +108,7 @@ public class Cookie { x.next(); // parse the remaining cookie attributes while (x.more()) { - name = unescape(x.nextTo("=;")).trim(); + name = unescape(x.nextTo("=;")).trim().toLowerCase(Locale.ROOT); // don't allow a cookies attributes to overwrite it's name or value. if("name".equalsIgnoreCase(name)) { throw new JSONException("Illegal attribute name: 'name'"); diff --git a/src/test/java/org/json/junit/CookieTest.java b/src/test/java/org/json/junit/CookieTest.java index fc29391..7e7b62b 100644 --- a/src/test/java/org/json/junit/CookieTest.java +++ b/src/test/java/org/json/junit/CookieTest.java @@ -84,7 +84,7 @@ public class CookieTest { JSONObject jo = Cookie.toJSONObject(cookieStr); assertTrue("has key 'name'", jo.has("name")); assertTrue("has key 'value'", jo.has("value")); - assertTrue("has key 'myAttribute'", jo.has("myAttribute")); + assertTrue("has key 'myAttribute'", jo.has("myattribute")); } /** @@ -177,7 +177,7 @@ public class CookieTest { "thisWont=beIncluded;"+ "secure"; String expectedCookieStr = - "{\"thisWont\":\"beIncluded\","+ + "{\"thiswont\":\"beIncluded\","+ "\"path\":\"/\","+ "\"expires\":\"Wed, 19-Mar-2014 17:53:53 GMT\","+ "\"domain\":\".yahoo.com\","+ From 56d33b806139ac5d69b1b7ff00952f01605e09ed Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Mon, 10 Dec 2018 13:19:31 -0500 Subject: [PATCH 438/451] changes number parsing to use BigDecimal as the backing type * updated tests to support BigDecimal as the backing type for numbers * updated some test resource handling to java7 try-with-resources format * cleaned up some other minor compiler warnings --- src/main/java/org/json/JSONObject.java | 84 +++++++------- src/main/java/org/json/XML.java | 103 ++++++++++++++---- .../java/org/json/junit/JSONArrayTest.java | 92 +++++++--------- .../java/org/json/junit/JSONObjectTest.java | 93 +++++++--------- .../java/org/json/junit/JSONPointerTest.java | 3 +- .../java/org/json/junit/JSONStringTest.java | 89 +++++---------- .../java/org/json/junit/JSONStringerTest.java | 7 +- .../org/json/junit/data/ExceptionalBean.java | 3 - .../java/org/json/junit/data/MyEnumClass.java | 4 +- .../org/json/junit/data/MyLocaleBean.java | 4 +- .../java/org/json/junit/data/Singleton.java | 14 +-- .../org/json/junit/data/SingletonEnum.java | 6 +- .../java/org/json/junit/data/WeirdList.java | 1 + 13 files changed, 248 insertions(+), 255 deletions(-) diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 095f8bd..f718c06 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -2109,48 +2109,54 @@ public class JSONObject { if ((initial >= '0' && initial <= '9') || initial == '-') { // decimal representation if (isDecimalNotation(val)) { - // quick dirty way to see if we need a BigDecimal instead of a Double - // this only handles some cases of overflow or underflow - if (val.length()>14) { - return new BigDecimal(val); + // Use a BigDecimal all the time so we keep the original + // representation. BigDecimal doesn't support -0.0, ensure we + // keep that by forcing a decimal. + try { + BigDecimal bd = new BigDecimal(val); + if(initial == '-' && BigDecimal.ZERO.compareTo(bd)==0) { + return Double.valueOf(-0.0); + } + return bd; + } catch (NumberFormatException retryAsDouble) { + // this is to support "Hex Floats" like this: 0x1.0P-1074 + try { + Double d = Double.valueOf(val); + if(d.isNaN() || d.isInfinite()) { + throw new NumberFormatException("val ["+val+"] is not a valid number."); + } + return d; + } catch (NumberFormatException ignore) { + throw new NumberFormatException("val ["+val+"] is not a valid number."); + } } - final Double d = Double.valueOf(val); - if (d.isInfinite() || d.isNaN()) { - // if we can't parse it as a double, go up to BigDecimal - // this is probably due to underflow like 4.32e-678 - // or overflow like 4.65e5324. The size of the string is small - // but can't be held in a Double. - return new BigDecimal(val); + } + // block items like 00 01 etc. Java number parsers treat these as Octal. + if(initial == '0' && val.length() > 1) { + char at1 = val.charAt(1); + if(at1 >= '0' && at1 <= '9') { + throw new NumberFormatException("val ["+val+"] is not a valid number."); + } + } else if (initial == '-' && val.length() > 2) { + char at1 = val.charAt(1); + char at2 = val.charAt(2); + if(at1 == '0' && at2 >= '0' && at2 <= '9') { + throw new NumberFormatException("val ["+val+"] is not a valid number."); } - return d; } // integer representation. // This will narrow any values to the smallest reasonable Object representation // (Integer, Long, or BigInteger) - // string version - // The compare string length method reduces GC, - // but leads to smaller integers being placed in larger wrappers even though not - // needed. i.e. 1,000,000,000 -> Long even though it's an Integer - // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long - //if(val.length()<=9){ - // return Integer.valueOf(val); - //} - //if(val.length()<=18){ - // return Long.valueOf(val); - //} - //return new BigInteger(val); - - // BigInteger version: We use a similar bitLength compare as + // BigInteger down conversion: We use a similar bitLenth compare as // BigInteger#intValueExact uses. Increases GC, but objects hold // only what they need. i.e. Less runtime overhead if the value is - // long lived. Which is the better tradeoff? This is closer to what's - // in stringToValue. + // long lived. BigInteger bi = new BigInteger(val); - if(bi.bitLength()<=31){ + if(bi.bitLength() <= 31){ return Integer.valueOf(bi.intValue()); } - if(bi.bitLength()<=63){ + if(bi.bitLength() <= 63){ return Long.valueOf(bi.longValue()); } return bi; @@ -2194,23 +2200,7 @@ public class JSONObject { char initial = string.charAt(0); if ((initial >= '0' && initial <= '9') || initial == '-') { try { - // if we want full Big Number support the contents of this - // `try` block can be replaced with: - // return stringToNumber(string); - if (isDecimalNotation(string)) { - Double d = Double.valueOf(string); - if (!d.isInfinite() && !d.isNaN()) { - return d; - } - } else { - Long myLong = Long.valueOf(string); - if (string.equals(myLong.toString())) { - if (myLong.longValue() == myLong.intValue()) { - return Integer.valueOf(myLong.intValue()); - } - return myLong; - } - } + return stringToNumber(string); } catch (Exception ignore) { } } diff --git a/src/main/java/org/json/XML.java b/src/main/java/org/json/XML.java index fb44cc9..c09fb03 100644 --- a/src/main/java/org/json/XML.java +++ b/src/main/java/org/json/XML.java @@ -26,6 +26,8 @@ SOFTWARE. import java.io.Reader; import java.io.StringReader; +import java.math.BigDecimal; +import java.math.BigInteger; import java.util.Iterator; /** @@ -424,17 +426,20 @@ public class XML { */ // To maintain compatibility with the Android API, this method is a direct copy of // the one in JSONObject. Changes made here should be reflected there. + // This method should not make calls out of the XML object. public static Object stringToValue(String string) { - if (string.equals("")) { + if ("".equals(string)) { return string; } - if (string.equalsIgnoreCase("true")) { + + // check JSON key words true/false/null + if ("true".equalsIgnoreCase(string)) { return Boolean.TRUE; } - if (string.equalsIgnoreCase("false")) { + if ("false".equalsIgnoreCase(string)) { return Boolean.FALSE; } - if (string.equalsIgnoreCase("null")) { + if ("null".equalsIgnoreCase(string)) { return JSONObject.NULL; } @@ -446,28 +451,84 @@ public class XML { char initial = string.charAt(0); if ((initial >= '0' && initial <= '9') || initial == '-') { try { - // if we want full Big Number support this block can be replaced with: - // return stringToNumber(string); - if (string.indexOf('.') > -1 || string.indexOf('e') > -1 - || string.indexOf('E') > -1 || "-0".equals(string)) { - Double d = Double.valueOf(string); - if (!d.isInfinite() && !d.isNaN()) { - return d; - } - } else { - Long myLong = Long.valueOf(string); - if (string.equals(myLong.toString())) { - if (myLong.longValue() == myLong.intValue()) { - return Integer.valueOf(myLong.intValue()); - } - return myLong; - } - } + return stringToNumber(string); } catch (Exception ignore) { } } return string; } + + /** + * direct copy of {@link JSONObject#stringToNumber(String)} to maintain Android support. + */ + private static Number stringToNumber(final String val) throws NumberFormatException { + char initial = val.charAt(0); + if ((initial >= '0' && initial <= '9') || initial == '-') { + // decimal representation + if (isDecimalNotation(val)) { + // Use a BigDecimal all the time so we keep the original + // representation. BigDecimal doesn't support -0.0, ensure we + // keep that by forcing a decimal. + try { + BigDecimal bd = new BigDecimal(val); + if(initial == '-' && BigDecimal.ZERO.compareTo(bd)==0) { + return Double.valueOf(-0.0); + } + return bd; + } catch (NumberFormatException retryAsDouble) { + // this is to support "Hex Floats" like this: 0x1.0P-1074 + try { + Double d = Double.valueOf(val); + if(d.isNaN() || d.isInfinite()) { + throw new NumberFormatException("val ["+val+"] is not a valid number."); + } + return d; + } catch (NumberFormatException ignore) { + throw new NumberFormatException("val ["+val+"] is not a valid number."); + } + } + } + // block items like 00 01 etc. Java number parsers treat these as Octal. + if(initial == '0' && val.length() > 1) { + char at1 = val.charAt(1); + if(at1 >= '0' && at1 <= '9') { + throw new NumberFormatException("val ["+val+"] is not a valid number."); + } + } else if (initial == '-' && val.length() > 2) { + char at1 = val.charAt(1); + char at2 = val.charAt(2); + if(at1 == '0' && at2 >= '0' && at2 <= '9') { + throw new NumberFormatException("val ["+val+"] is not a valid number."); + } + } + // integer representation. + // This will narrow any values to the smallest reasonable Object representation + // (Integer, Long, or BigInteger) + + // BigInteger down conversion: We use a similar bitLenth compare as + // BigInteger#intValueExact uses. Increases GC, but objects hold + // only what they need. i.e. Less runtime overhead if the value is + // long lived. + BigInteger bi = new BigInteger(val); + if(bi.bitLength() <= 31){ + return Integer.valueOf(bi.intValue()); + } + if(bi.bitLength() <= 63){ + return Long.valueOf(bi.longValue()); + } + return bi; + } + throw new NumberFormatException("val ["+val+"] is not a valid number."); + } + + /** + * direct copy of {@link JSONObject#isDecimalNotation(String)} to maintain Android support. + */ + private static boolean isDecimalNotation(final String val) { + return val.indexOf('.') > -1 || val.indexOf('e') > -1 + || val.indexOf('E') > -1 || "-0".equals(val); + } + /** * Convert a well-formed (but not necessarily valid) XML string into a diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index b358b7a..df49365 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -33,7 +33,14 @@ import java.io.IOException; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; import org.json.JSONArray; import org.json.JSONException; @@ -424,7 +431,7 @@ public class JSONArrayTest { assertTrue("expected \"true\"", "true".equals(jsonArray.query("/2"))); assertTrue("expected \"false\"", "false".equals(jsonArray.query("/3"))); assertTrue("expected hello", "hello".equals(jsonArray.query("/4"))); - assertTrue("expected 0.002345", Double.valueOf(0.002345).equals(jsonArray.query("/5"))); + assertTrue("expected 0.002345", BigDecimal.valueOf(0.002345).equals(jsonArray.query("/5"))); assertTrue("expected \"23.45\"", "23.45".equals(jsonArray.query("/6"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonArray.query("/7"))); assertTrue("expected \"43\"", "43".equals(jsonArray.query("/8"))); @@ -491,7 +498,7 @@ public class JSONArrayTest { new Float(jsonArray.optFloat(99)).isNaN()); assertTrue("Array opt Number", - new Double(23.45e-4).equals(jsonArray.optNumber(5))); + BigDecimal.valueOf(23.45e-4).equals(jsonArray.optNumber(5))); assertTrue("Array opt Number default", new Double(1).equals(jsonArray.optNumber(0, 1d))); assertTrue("Array opt Number default implicit", @@ -832,13 +839,6 @@ public class JSONArrayTest { for (String s : jsonArray4Strs) { list.contains(s); } - - // assertEquals("Expected same number of lines", actualStrArray.length, -// jsonArray0Strs.length); -// assertEquals(jsonArray0Str, jsonArray.toString()); -// assertEquals(jsonArray0Str, jsonArray.toString(0)); -// assertEquals(jsonArray1Str, jsonArray.toString(1)); -// assertEquals(jsonArray4Str, jsonArray.toString(4)); } /** @@ -878,7 +878,7 @@ public class JSONArrayTest { */ @SuppressWarnings("boxing") @Test - public void iterator() { + public void iteratorTest() { JSONArray jsonArray = new JSONArray(this.arrayStr); Iterator it = jsonArray.iterator(); assertTrue("Array true", @@ -892,8 +892,8 @@ public class JSONArrayTest { assertTrue("Array string", "hello".equals(it.next())); - assertTrue("Array double", - new Double(23.45e-4).equals(it.next())); + assertTrue("Array double [23.45e-4]", + new BigDecimal("0.002345").equals(it.next())); assertTrue("Array string double", new Double(23.45).equals(Double.parseDouble((String)it.next()))); @@ -939,24 +939,18 @@ public class JSONArrayTest { String str = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":2,\"key3\":3}]"; JSONArray jsonArray = new JSONArray(str); String expectedStr = str; - StringWriter stringWriter = new StringWriter(); - try { + try (StringWriter stringWriter = new StringWriter();) { jsonArray.write(stringWriter); String actualStr = stringWriter.toString(); JSONArray finalArray = new JSONArray(actualStr); Util.compareActualVsExpectedJsonArrays(jsonArray, finalArray); assertTrue("write() expected " + expectedStr + - " but found " + actualStr, - actualStr.contains("value1") && - actualStr.contains("value2") && - actualStr.contains("key1") && - actualStr.contains("1") && - actualStr.contains("key2") && - actualStr.contains("2") && - actualStr.contains("key3") && - actualStr.contains("3")); - } finally { - stringWriter.close(); + " but found " + actualStr, + actualStr.startsWith("[\"value1\",\"value2\",{") + && actualStr.contains("\"key1\":1") + && actualStr.contains("\"key2\":2") + && actualStr.contains("\"key3\":3") + ); } } @@ -986,41 +980,33 @@ public class JSONArrayTest { String str0 = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":false,\"key3\":3.14}]"; JSONArray jsonArray = new JSONArray(str0); String expectedStr = str0; - StringWriter stringWriter = new StringWriter(); - try { + try (StringWriter stringWriter = new StringWriter();) { String actualStr = jsonArray.write(stringWriter, 0, 0).toString(); JSONArray finalArray = new JSONArray(actualStr); Util.compareActualVsExpectedJsonArrays(jsonArray, finalArray); assertTrue("write() expected " + expectedStr + - " but found " + actualStr, - actualStr.contains("value1") && - actualStr.contains("value2") && - actualStr.contains("key1") && - actualStr.contains("1") && - actualStr.contains("key2") && - actualStr.contains("false") && - actualStr.contains("key3") && - actualStr.contains("3.14")); - } finally { - stringWriter.close(); + " but found " + actualStr, + actualStr.startsWith("[\"value1\",\"value2\",{") + && actualStr.contains("\"key1\":1") + && actualStr.contains("\"key2\":false") + && actualStr.contains("\"key3\":3.14") + ); } - stringWriter = new StringWriter(); - try { + + try (StringWriter stringWriter = new StringWriter();) { String actualStr = jsonArray.write(stringWriter, 2, 1).toString(); JSONArray finalArray = new JSONArray(actualStr); Util.compareActualVsExpectedJsonArrays(jsonArray, finalArray); assertTrue("write() expected " + expectedStr + - " but found " + actualStr, - actualStr.contains("value1") && - actualStr.contains("value2") && - actualStr.contains("key1") && - actualStr.contains("1") && - actualStr.contains("key2") && - actualStr.contains("false") && - actualStr.contains("key3") && - actualStr.contains("3.14")); - } finally { - stringWriter.close(); + " but found " + actualStr, + actualStr.startsWith("[\n" + + " \"value1\",\n" + + " \"value2\",\n" + + " {") + && actualStr.contains("\"key1\": 1") + && actualStr.contains("\"key2\": false") + && actualStr.contains("\"key3\": 3.14") + ); } } @@ -1118,7 +1104,7 @@ public class JSONArrayTest { assertTrue("val3 list val 1 should not be null", val3Val1List != null); assertTrue("val3 list val 1 should have 2 elements", val3Val1List.size() == 2); assertTrue("val3 list val 1 list element 1 should be value1", val3Val1List.get(0).equals("value1")); - assertTrue("val3 list val 1 list element 2 should be 2.1", val3Val1List.get(1).equals(Double.valueOf("2.1"))); + assertTrue("val3 list val 1 list element 2 should be 2.1", val3Val1List.get(1).equals(new BigDecimal("2.1"))); List val3Val2List = (List)val3List.get(1); assertTrue("val3 list val 2 should not be null", val3Val2List != null); diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 5e5deb0..75b23a1 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -75,7 +75,6 @@ import org.json.junit.data.Singleton; import org.json.junit.data.SingletonEnum; import org.json.junit.data.WeirdList; import org.junit.Test; -import org.junit.Ignore; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; @@ -268,7 +267,7 @@ public class JSONObjectTest { assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey"))); assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey"))); assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObjectByName.query("/doubleKey"))); + assertTrue("expected \"doubleKey\":-23.45e67", new BigDecimal("-23.45e67").equals(jsonObjectByName.query("/doubleKey"))); } /** @@ -891,14 +890,14 @@ public class JSONObjectTest { jsonObject.optNumber("intKey") instanceof Integer); assertTrue("optNumber long should return Long", jsonObject.optNumber("longKey") instanceof Long); - assertTrue("optNumber double should return Double", - jsonObject.optNumber("doubleKey") instanceof Double); + assertTrue("optNumber double should return BigDecimal", + jsonObject.optNumber("doubleKey") instanceof BigDecimal); assertTrue("optNumber Str int should return Integer", jsonObject.optNumber("intStrKey") instanceof Integer); assertTrue("optNumber Str long should return Long", jsonObject.optNumber("longStrKey") instanceof Long); - assertTrue("optNumber Str double should return Double", - jsonObject.optNumber("doubleStrKey") instanceof Double); + assertTrue("optNumber Str double should return BigDecimal", + jsonObject.optNumber("doubleStrKey") instanceof BigDecimal); assertTrue("optNumber BigDecimalStrKey should return BigDecimal", jsonObject.optNumber("BigDecimalStrKey") instanceof BigDecimal); assertTrue("xKey should not exist", @@ -933,27 +932,27 @@ public class JSONObjectTest { assertTrue("-0.0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double); assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String); assertTrue( "0.2 should be a Double!", - JSONObject.stringToValue( "0.2" ) instanceof Double ); - assertTrue( "Doubles should be Doubles, even when incorrectly converting floats!", - JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof Double ); + JSONObject.stringToValue( "0.2" ) instanceof BigDecimal ); + assertTrue( "Doubles should be BigDecimal, even when incorrectly converting floats!", + JSONObject.stringToValue( new Double( "0.2f" ).toString() ) instanceof BigDecimal ); /** * This test documents a need for BigDecimal conversion. */ Object obj = JSONObject.stringToValue( "299792.457999999984" ); - assertTrue( "evaluates to 299792.458 double instead of 299792.457999999984 BigDecimal!", - obj.equals(new Double(299792.458)) ); + assertTrue( "does not evaluate to 299792.457999999984 BigDecimal!", + obj.equals(new BigDecimal("299792.457999999984")) ); assertTrue( "1 should be an Integer!", JSONObject.stringToValue( "1" ) instanceof Integer ); assertTrue( "Integer.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); -// assertTrue( "Large integers should be a Long!", -// JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); + assertTrue( "Large integers should be a Long!", + JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); assertTrue( "Long.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); String str = new BigInteger( new Long( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString(); - assertTrue( "Really large integers currently evaluate to string", - JSONObject.stringToValue(str).equals("9223372036854775808")); + assertTrue( "Really large integers currently evaluate to BigInteger", + JSONObject.stringToValue(str).equals(new BigInteger("9223372036854775808"))); } /** @@ -974,16 +973,16 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(str); // Comes back as a double, but loses precision assertTrue( "numberWithDecimals currently evaluates to double 299792.458", - jsonObject.get( "numberWithDecimals" ).equals( new Double( "299792.458" ) ) ); + jsonObject.get( "numberWithDecimals" ).equals( new BigDecimal( "299792.457999999984" ) ) ); Object obj = jsonObject.get( "largeNumber" ); - assertTrue("largeNumber currently evaluates to string", - "12345678901234567890".equals(obj)); + assertTrue("largeNumber currently evaluates to BigInteger", + new BigInteger("12345678901234567890").equals(obj)); // comes back as a double but loses precision - assertTrue( "preciseNumber currently evaluates to double 0.2", - jsonObject.get( "preciseNumber" ).equals(new Double(0.2))); + assertEquals( "preciseNumber currently evaluates to double 0.2", + 0.2, jsonObject.getDouble( "preciseNumber" ), 0.0); obj = jsonObject.get( "largeExponent" ); - assertTrue("largeExponent should currently evaluates as a string", - "-23.45e2327".equals(obj)); + assertTrue("largeExponent should evaluate as a BigDecimal", + new BigDecimal("-23.45e2327").equals(obj)); } /** @@ -1021,17 +1020,17 @@ public class JSONObjectTest { assertTrue( "negativeNaN currently evaluates to string", obj.equals("-NaN")); assertTrue( "negativeFraction currently evaluates to double -0.01", - jsonObject.get( "negativeFraction" ).equals(new Double(-0.01))); + jsonObject.get( "negativeFraction" ).equals(BigDecimal.valueOf(-0.01))); assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", - jsonObject.get( "tooManyZerosFraction" ).equals(new Double(0.001))); + jsonObject.get( "tooManyZerosFraction" ).equals(BigDecimal.valueOf(0.001))); assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875", - jsonObject.get( "negativeHexFloat" ).equals(new Double(-3.99951171875))); + jsonObject.get( "negativeHexFloat" ).equals(Double.valueOf(-3.99951171875))); assertTrue("hexFloat currently evaluates to double 4.9E-324", - jsonObject.get("hexFloat").equals(new Double(4.9E-324))); + jsonObject.get("hexFloat").equals(Double.valueOf(4.9E-324))); assertTrue("floatIdentifier currently evaluates to double 0.1", - jsonObject.get("floatIdentifier").equals(new Double(0.1))); + jsonObject.get("floatIdentifier").equals(Double.valueOf(0.1))); assertTrue("doubleIdentifier currently evaluates to double 0.1", - jsonObject.get("doubleIdentifier").equals(new Double(0.1))); + jsonObject.get("doubleIdentifier").equals(Double.valueOf(0.1))); } /** @@ -1311,11 +1310,11 @@ public class JSONObjectTest { * might inconvenience users. */ obj = JSONObject.stringToValue(bigInteger.toString()); - assertTrue("stringToValue() turns bigInteger string into string", - obj instanceof String); + assertTrue("stringToValue() turns bigInteger string into Number", + obj instanceof Number); obj = JSONObject.stringToValue(bigDecimal.toString()); - assertTrue("stringToValue() changes bigDecimal string", - !obj.toString().equals(bigDecimal.toString())); + assertTrue("stringToValue() changes bigDecimal Number", + obj instanceof Number); /** * wrap() vs put() big number behavior is now the same. @@ -1580,7 +1579,7 @@ public class JSONObjectTest { assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/keyInt"))); assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(jsonObject.query("/keyLong"))); - assertTrue("expected 3.1", Double.valueOf(3.1).equals(jsonObject.query("/keyDouble"))); + assertTrue("expected 3.1", BigDecimal.valueOf(3.1).equals(jsonObject.query("/keyDouble"))); assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(jsonObject.query("/keyBigInt"))); assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(jsonObject.query("/keyBigDec"))); @@ -2083,7 +2082,7 @@ public class JSONObjectTest { /** * Explore how JSONObject handles parsing errors. */ - @SuppressWarnings("boxing") + @SuppressWarnings({"boxing", "unused"}) @Test public void jsonObjectParsingErrors() { try { @@ -2629,14 +2628,11 @@ public class JSONObjectTest { String str = "{\"key1\":\"value1\",\"key2\":[1,2,3]}"; String expectedStr = str; JSONObject jsonObject = new JSONObject(str); - StringWriter stringWriter = new StringWriter(); - try { + try (StringWriter stringWriter = new StringWriter()) { String actualStr = jsonObject.write(stringWriter).toString(); assertTrue("write() expected " +expectedStr+ " but found " +actualStr, expectedStr.equals(actualStr)); - } finally { - stringWriter.close(); } } @@ -2739,21 +2735,15 @@ public class JSONObjectTest { " }"; JSONObject jsonObject = new JSONObject(str0); String expectedStr = str0; - StringWriter stringWriter = new StringWriter(); - try { + try (StringWriter stringWriter = new StringWriter();) { String actualStr = jsonObject.write(stringWriter,0,0).toString(); assertEquals(expectedStr, actualStr); - } finally { - stringWriter.close(); } expectedStr = str2; - stringWriter = new StringWriter(); - try { + try (StringWriter stringWriter = new StringWriter();) { String actualStr = jsonObject.write(stringWriter,2,1).toString(); assertEquals(expectedStr, actualStr); - } finally { - stringWriter.close(); } } @@ -2965,7 +2955,7 @@ public class JSONObjectTest { assertTrue("key3 list val 1 should not be null", key3Val1List != null); assertTrue("key3 list val 1 should have 2 elements", key3Val1List.size() == 2); assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); - assertTrue("key3 list val 1 list element 2 should be 2.1", key3Val1List.get(1).equals(Double.valueOf("2.1"))); + assertTrue("key3 list val 1 list element 2 should be 2.1", key3Val1List.get(1).equals(new BigDecimal("2.1"))); List key3Val2List = (List)key3List.get(1); assertTrue("key3 list val 2 should not be null", key3Val2List != null); @@ -2984,8 +2974,7 @@ public class JSONObjectTest { /** * test that validates a singleton can be serialized as a bean. */ - // @todo: investigate, re-enable this test - @Ignore + @SuppressWarnings("boxing") @Test public void testSingletonBean() { final JSONObject jo = new JSONObject(Singleton.getInstance()); @@ -3009,8 +2998,7 @@ public class JSONObjectTest { /** * test that validates a singleton can be serialized as a bean. */ - // @todo: investigate, re-enable this test - @Ignore + @SuppressWarnings("boxing") @Test public void testSingletonEnumBean() { final JSONObject jo = new JSONObject(SingletonEnum.getInstance()); @@ -3034,6 +3022,7 @@ public class JSONObjectTest { /** * Test to validate that a generic class can be serialized as a bean. */ + @SuppressWarnings("boxing") @Test public void testGenericBean() { GenericBean bean = new GenericBean<>(42); @@ -3048,6 +3037,7 @@ public class JSONObjectTest { /** * Test to validate that a generic class can be serialized as a bean. */ + @SuppressWarnings("boxing") @Test public void testGenericIntBean() { GenericBeanInt bean = new GenericBeanInt(42); @@ -3064,6 +3054,7 @@ public class JSONObjectTest { */ @Test public void testWierdListBean() { + @SuppressWarnings("boxing") WeirdList bean = new WeirdList(42, 43, 44); final JSONObject jo = new JSONObject(bean); // get() should have a key of 0 length diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index 7791d8e..e06851e 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -29,7 +29,6 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.io.IOException; import java.io.InputStream; import org.json.JSONArray; @@ -61,6 +60,7 @@ public class JSONPointerTest { assertSame(document, query("")); } + @SuppressWarnings("unused") @Test(expected = NullPointerException.class) public void nullPointer() { new JSONPointer((String) null); @@ -150,6 +150,7 @@ public class JSONPointerTest { assertSame(document.get("m~n"), query("#/m~0n")); } + @SuppressWarnings("unused") @Test(expected = IllegalArgumentException.class) public void syntaxError() { new JSONPointer("key"); diff --git a/src/test/java/org/json/junit/JSONStringTest.java b/src/test/java/org/json/junit/JSONStringTest.java index 8039cfb..788d8eb 100644 --- a/src/test/java/org/json/junit/JSONStringTest.java +++ b/src/test/java/org/json/junit/JSONStringTest.java @@ -26,7 +26,6 @@ SOFTWARE. import static org.junit.Assert.*; -import java.io.IOException; import java.io.StringWriter; import java.util.*; @@ -50,105 +49,84 @@ public class JSONStringTest { JSONArray jsonArray = new JSONArray(); jsonArray.put((Object)null); - StringWriter writer = new StringWriter(); - try { + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[null]".equals(output)); jsonArray = new JSONArray(); jsonArray.put(JSONObject.NULL); - } finally { - writer.close(); } - writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[null]".equals(output)); jsonArray = new JSONArray(); jsonArray.put(new JSONObject()); - } finally { - writer.close(); } - writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[{}]".equals(output)); jsonArray = new JSONArray(); jsonArray.put(new JSONArray()); - } finally { - writer.close(); } - writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[[]]".equals(output)); jsonArray = new JSONArray(); Map singleMap = Collections.singletonMap("key1", "value1"); jsonArray.put((Object)singleMap); - } finally { - writer.close(); } - writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[{\"key1\":\"value1\"}]".equals(output)); jsonArray = new JSONArray(); List singleList = Collections.singletonList("entry1"); jsonArray.put((Object)singleList); - } finally { - writer.close(); } - writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[[\"entry1\"]]".equals(output)); jsonArray = new JSONArray(); int[] intArray = new int[] { 1, 2, 3 }; jsonArray.put(intArray); - } finally { - writer.close(); } - writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[[1,2,3]]".equals(output)); jsonArray = new JSONArray(); jsonArray.put(24); - } finally { - writer.close(); } - writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[24]".equals(output)); jsonArray = new JSONArray(); jsonArray.put("string value"); - } finally { - writer.close(); } - writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[\"string value\"]".equals(output)); jsonArray = new JSONArray(); jsonArray.put(true); - } finally { - writer.close(); } - writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[true]".equals(output)); - } finally { - writer.close(); } } @@ -207,15 +185,13 @@ public class JSONStringTest { jsonArray.put(jsonString); - StringWriter writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[\"the JSON string value\"]".equals(output)); output = JSONObject.valueToString(jsonString); assertTrue("String values should be equal", "\"the JSON string value\"".equals(output)); - } finally { - writer.close(); } } @@ -230,8 +206,7 @@ public class JSONStringTest { jsonArray.put(jsonString); - StringWriter writer = new StringWriter(); - try { + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[\"the toString value\"]".equals(output)); @@ -244,8 +219,6 @@ public class JSONStringTest { assertTrue("Expected JSONException", e instanceof JSONException); assertTrue("Exception message does not match", "Bad value from toJSONString: null".equals(e.getMessage())); } - } finally { - writer.close(); } } @@ -255,22 +228,19 @@ public class JSONStringTest { * the original exception. */ @Test - public void testJSONStringExceptionValue() throws IOException { + public void testJSONStringExceptionValue() { JSONStringExceptionValue jsonString = new JSONStringExceptionValue(); JSONArray jsonArray = new JSONArray(); jsonArray.put(jsonString); - StringWriter writer = new StringWriter(); - try { + try (StringWriter writer = new StringWriter();) { jsonArray.write(writer).toString(); fail("Expected an exception, got a String value"); } catch (JSONException e) { assertEquals("Unable to write JSONArray value at index: 0", e.getMessage()); } catch(Exception e) { fail("Expected JSONException"); - } finally { - writer.close(); } try { @@ -294,15 +264,12 @@ public class JSONStringTest { jsonArray.put(nonJsonString); - StringWriter writer = new StringWriter(); - try { + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[\"the toString value for StringValue\"]".equals(output)); output = JSONObject.valueToString(nonJsonString); assertTrue("String values should be equal", "\"the toString value for StringValue\"".equals(output)); - } finally { - writer.close(); } } @@ -317,15 +284,13 @@ public class JSONStringTest { jsonArray.put(nonJsonString); - StringWriter writer = new StringWriter(); - try { + + try (StringWriter writer = new StringWriter();) { String output = jsonArray.write(writer).toString(); assertTrue("String values should be equal", "[\"\"]".equals(output)); output = JSONObject.valueToString(nonJsonString); assertTrue("String values should be equal", "\"\"".equals(output)); - } finally { - writer.close(); } } diff --git a/src/test/java/org/json/junit/JSONStringerTest.java b/src/test/java/org/json/junit/JSONStringerTest.java index defe4a5..a99db3b 100644 --- a/src/test/java/org/json/junit/JSONStringerTest.java +++ b/src/test/java/org/json/junit/JSONStringerTest.java @@ -26,6 +26,7 @@ SOFTWARE. import static org.junit.Assert.*; +import java.math.BigDecimal; import java.util.*; import org.json.*; @@ -269,7 +270,7 @@ public class JSONStringerTest { assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/stringValue"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/complexStringValue"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/intValue"))); - assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(jsonObject.query("/doubleValue"))); + assertTrue("expected -23.45e67", BigDecimal.valueOf(-23.45e67).equals(jsonObject.query("/doubleValue"))); } /** @@ -298,7 +299,7 @@ public class JSONStringerTest { assertTrue("expected null", JSONObject.NULL.equals(jsonArray.query("/2"))); assertTrue("expected hello world!", "hello world!".equals(jsonArray.query("/3"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonArray.query("/4"))); - assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(jsonArray.query("/5"))); + assertTrue("expected -23.45e67", BigDecimal.valueOf(-23.45e67).equals(jsonArray.query("/5"))); } /** @@ -355,7 +356,7 @@ public class JSONStringerTest { assertTrue("expected null", JSONObject.NULL.equals(jsonObject.query("/nullValue"))); assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/stringValue"))); assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/intValue"))); - assertTrue("expected -23.45e67", Double.valueOf(-23.45e67).equals(jsonObject.query("/doubleValue"))); + assertTrue("expected -23.45e67", BigDecimal.valueOf(-23.45e67).equals(jsonObject.query("/doubleValue"))); assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/complexStringValue"))); assertTrue("expected v1", "v1".equals(jsonObject.query("/object2/k1"))); assertTrue("expected v2", "v2".equals(jsonObject.query("/object2/k2"))); diff --git a/src/test/java/org/json/junit/data/ExceptionalBean.java b/src/test/java/org/json/junit/data/ExceptionalBean.java index 74d78a7..72d6c0c 100644 --- a/src/test/java/org/json/junit/data/ExceptionalBean.java +++ b/src/test/java/org/json/junit/data/ExceptionalBean.java @@ -7,8 +7,6 @@ import java.io.Closeable; import java.io.IOException; import java.lang.reflect.InvocationTargetException; -import org.json.JSONObject; - /** * Object for testing the exception handling in {@link JSONObject#populateMap}. * @@ -56,7 +54,6 @@ public class ExceptionalBean { /** * @return a string */ - @SuppressWarnings("unused") public String getString() { return "Yup, it's closeable"; } diff --git a/src/test/java/org/json/junit/data/MyEnumClass.java b/src/test/java/org/json/junit/data/MyEnumClass.java index 4d403c8..0486694 100644 --- a/src/test/java/org/json/junit/data/MyEnumClass.java +++ b/src/test/java/org/json/junit/data/MyEnumClass.java @@ -8,13 +8,13 @@ public class MyEnumClass { private MyEnumField myEnumField; public MyEnum getMyEnum() { - return myEnum; + return this.myEnum; } public void setMyEnum(MyEnum myEnum) { this.myEnum = myEnum; } public MyEnumField getMyEnumField() { - return myEnumField; + return this.myEnumField; } public void setMyEnumField(MyEnumField myEnumField) { this.myEnumField = myEnumField; diff --git a/src/test/java/org/json/junit/data/MyLocaleBean.java b/src/test/java/org/json/junit/data/MyLocaleBean.java index 846e1c5..5d3cb52 100755 --- a/src/test/java/org/json/junit/data/MyLocaleBean.java +++ b/src/test/java/org/json/junit/data/MyLocaleBean.java @@ -4,9 +4,9 @@ public class MyLocaleBean { private final String id = "beanId"; private final String i = "beanI"; public String getId() { - return id; + return this.id; } public String getI() { - return i; + return this.i; } } diff --git a/src/test/java/org/json/junit/data/Singleton.java b/src/test/java/org/json/junit/data/Singleton.java index 36a9824..224b48a 100644 --- a/src/test/java/org/json/junit/data/Singleton.java +++ b/src/test/java/org/json/junit/data/Singleton.java @@ -33,7 +33,7 @@ public final class Singleton { /** @return someInt */ public int getSomeInt() { - return someInt; + return this.someInt; } /** @@ -48,7 +48,7 @@ public final class Singleton { /** @return someString */ public String getSomeString() { - return someString; + return this.someString; } /** @@ -65,8 +65,8 @@ public final class Singleton { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + someInt; - result = prime * result + ((someString == null) ? 0 : someString.hashCode()); + result = prime * result + this.someInt; + result = prime * result + ((this.someString == null) ? 0 : this.someString.hashCode()); return result; } @@ -79,12 +79,12 @@ public final class Singleton { if (getClass() != obj.getClass()) return false; Singleton other = (Singleton) obj; - if (someInt != other.someInt) + if (this.someInt != other.someInt) return false; - if (someString == null) { + if (this.someString == null) { if (other.someString != null) return false; - } else if (!someString.equals(other.someString)) + } else if (!this.someString.equals(other.someString)) return false; return true; } diff --git a/src/test/java/org/json/junit/data/SingletonEnum.java b/src/test/java/org/json/junit/data/SingletonEnum.java index 8147cc6..3dd0309 100644 --- a/src/test/java/org/json/junit/data/SingletonEnum.java +++ b/src/test/java/org/json/junit/data/SingletonEnum.java @@ -19,7 +19,7 @@ public enum SingletonEnum { /** single instance. */ /** - * @return the singleton instance. I a real application, I'd hope no one did + * @return the singleton instance. In a real application, I'd hope no one did * this to an enum singleton. */ public static final SingletonEnum getInstance() { @@ -32,7 +32,7 @@ public enum SingletonEnum { /** @return someInt */ public int getSomeInt() { - return someInt; + return this.someInt; } /** @@ -47,7 +47,7 @@ public enum SingletonEnum { /** @return someString */ public String getSomeString() { - return someString; + return this.someString; } /** diff --git a/src/test/java/org/json/junit/data/WeirdList.java b/src/test/java/org/json/junit/data/WeirdList.java index 77cd17f..3560586 100644 --- a/src/test/java/org/json/junit/data/WeirdList.java +++ b/src/test/java/org/json/junit/data/WeirdList.java @@ -53,6 +53,7 @@ public class WeirdList { * index to get * @return the value at the index */ + @SuppressWarnings("boxing") public int getInt(int i) { return this.list.get(i); } From 5a321147921de234cdfb1773476b4932976741cb Mon Sep 17 00:00:00 2001 From: Sean Leary Date: Wed, 27 May 2020 08:23:09 -0500 Subject: [PATCH 439/451] Unified license for both src and test All code in the project is covered by the original license --- LICENSE | 179 -------------------------------------------------------- 1 file changed, 179 deletions(-) diff --git a/LICENSE b/LICENSE index c8cc5e6..6cfb9b2 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,3 @@ -===== License for the code in /src/main: Copyright (c) 2002 JSON.org @@ -22,181 +21,3 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -===== License for the code in /src/test: - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS \ No newline at end of file From d088cf014e42b75b92d932adac1645840548c76d Mon Sep 17 00:00:00 2001 From: vivek Date: Wed, 3 Jun 2020 11:46:48 +0200 Subject: [PATCH 440/451] Development for stleary#516 completed with rebased repository - Introduced JSONObject(int) constructor. - int > Initial capacity of the underlying data structure - Test for new introduced JSONArray(int) constructor. 1. Checked with input parameter: 0 2. Checked with input parameter: positive number 3. Checked with positive number input parameter and compared length 4. If input parameter is negative number JSONException is thrown: JSONArray initial capacity cannot be negative. --- src/main/java/org/json/JSONArray.java | 16 ++++++++++++++ .../java/org/json/junit/JSONArrayTest.java | 21 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index d5ad7f4..787e124 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -205,6 +205,22 @@ public class JSONArray implements Iterable { } } + /** + * Construct a JSONArray with the specified initial capacity. + * + * @param initialCapacity + * the initial capacity of the JSONArray. + * @throws JSONException + * If the initial capacity is negative. + */ + public JSONArray(int initialCapacity) throws JSONException { + if (initialCapacity < 0) { + throw new JSONException( + "JSONArray initial capacity cannot be negative."); + } + this.myArrayList = new ArrayList(initialCapacity); + } + @Override public Iterator iterator() { return this.myArrayList.iterator(); diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index df49365..eda3c06 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -26,6 +26,7 @@ SOFTWARE. import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -1119,4 +1120,24 @@ public class JSONArrayTest { assertTrue("Removing an entry should succeed", list.remove(2) != null); assertTrue("List should have 2 elements", list.size() == 2); } + + /** + * Create a JSONArray with specified initial capacity. + * Expects an exception if the initial capacity is specified as a negative integer + */ + @Test + public void testJSONArrayInt() { + assertNotNull(new JSONArray(0)); + assertNotNull(new JSONArray(5)); + // Check Size -> Even though the capacity of the JSONArray can be specified using a positive + // integer but the length of JSONArray always reflects upon the items added into it. + assertEquals(0l, (long)new JSONArray(10).length()); + try { + assertNotNull("Should throw an exception", new JSONArray(-1)); + } catch (JSONException e) { + assertEquals("Expected an exception message", + "JSONArray initial capacity cannot be negative.", + e.getMessage()); + } + } } From 4b84ba2f667670c3d555a1425cda3e52d3566906 Mon Sep 17 00:00:00 2001 From: viveksacademia4git <45398326+viveksacademia4git@users.noreply.github.com> Date: Wed, 3 Jun 2020 17:10:38 +0200 Subject: [PATCH 441/451] Changes to make the Gradle work - commented `java() {...}` within build.gradle - added following files 1. gradlew 2. gradlew.bat (for windows) 3. gradle/wrapper/gradle-wrapper.properties (for ./gradlew command execution) 4. gradle/wrapper/gradle-wrapper.jar (for ./gradlew command execution) --- build.gradle | 8 +- gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 58695 bytes gradle/wrapper/gradle-wrapper.properties | 5 + gradlew | 183 +++++++++++++++++++++++ gradlew.bat | 103 +++++++++++++ 5 files changed, 295 insertions(+), 4 deletions(-) create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat diff --git a/build.gradle b/build.gradle index 64f87d2..afe78ac 100644 --- a/build.gradle +++ b/build.gradle @@ -40,10 +40,10 @@ sourceCompatibility = '1.7' configurations.all { } -java { - withSourcesJar() - withJavadocJar() -} +//java { + //withSourcesJar() + //withJavadocJar() +//} publishing { publications { diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..f3d88b1c2faf2fc91d853cd5d4242b5547257070 GIT binary patch literal 58695 zcma&OV~}Oh(k5J8>Mq;vvTfV8ZQE5{wr$(iDciPf+tV}m-if*I+;_h3N1nY;M6TF7 zBc7A_WUgl&IY|&uNFbnJzkq;%`2QLZ5b*!{1OkHidzBVe;-?mu5upVElKVGD>pC88 zzP}E3wRHBgaO?2nzdZ5pL;m-xf&RU>buj(E-s=DK zf%>P9se`_emGS@673tqyT^;o8?2H}$uO&&u^TlmHfPgSSfPiTK^AZ7DTPH`Szw4#- z&21E&^c|dx9f;^@46XDX9itS+ZRYuqx#wG*>5Bs&gxwSQbj8grds#xkl;ikls1%(2 zR-`Tn(#9}E_aQ!zu~_iyc0gXp2I`O?erY?=JK{M`Ew(*RP3vy^0=b2E0^PSZgm(P6 z+U<&w#)I=>0z=IC4 zh4Q;eq94OGttUh7AGWu7m){;^Qk*5F6eTn+Ky$x>9Ntl~n0KDzFmB0lBI6?o!({iX zQt=|-9TPjAmCP!eA{r|^71cIvI(1#UCSzPw(L2>8OG0O_RQeJ{{MG)tLQ*aSX{AMS zP-;|nj+9{J&c9UV5Ww|#OE*Ah6?9WaR?B04N|#`m0G-IqwdN~Z{8)!$@UsK>l9H81 z?z`Z@`dWZEvuABvItgYLk-FA(u-$4mfW@2(Eh(9fe`5?WUda#wQa54 z3dXE&-*@lsrR~U#4NqkGM7Yu4#pfGqAmxmGr&Ep?&MwQ9?Z*twtODbi;vK|nQ~d_N z;T5Gtj_HZKu&oTfqQ~i`K!L||U1U=EfW@FzKSx!_`brOs#}9d(!Cu>cN51(FstP_2dJh>IHldL~vIwjZChS-*KcKk5Gz zyoiecAu;ImgF&DPrY6!68)9CM-S8*T5$damK&KdK4S6yg#i9%YBH>Yuw0f280eAv3 za@9e0+I>F}6&QZE5*T8$5__$L>39+GL+Q(}j71dS!_w%B5BdDS56%xX1~(pKYRjT; zbVy6V@Go&vbd_OzK^&!o{)$xIfnHbMJZMOo``vQfBpg7dzc^+&gfh7_=oxk5n(SO3 zr$pV6O0%ZXyK~yn++5#x`M^HzFb3N>Vb-4J%(TAy#3qjo2RzzD*|8Y} z7fEdoY5x9b3idE~-!45v?HQ$IQWc(c>@OZ>p*o&Om#YU904cMNGuEfV=7=&sEBWEO z0*!=GVSv0>d^i9z7Sg{z#So+GM2TEu7$KXJ6>)Bor8P5J(xrxgx+fTLn1?Jlotz*U z(ekS*a2*ml5ft&R;h3Gc2ndTElB!bdMa>UptgIl{pA+&b+z_Y&aS7SWUlwJf-+PRv z$#v|!SP92+41^ppe}~aariwztUtwKA8BBLa5=?j3@~qHfjxkvID8CD`t5*+4s|u4T zLJ9iEfhO4YuAl$)?VsWcln|?(P=CA|!u}ab3c3fL8ej9fW;K|@3-c@y4I;^8?K!i0 zS(5Cm#i85BGZov}qp+<-5!Fh+KZev3(sA2D_4Z~ZLmB5B$_Yw2aY{kA$zuzggbD{T zE>#yd3ilpjM4F^dmfW#p#*;@RgBg{!_3b6cW?^iYcP!mjj!}pkNi{2da-ZCD2TKKz zH^x^+YgBb=dtg@_(Cy33D|#IZ&8t?w8$E8P0fmX#GIzq~w51uYmFs{aY76e0_~z2M z(o%PNTIipeOIq(H5O>OJ*v8KZE>U@kw5(LkumNrY>Rv7BlW7{_R9v@N63rK)*tu|S zKzq|aNs@81YUVZ5vm>+pc42CDPwQa>oxrsXkRdowWP!w?=M(fn3y6frEV*;WwfUV$s31D!S_;_~E@MEZ>|~wmIr05#z2J+& zBme6rnxfCp&kP@sP)NwG>!#WqzG>KN7VC~Gdg493So%%-P%Rk!<|~-U|L3VASMj9K zk(Pfm1oj~>$A>MFFdAC8M&X0i9-cV7Q($(R5C&nR5RH$T&7M=pCDl`MpAHPOha!4r zQnYz$7B1iLK$>_Ai%kZQaj-9)nH$)tESWUSDGs2|7plF4cq1Oj-U|+l4Ga}>k!efC z*ecEudbliG+%wI8J#qI!s@t%0y9R$MBUFB)4d47VmI`FjtzNd_xit&l1T@drx z&4>Aj<2{1gUW8&EihwT1mZeliwrCN{R|4@w4@@Btov?x5ZVzrs&gF0n4jGSE33ddUnBg_nO4Zw)yB$J-{@a8 z);m%fvX2fvXxogriNb}}A8HxA)1P-oK+Da4C3pofK3>U_6%DsXFpPX}3F8O`uIpLn zdKjq(QxJTJ4xh->(=lxWO#^XAa~<7UxQl8~8=izS!TcPmAiBP5Et7y?qEbFd9Q=%IJ;%Kn$lto-~3`}&`x=AVS+Uo7N*hbUxhqVH_w^sn!74z{Ka#*U6s z=8jIrHpUMBC@@9Jn~GS<$lse*EKuX%3Swl5&3~GiK_$vn8Vjqe{mjhBlH}m4I8qK+ ztU50COh7)d-gXpq-|}T;biGa^e=VjxjjFuoGIA8`2jJ}wNBRcsx24?7lJ7W4ksNPv zA7|gcXT@~7KTID#0|EX#OAXvgaBJ8Jg!7X#kc1^Tvl;I(=~(jtn-(5bhB=~J^w5bw z8^Hifeupm;nwsSDkT{?x?E(DgLC~Nh8HKQGv`~2jMYrz9PwS^8qs3@nz4ZBCP5}%i z=w}jr2*$X-f(zDhu%D8(hWCpix>TQpi{e`-{p^y?x4?9%)^wWc?L}UMcfp~lL|;g) zmtkcXGi9#?cFOQQi_!Z8b;4R%4y{$SN~fkFedDJ&3eBfHg|DRSx09!tjoDHgD510Z z_aJLHdS&7;Dl;X|WBVyl_+d+2_MK07^X1JEi_)v$Z*ny-()VrD6VWx|Un{)gO0*FQ zX{8Ss3JMrV15zXyfCTsVO@hs49m&mN(QMdL3&x@uQqOyh2gnGJYocz0G=?BX7qxA{ zXe0bn4ij^;wfZfnRlIYkWS^usYI@goI9PccI>}Ih*B!%zv6P$DoXsS%?G)|HHevkG z>`b#vtP=Lx$Ee(t??%_+jh(nuc0Q&mCU{E3U z1NqNK!XOE#H2Pybjg0_tYz^bzX`^RR{F2ML^+<8Q{a;t(#&af8@c6K2y2m zP|parK=qf`I`#YxwL=NTP>tMiLR(d|<#gEu=L-c!r&(+CpSMB5ChYW1pUmTVdCWw|!Ao?j&-*~50S`=) z9#Knf7GPA19g%Y7wip@`nj$aJcV|SakXZ*Q2k$_SZlNMx!eY8exF;navr&R)?NO9k z#V&~KLZ0c9m|Mf4Gic}+<=w9YPlY@|Pw*z?70dwOtb<9-(0GOg>{sZaMkZc9DVk0r zKt%g5B1-8xj$Z)>tWK-Gl4{%XF55_Ra3}pSY<@Y&9mw`1jW8|&Zm{BmHt^g=FlE{` z9Lu7fI2v3_0u~apyA;wa|S4NaaG>eHEw&3lNFVd_R9E=Y? zgpVQxc9{drFt2pP#ZiN~(PL%9daP4pWd*5ABZYK{a@e&Vb`TYiLt$1S>KceK36Ehz z;;MI%V;I`#VoSVAgK3I%-c>ViA>nt=5EZ zjr$Jv~$_vg<$q<@CpZ1gdqP_3v^)uaqZ`?RS_>f(pWx3(H;gWpjR?W8L++YPW;)Vw3)~tozdySrB3A2;O<%1F8?Il4G|rO0mEZYHDz!?ke!$^bEiWRC1B%j~ws0+hHS;B8l5Wh)e+Ms7f4M4CbL%Q_*i~cP}5-B(UkE&f7*pW6OtYk5okQCEoN4v|7;(+~~nyViqo5 z(bMGQi$)KN6EmfVHv4pf2zZMJbcAKyYy>jY@>LB5eId|2Vsp{>NMlsee-tmh({;@b z@g;wiv8@a1qrDf-@7$(MR^M^*dKYBewhIDFX%;*8s zR#u?E;DJO;VnTY6IfbO=dQ61V0DisUAs4~t|9`9ZE(jG}ax#-xikDhsO_4^RaK ziZ?9AJQP_{9WuzVk^s_U+3V8gOvVl5(#1>}a|RL>};+uJB%nQM-J>M4~yK)cioytFXtnmOaJZSiE+3g}C`Im~6H z*+-vjI>ng5w>>Y!L(+DwX2gs0!&-BFEaDie4i5ln*NGP$te7$F9iUlJl4`XpkAsPm z0l?GQ17uN^=g~u1*$)S`30xL%!`LW*flwT*#svAtY(kHXFfvA`dj*pDfr0pBZ`!La zWmX$Z@qyv|{nNsRS|+CzN-Pvb>47HEDeUGFhpp5C_NL0Vp~{Wc{bsm_5J!#tuqW@? z)Be zb&Gj&(l*bHQDq7w-b`F9MHEH*{Dh~0`Gn8t`pz}!R+q~4u$T@cVaUu`E^%0f-q*hM z1To6V31UGJN7a-QW5;nhk#C26vmHyjTVZkdV zqYMI9jQY)3oZt=V0L7JZQ=^c2k){Y_lHp&V_LIi*iX^Ih3vZ_K<@Di(hY<&g^f?c$wwF-wX1VLj>ZC4{0#e`XhbL_$a9uXS zKph*4LupSV2TQBCJ4AfOXD8fs2;bAGz-qU4=Qj$^1ZJX z2TtaVdq>OjaWGvv9)agwV)QW9eTZ-xv`us2!yXSARnD5DwX_Vg*@g4w!-zT|5<}-7 zsnllGRQz>k!LwdU`|i&!Bw^W7CTUU3x`Zg8>XgHj=bo!cd<#pI8*pa*1N`gg~I0ace!wzZoJ)oGScm~D_Sc;#wFed zUo;-*0LaWVCC2yqr6IbeW3`hvXyMfAH94qP2|cN``Z%dSuz8HcQ!WT0k38!X34<6l zHtMV%4fH5<6z-lYcK;CTvzzT6-^xSP>~a*8LfbByHyp$|X*#I6HCAi){gCu1nvN%& zvlSbNFJRCc&8>f`$2Qa`fb@w!C11v1KCn)P9<}ei0}g*cl~9A9h=7(}FO!=cVllq3 z7nD)E%gt;&AYdo{Ljb2~Fm5jy{I><%i*GUlU8crR4k(zwQf#nima@xb%O71M#t-4< z(yjX(m^mp_Y;5()naqt2-VibylPS)Oof9uBp$3Gj`>7@gjKwnwRCc>rx%$esn);gI z5B9;~uz57n7Rpm8K^o=_sFPyU?>liHM&8&#O%f)}C5F7gvj#n#TLp@!M~Q?iW~lS}(gy%d&G3p?iBP z(PZQUv07@7!o3~1_l|m5m;Xr)^QK_JaVAY3v1UREC*6>v;AT$BO`nA~KZa1x3kV2F z%iwG7SaaAcT8kalCa^Hg&|eINWmBQA_d8$}B+-Q_@6j_{>a- zwT3CMWG!A}Ef$EvQsjK>o)lJ;q!~#F%wo`k-_mT=+yo%6+`iGe9(XeUl;*-4(`G;M zc@+ep^Xv&<3e7l4wt48iwaLIC1RhSsYrf6>7zXfVD zNNJ1#zM;CjKgfqCabzacX7#oEN{koCnq1-stV+-CMQ=ZX7Fpd*n9`+AEg9=p&q7mTAKXvcbo?$AVvOOp{F>#a;S?joYZl_f}BECS%u&0x!95DR;|QkR9i}`FEAsPb=)I z8nb=4iwjiLRgAF}8WTwAb^eA>QjL4Srqb#n zTwx^-*Z38Uzh@bX$_1tq>m{o8PBX*t3Lqaf$EBqiOU*2NFp{LJX#3}p9{|v{^Hg4f zlhllKI>F+>*%mu6i9V7TT*Wx-zdK z(p8faUOwGOm5mBC%UGA1jO0@IKkG;i&+6Ur8XR2ZuRb$*a}R^-H6eKxcYodlXsF`& z{NkO+;_Yh-Ni@vV9iyzM43Yibn;oC7hPAzC24zs&+RYdY&r`3&&fg2hs62ysV^G`N zHMfBEFo8E3S$0C_m({bL8QCe$B@M{n1dLsaJYIU;(!n*V?0I1OvBB=iYh&`?u8 z&~n-$nbVIhO3mMhCQRlq%XRr1;Hvl=9E_F0sc9!VLnM>@mY~=Cx3K5}wxHKEZF9pC zIdyu1qucM!gEiomw7bW0-RwbX7?o=FE#K0l4`U2KhC8*kMWaEWJyVNZVu_tY2e&4F zb54Lh=Oz>(3?V$!ArXFXh8Cb3i;%KQGCrW$W#;kvx$YA2gofNeu?@nt>Yq8?2uJQp zUTo14hS%&dHF3Uhm~Z1>W)yb%&HoM!3z?%a%dmKT#>}}kKy2B=V3{Nu=bae%V%wU$ zb4%^m?&qn==QeHo`nAs3H}wtiK~!!&i|iBLfazh6!y9F)ToKNyE0B385!zq{p)5vB zvu`R#ULIS|2{3w52c*c$4}Pe>9Fw&U^>Bb_LUWn!xPx3X-uQsv(b1XFvFzn#voq0* z5~o`V_G805QXdgAOwOjoqmZ?uzwBVYSNP0Ie8FL`P0VK1J4CzV@t&%0duHB{;yIL$FZ9 zz#s#%ZG6ya&AwE;0_~^$1K

Hnj76Oym1QVh(3qRgs)GmgnEt-KxP|nCFY3uezZn zmtR0CZ$Z_-+f07?lu_tr~IC{&U6+QOth>ZgYk4V2FI$B2V3`M`Jk zsr>>lupymPeK129PfpDt9?GA2;I>03Ktz8NxwvTroqu8oaRB&bXT}G=^2UyOW}(4H z;9sG^YwV8K7pC&&viM^X_pfeFoN!cIhrE>OPQ5E<4KKDyPhRV^BGb_^Y6GO6#w}c= zu`0fC-@F4qXQtnB^nPmfI7Uw0bLhY^09TCO+H2(nvg8jdPjMAi4oSX%GP3oeo0`ks z%DoV|waU-Q7_libJCwnnOL9~LoapKqFPpZx?5FygX zsA~*ZR7X=@i{smf?fgxbcY6Y`JvD50P=R;Xv^sANPRp-Hc8n~Wb*gLIaoZJ2Q^CFe z_=G}y&{_NXT|Ob??}$cF7)$oPQMaeN_va1f%>C>V2E01uDU=h~<_fQKjtnl_aho2i zmI|R9jrNdhtl+q*X@}>l08Izz&UJygYkbsqu?4OOclV{GI5h98vfszu2QPiF?{Tvh19u_-C^+NjdAq!tq&Rd`ejXw#` z@U15c$Nmylco)Yj4kctX{L+lz$&CqTT5~}Q>0r-Xe!m5+?du6R&XY|YD5r5C-k*`s zOq-NOg%}RJr5ZWV4)?EO%XzZg&e8qVFQ?40r=8BI-~L%9T7@_{1X@<7RjboXqMzsV z8FiSINMjV*vC^FCv_;`jdJ-{U1<_xjZg4g?ek z4FtsapW_vFGqiGcGHP%?8US~Dfqi8^ZqtHx!}0%dqZFg%nQB)8`mE$~;1)Fb76nFk z@rK#&>2@@)4vO&gb{9&~R8-_{8qz6Rmw`4zeckD(L9xq}{r(fUO0Zh-R(d#x{<0j| z?6xZ2sp3mWnC}40B~g2QinHs1CZqZH&`+x2yBLT8hF7oWNIs_#YK2cyHO6AoGRG|RM>Hyn(ddpXFPAOGh~^0zcat`%&WoEQf9)!@l*3Tt@m>Lb z6$+$c!zsy_=%L9!_;jfd`?VXDd*^Vn%G>n~V9Vr6+_D@#E+dWB#&zAE+6xJeDMr1j zV+Tp~ht!M%^6f?)LBf8U1O4G#CutR07SB>8C&_&;g3TdIR#~e~qRtwd>&)|-ztJJ#4y0|UMjhJZlS8gA zAA260zUh+!$+xMfWKs|Lr23bcy#)JNnY|?WOka&wTS7_u%*N7PrMl1Lp9gxJY%CF? zz4IA@VVxX{knZPlNF+$9)>YIj#+(|$aflt=Wnforgn6`^3T+vaMmbshBjDi&tR(a7 zky~xCa77poRXPPam)@_UCwPdha^X~Aum=c0I@yTyD&Z!3pkA7LKr%Y6g%;~0<`{2& zS7W$AY$Kd}3Tg9CJgx=_gKR59zTMROsos?PU6&ocyCwCs8Qx1R%2#!&5c%~B+APu( z<1EXfahbm{XtOBK%@2a3&!cJ6R^g|2iLIN1)C2|l=;uj%tgSHoq2ojec6_4@6b<8BYG1h-Pm_V6dkRB!{T?jwVIIj&;~b7#%5Ew=0Fx zc(p7D1TT&e=hVt4spli}{J6tJ^}WL>sb`k}&gz+6It`Yz6dZdI53%$TR6!kSK2CfT*Q$`P30 z;$+G$D*C$U(^kkeY!OWn$j@IUu0_a{bZQ=TCbHD1EtmZ0-IBR<_3=tT%cz$>EE!V}pvfn7EMWs^971+XK}~kxSc_ATJJD$?)1Gz^Jq!>Hz#KkdCJ~jb-Y*Xv01_}}=T_V-A1<3O!V9Ezf z%Lnjihb3>=ZV}jSeqNu5AAdVbe|`;|p<%W#-<$s1oDYrB;C({psqV>ENkhadsC{cfEx=teVSB`?FOs+}d#pssxP z(ihudAVu3%%!*vOIWY11fn1M0&W|(|<2lEShz|#%W|wV2qM%#+P9NOy1x8jytHpfU zh;_L^uiL<<$L@~NpRXSrkJgdC>9R=>FmVu3^#C?3H>P{ue=mcv7lBmnfA?mB|L)EF zHv%Nl|D}0Tb~JVnv$ZysvbD8zw)>|5NpW3foe!QHipV9>Zy`|<5?O+rsBr*nZ4OE} zUytv%Rw7>^moSMsSU?@&a9+OdVgzWZnD>QXcUd{dd7vad+=0Hy)4|0A`}rpCx6cu!Ee5AM=iJ?|6=pG^>q(ExotyZP3(2PGhgg6-FkkQHS?nHX(yU0NG;4foCV|&)7 z1YK!bnv%#5n<25|CZ>4r1nK=D39qMzLAja*^#CN(aBbMx${?Iur3t=g2EMK|KwOF?I@W~0y`al&TGqJ zwf#~(?!>@#|JbDjQV9ct%+51l%q|lcY&f{FV&ACRVW*%VY6G5DzTpC!e%=T30mvav zRk$JOTntNoxRv>PDlJG1X=uep&???K00ep|l_#7=YZPuRHYoM46Z$O=ZZuGy_njgC z>P@gd+zKH5SjpWQ!h_r*!ol1s{9DS@sD4}xgFxaw>|av!xrKzg?rGnhZ#uZeU~iod z3-i*Hl@7cge0);y{DCVU(Ni1zg{yE&CxYT7)@zJ%ZZABj-Fh}0au^)*aw`vpmym;( z5|JZ!EACYenKNXH%=Md{my$sI3!8^FgtqkMcUR%w_)EBdP5DZ64aCIR%K99tId6SU ziT8Ef)K%7{XuIpPi}N+&FCm$elE>oKY;3c$x+*mXy?~wt6~?ss$HGqCm=YL2xzVTQ zr>*2_F;7j{5}NUPQ(aY0+h~rOKN|IA28L7^4XjX!L0C^vFB+3R5*1+s@k7;4d#U=5 zXTy8JN^_BCx1a4O3HMa9rf@?Fz>>dq}uvkY7!c?oksgs~xrpCo1{}^PD?w}Ug z3MbfBtRi z$ze~eRSLW^6bDJJeAt^5El{T*i1*v9wX{T7`a2wAVA z%j>3m*g^lc*~GOHFNy?h7>f7mPU*)3J>yPosaGkok}2#?wX5d$9moM~{NTzLznVhX zKa}bFQt#De`atoWzj4Lb@ZCud_T9rA@6VcmvW(+X?oIaH-FDbEg#0Slwf|7f!zUO( z7EUzpBOODL&w~(tNt0z|<9}Filev&4y;SQPp+?kIvJgnpc!^eYmsWz1)^n`LmP&Ui z-Oi1J2&O|$I<^V@g2Z91l3OArSbCkYAD0Tuw-O(INJJ>t%`DfIj}6%zmO+=-L{b!P zLRKvZHBT=^`60YuZon~D$;8UDlb-5l8J=1erf$H(r~ryWFN)+yY@a;=CjeUGNmexR zN)@)xaHmyp$SJcl>9)buKst5_+XomJu34&QMyS zQR(N@C$@%EmfWB8dFN(@Z%xmRma@>QU}!{3=E`wrRCQ~W=Dwb}*CW8KxAJ;v@TAs3 zW}Pq5JPc)(C8Rths1LR}Bgcf6dPOX<#X08^QHkznM-S>6YF(siF;pf~!@)O{KR4q1_c`T9gxSEf`_;a-=bg6=8W zQ&t`BK^gsK-E0Jp{^gW&8F9k?L4<#}Y0icYT2r+Dvg!bnY;lNNCj_3=N=yd9cM9kY zLFg|R0X;NRMY%zD*DbAmFV`(V@IANtz4^_32CH*)XCc$A>P-v49$k@!o$8%Ug>3-- z$#Fpo9J>eUMKg>Cn+T0H!n0Hf#avZX4pp54cv}YcutP+CmKC~a745-zhZp`KNms;J zS3S49WEyS8gCRAY|B~6yDh*cehY52jOSA#MZmk2dzu`_XpBXx9jDf!H3~!`n zaGe=)1VkfIz?*$T3t>-Pwhrw447idZxrsi;ks;(NF>uVl12}zI(N~2Gxi)8yDv-TLgbZ;L&{ax&TBv;m@z6RcbakF^el{!&)<___n#_|XR%jedxzfXG!a2Eyi)4g zYAWkYK{bQzhm|=>4+*SLTG2<#7g-{oB48b05=?PeW;Jo3ebWlo5y5|cl?p8)~PVZqiT^A~w-V*st8kV%%Et1(}x(mE0br-#hyPspVehofF`{gjFXla1lrqXJqQKE9M)8Xe0ZO&s$}Q zBTPjH>N!UU%bRFqaX(O9KMoG$Zy|xt-kCDjz(E*VDaI={%q? zURR{qi>G^wNteX|?&ZfhK-93KZlPXmGMsPd1o?*f_ej~TkoQ#no}~&#{O=>RadgtR zvig@~IZMsm3)vOr`>TGKD&fbRoB*0xhK7|R?Jh-NzkmR}H6lJiAZTIM1#AXE1LOGx zm7j;4b(Lu6d6GwtnsCvImB8%KJD+8z?W{_bDEB$ulcKP*v;c z*Ymsd)aP+t$dAfC-XnbwDx3HXKrB{91~O}OBx)fsb{s-qXkY<@QK7p-q-aaX&F?GS z2};`CqoNJ$<0DuM2!NCbtIpJ9*1a8?PH#bnF#xf~AYOIc4dx1Bw@K=)9bRX;ehYs; z$_=Ro(1!iIM=kZDlHFB>Ef46#rUwLM%)(#oAG(gYp>0tc##V{#aBl!q``!iIe1GBn z+6^G^5)(nr z8h#bm1ZzI450T?!EL)>RWX8VwT1X`2f;dW!{b~S>#$Pa~D6#Hp!;85XzluH%v5325 z730-aW?rY1!EAt;j7d23qfbMEyRZqxP};uID8xmG@mGw~3#2T^B~~14K5?&dP&H@r zL|aXJsEcAAXEXfu2d-!otZTV=if~^EQD*!NkUFQaheV&b-?-zH6JfjKO)aYN=Do*5 zYZ-@m#)5U0c&sUqu_%-Editr5#%Ne&bs)DxOj2_}`f;I_ReEY9U&Cf3rb>A3LK(ZD zid0_-3RfsS*t&g!zw}C_9u(_ze-vc1L59CdBl(IS^yrvsksfvjXfm>(lcol%L3))Q z@ZT;aumO3Q#8R!-)U697NBM@11jQ>lWBPs#?M4_(w=V_73rsiZh8awEm>q1phn1Ks ze@D|zskeome3uilE8-dgG(EojlI(@Yhfm}Xh_AgueHV`SL##I@?VR+bEHH=sh21A_ zhs&pIN7YTLcmJiyf4lZ;`?pN0`8@QbzDpmT`$m0CTrTMiCq%dE&Cd_{-h`I~f8Kps zAuZt4z)}@T>w$9V@iLi=mh({yiCl}}d>JN)z;*G<6&mgl(CYhJHCAPl=PYK2D>*F zy;YK=xS@1JW7i=C)T04(2P#|fowalY=`Y`G8?eRMAKt|ddG9UF^0M5 zW=ZGZ5qb-z@}iS`4RKXvuPIfzUHT)rv<8a|b?bgB3n=ziCiX4m2~CdVBKHWxw2+Hz zLvqoAij9(0moKoo2$`dqS0?5-(?^RXfcsQB6hU2SAgq8wyeasuyFGcK+@An?8ZzVw zW8wwbZB@i=<<4fA7JKPkki6y>>qO3_bW>-uQ*>9g+g7M0U^`RV)YTrGu2Q=2K>fiI zY0dFs>+}xuOZE^efLK2K6&X@>+y10Oqejnnq^NjfXt9JpK4K_E=cl29 z(t2P;kl4AK_Jg9v{1(z)ESpyo_(Z`74D&J1A#J?l5&J^Ad1sm5;Po@s9v7wOs(=_T zkutjt`BaxT09G{-r>yzyKLlM(k`GZl5m+Tgvq=IN|VjtJ*Zu66@#Rw;qdfZqi15A@fr^vz?071F5!T`s>Lx5!TszI%UK|7dDU;rUCwrRcLh!TZZ9$UMfo z@Qzjw>tKS3&-pyWS^p4mMtx`AvwxVc?g?#8aj@jQ#YKDG0aCx{pU+36?ctAiz=f$k z05S(b&VPQgA(Sm`oP&M^eiHvBe&PcTb+j$!!Yx(j3iI5zcQLOn(QqfX5OElbSsQBUw7);5C92onieJyx`p{V!iwXk)+1v zA6vStRZo0hc>m5yz-pkby#9`iG5+qJ{x>6I@qeAK zSBFylj8{FU*0YbFd2FZ6zdt^2p?V;3F~kap`UQgf@}c33+6xP)hK)fmDo@mm=`47* z9S6rnwCSL&aqgZs959!lhEZZp`*>V8ifNmL;cqajMuaJ~t`;jLPB?X~Ylk_Z#Q;%} zV+sAJ=4505-DdnIR=@D_a`Gy#RxtSX+i-zInO@LVDOd*p>M-|X(qRrZ3S(>(=Oj>} z89d75&n?m^j>;SOXM=)vNoum|3YmzxjYx%^AU*V|5v@SjBYtESp^yz?eQ#>5pnCj} zJ_WCw23wGd2AA-iBve8Hq8`%B3K4@9q@a}sf$49IA^IPsX@QK)36mrzqOv?R_n9K@ zw3=^_m#j{gNR0;&+F~wlS(i8IQN8mIvIO)mkx|e)u*y+xDie}%mkZ*m)BQM^$R@-g z1FrP0{8A?EcxtxxxX&J;393ljwwG?2A2?y-1M0-tw$?5ssoEsbPi?sd2!s~TrwPLF zYo-5XYV7AU-c|Vb-v;>pVi^CwX(Rpt<9{Ic?@<9SrNu>F(gwij%?dC9^!Xo90o1-| z&_aPKo%+xyw64e&v<}F^-7sO0Cz-VOF@7**i@v&(Oy4Q8PbV+4&rKwmYyokM z48OZ|^%*mC_Q)RJ31D#b4o4Jzr{~BX4D#swW<31;qCil2qlim;e=9ymJAEXfv-|h3 z)>uqQ5~S+8IgiWW28Fqbq+@ukCLy+k7eGa1i5#G_tAUquw$FjFvQt6~kWa69KXvAj z-knF`5yWMEJvCbTX!K{L)VeNF?(+s?eNjtE5ivg^-#937-l()2nKr#cHShB&Pl^l8 zVYws26D^7nXPlm<_DYU{iDS>6Bq0@QsN%6n>XHVvP<^rDWscC!c+LFrK#)T@$%_0{ zob%f&oaq>1_Z8Ata@Y2K6n?GYg|l8SgUr(}hi4D!@KL~hjRv<}ZZ`tCD^ev=H&^0pP%6q2e+t=Ua`ag8xqWvNnIvCU|6ZA^L5v{DD)!mcQ@n6{=; z#Z)PrAz>*+h-|IV!&J*f@{xb!L7h3{?FEs*ifw5z2U9$&OkYseI68yb=V4xv*VK3- zVxGhtmedujX32y-kC{5ej-Wy#JvB~4oxTb{|1H825_B(A0#?CjUTc=PrGh6jAgK9h zoLAe`+NBdStZE@Y8UH^Rd*|R-|7Ke}wr$(CZQHhO+upHlCp)%n+fH_}S8%^%xqhu%20_1p=x#Dl9ia`c3iM+9Vh5?gyY8M9c$tJ5>}V_sidHN zoMl%rSgSK!7+Y8tQkYq|;Vh`4by2uMsUfnxkk2{S@a>V#d}fv}Yud*>paVi_~T zU!GoYwWbnG%92!Cte(zhZX-i9#KJ;b{$(aZs|{MerP#6||UUx$=y)4XOb zihyKn`_QhJ#~@_peJ*8yD4>I7wQyKkZG%#FTKZfb(@G+9x7-3@hG}+ZC&$7DwbaB$ zC)jLj7yituY&WpOWlG7Z4Tuxzdwo6k!3lgwhh7BYMyB? zO9Q5nvn77~g~c623b`Pe5efNzYD#2Sfmg>aMB5s?4NC|-0pIXy%%`J;+E{(irb!Szc8M8A@!}0zqJLoG4SJ5$~1*yRo0^Z`uObA+= zV?1sYNvzvWbP%AsMzoIo3Cwx~y%i8rHF(BgLS>tH5Ab|1wp$X_3o2_VB(pFxgQ5QQ zk@)Vy95$b%HVf4@ppX(wrv^Jwfrsu+9N_OUm}nD7Ch_7STj66EYsZR#`9k|Tf^@p& ziHwnO$p{TB#R(Q{Os>Un~0!r$JO zLZ&F%SP|%$TuG)mFeOhKr1?S!aa0jTV$2XIeZb_fgO&n{8HTe9s`L&(tKoy?OaS^$ zLHNrgYgq920EI~M>LyU7gK70$7*`nFKD^d>MoEAhsBU0%@*RW@%T(J z?+wVbz=mcN%4#7qlCpl_^Ay7VB%?+uW1WSNnQOj^tALyqTpV zkEN2C;qO_W)MYl^Ow5I;t3;z#iG82F(qe}#QeE;AjA=wM==dB(Gu+ez*5|RVxO4}l zt`o?*B;);-0`vR(#+Q^L4WH_9wklh-S-L-_zd%Q0LZ%|H5=>Z)-x#Z+m%p&6$2ScV zEBneIGo)r0oT)xjze*Q~AIqhB%lOM5Id}^eKwS!?b_;B&TouZsemyL&y`)#FX}ZKp zp)ZnB*^)1P@2bCoe+Z|#KhTBNrT)UN@WIuudw})fwHl)re1|b~E1F=xpH?7L77p>5 zei$aD@KO0<+zo1<&7OuZatNsPq24Whu%0jD_ z$ZZy6MzayYgTJulNEy8D$F%JDYgx|d6{6kpDg#s170<15bM#4tzvrDU$6bvu-hH@6 zgcjq&3aR3k(23$FaUA|iuoy*bO{2F6W0<+ZdsYvXjc?d@ZT8kM!GD}r@qr;TF@0Hb z2Dz-A!HZ$-qJ?F%w6_`t`8xk$f$MNBfjqwvJiVdD+pf7NVFGh?O=qp2vh%UcYvc{rFldib~rkIlo`seU%pO_6hmBWGMcUhsBSWiQYYPMX<-Cjp49@7U==iS57bG zw3T9Nbm`)m9<<4e$U74`t~zRo0JSfi}=GdQXGLLPyW zlT^I}y=t$j{Vx!wN^z8X4l0|@RNrC#)G>bK)7IT7Qop>YdS^NnI3gfP>vtp)pXkr2WSVcAAv8uN>@ z`6)kICvNYU$DA8pnkl4sQopDC6<_M8zGJ^@ANXJL(yd#n1XFj9pH;rld*gwY8om_I zdB55w@FUQ_2k}d%HtQsmUx_7Mzftky&o2X2yDQrgGcehmrDDDtUJj5``AX$gzEbMc zUj2Qzp)Lo>y-O*@HJ|g9$GR2-jgjKfB68J6OlIg;4F2@2?FlW zqj|lO7A2Ts-Kd!SO|r9XLbPt_B~pBpF40xcr0h=a&$bg(cwjp>v%d~Uk-7GUWom?1 z92p+C0~)Og*-N~daT#gQdG{&dPRZso(#{jGeDb1G`N)^nFSB`{2-UQ&!fkPyK`m03 z_Di94`{-(%3nE4}7;4MZ)Pmawf#{}lyTSs5f(r;r1Dp4<;27K=F}Oga^VsUs3*NIn zOsYstpqpRF&rq^9>m50LRORj>=;{CV2&#C$-{M5{oY9biBSoQyXvugVcwyT-19S;pf!`GSNqb4**TI%Y z*zyV)XN3Fdp3RNNr9FU+cV*tt?4L8>D@kJp^rkf_rJ~DPYL}oJngd1^l!4ITQN`0RTT^iq4xMg|S6;d}lznE$Ip^8pW-CHu zP*^!U>Lcd3*shqa)pswq;y<|ISM1g1RG#`|MSPNAsw*XH1IAD(e(Kgqp6aDHgv>fI z!P67$z{#()Pdo3;4dUoy*Xor(O?+YTRPe=g*FfRj*9q9!8p%1l>g3e^rQ_nm{(@4t z?^nMDC2J8@my5q0QyCljCSp_@)No+6bZ*y)lSdrkLFcR6YOHu*vZ-q(C);5$MmM_z z1WT>Gc8g%`Rt~6*!}JhWi0=Rc_z5c8GR9YXW+cdoK~Ea(@wyXf|89HagNuFAO-V7k zUb|9zaCCWH3^Fz(m7$8K$|0ZOP!SNpgP!ql<)!z8w$Z$?9gq2f<~koe3|zD=imLfD z>IV5?SkRZ;7JlOG%z%Tlze$GXr0A}ResyF63ZGZVDLv2k4HWtoqoCaq+Z&GaVKuLA z>@zhNjYYc=sexH?;DTe4&2vnQE}C@UFo&|qcLddvH0FwswdRUc(p*X&IT^Zu>xLpG zn(@C%3ig(l2ZPm#Fc){+0b+%O7nt4zbOt+3@GQVm|1t70=-U(>yo3VY2`FnXFHUyi zwiqf(akt0kEE5_Pa-a*VCS}Pi6?`~P%bvX6UT~r-tUAY%I4XF3^nC+tf3alyL{M`w zv?aVQ#usdwpZmkrfv19O39}tQPQM+oY**a{X?@3Qe>r$+G!>r#?Id&U&m^HU(f= zjVpSi9M||1FyNQA&PO`*94&(qTTMQv3-z`bpCXs-3bX}#Ovqec<>omYhB*VrwxqjY zF3#OXFsj`h#G?F}UAilxTQ|78-edHc-Uc-LHaH*Y(K%R#dVw>_gz}kRD4s#+U&Pq= zps)kMf_t9`GHR7CO4zI8WVj0%qiSqy50N{e_5o#GrvNhMpJf5_sCPrEa%a@ltFnss ziaWh26vEW4fQp}qa4oP(l4xIMpA)~VHD9!lP%;Tm`(HD$jYMM-5Ag>S(gC35J35$%?^gk(r|`4Ewi-W z;f&;B*fO=kC@N=r<-#nGW|yXE;`zb0Y3TJOAkw1a$SQgoTawHZTck+V%T=spmP`^BHihc(jc+S1ObX%6AYQ6LVVc+BfM*P{2s0T2z zVIs*5{ql%#CKAzv0?@S+%||z;`dpfj0Y(VtA51n$j%sG5I%A|h98VU}PkVZFrk1*G zaw75v3(N50lanvr&ND4=7Db;HS4fpi)2vTME7aD2-8N5+kcOXmYCrLE?*5&dWhvB` zbD5)ADuIwwpS*Ms;1qyns(8&tZ*)0*&_lNa`_(phwqkL}h#WdX_ zyKg%+7vP>*&Fus9E4SqIN*Ms`QLB(YOnJ|md%U|X`r#tVN$#q6nEH1|blQ?9e(3|3 z`i#;GUl~v?I6&I6%YvkvmR?*l%&z)Pv8irzVQsWrZSr%aoYuPJa#EjK|4NmiuswK= zlKP2v&;yXv3>LQ$P){aYWrb)5GICwbj;ygw>*amKP;Z{xb^cF}O@IeQ^hB-OjEK{l z>#PNyLuVkeDroL9SK2*ChHmJJSkv@YRn7)E49fy!3tqhq`HtHs_(DK|2Lyv(%9L&f zSy+H}Uk{nE2^5h7zN7;{tP3)$1GK9Xcv^L48Sodg0}ZST@}x607yJo2O*XCfs7*wT@d?G^Q6QQRb!kVn?}iZLUVoyh8M4A^ElaHD*Nn2= zkfCS=(Bg9-Mck6K{ z%ZM59Rs4(j1tSG1B#wS=$kQfXSvw6V>A(IC@>F;5RrCos`N{>Oyg|o*qR2EJ>5Gpe ze~a4CB{mmDXC7C>uS@VL&t%X#&4k<`nDx;Zjmo%?A4fV3KOhBr;VuO!cvM8s2;pG5 zcAs!j?nshFQhNA`G3HMS z?8bfRyy1LwSYktu+I7Hurb-AIU9r|rl5nMd!S&!()6xYNJ1EqJd9BkjgDH@F*! zzjtj4ezywvlkV7X@dG^oOB}T76eK=y!YZB#53LhYsZuP&HdmVL>6kH8&xwa zxv8;t-AE>D5K<{`-({E0O4%fGiLVI8#GfZ0aXR6SfYiPUJKnujMoTI5El<1ZO9w|u zS3lJFx<7XUoUD(@)$pDcs3taMb*(v2yj#G)=Mz-1M1q@Tf4o{s9}Uj9Yo?8refJwV zJ;b+7kf0M}fluzHHHS!Ph8MGJxJNks7C$58^EmlaJcp`5nx+O7?J)4}1!Y>-GHf9o zk}oTyPa>+YC$)(Qm8|MhEWbj?XEq}R=0NFH@F3ymW>&KS!e&k5*05>V@O*~my_Th; zlP05~S5@q+XG>0EuSH!~gZe_@5Dbj}oNIiPJpEOip+3l!gyze@%qOkmjmx=?FWJLF zj?b}f8Vet*yYd16KmM43rVfZo?rz3u|L6Foi*GQe4+{REUv9*}d?%a{%=8|i;I!aT z7Wxm}QJC`?cEt9+$@kSkB!@`TKZz1|yrA1^*7geq zD5Kx-zf|pvWA+8s$egLrb=kY385v2WCGL{y4I15NCz5NMnyXP_^@rsP#LN$%`2+AL zJaUyV<5;B^7f+pLzTN50Z~6KC0WI<|#bMfv+JiP3RTN^2!a7*oi+@v3w*sm5#|7zz zosF*{&;fHBXn2@uguQ1IDsh(oJzH#i4%pk;Qh^T zfQLyOW;E*NqU!Fki*f-T4j(?C$lY2CT{e!uW}8E(evb3!S%>v^NtNy@BTYAD;DkVo zn9ehVGaO7s?PQBP{p%b#orGi6Y&~<;D%XLWdUi}`Nu-(U$wBBTt*|N4##sm2JSuWc)TRoYg57cM*VDGj~ka<=&JF zo8=4>Z8F`wA?AUHtoi$_hHoK!3v?l*P0$g^yipOWlcex4?N2?Ewb1U=lu}0`QICA4 zef61j-^1p}hkA*0_(esa!p%dX6%-1e-eMfQsIp6wRgtE=6=hDe`&jel{y=6x5;78s z?5^{J|t!#x1aS8<3C`v%E%u{*wZwSXr$0Owl5_ zmXh>D>C_SjOCL^CyGZpBpM5`eymt{*rf~9`%F&&o7*S!H%3X)7~QFgn^J>6 zD+yV}u{HN-x9*_$R;a+k?4k*1f)rE~K|QvcC3dlr>!nftB?gE-cfcPMj&9mRl>|Lg zQyCe|&SuZopU0>IfRmcV3^_mhueN5oQ=J+H4%UsSIum4r4!`^DJqZr?1j3BU)Ttzg z6LwM)W&UEMIe*H2T6|{rQ;x9qGbp7ca#-!Egm4|ECNTMN);`>2Q&%|BpOdIJ4l|fp zk!qEhl;n(Y7~R1YNt7FnY10bQZXRna2X`E_D1f*}v1bW^lJorDD0_p2Rkr32n}hY! zCDB(t$)4YOd)97R60gfg3|wrlsVs#4=poh4JS7Ykg$H)vE#B|YFrxU-$Ae^~62e;! zK9mwxK?dV4(|0_sv(zY&mzkf{x@!T8@}Z6Bf)#sfGy#XyRS1{$Bl(6&+db=>uy-@y z$Eq~9fYX$06>PSKAs#|7RqJ3GFb;@(^e`jpo-14%^{|%}&|6h{CD(w@8(bu-m=dVl zoWmYtxTjwKlI!^nwJ}^+ql`&fE#pcj*3I|_Z>#y##e@AvnlSN4po#4N#}WT)V5oNP zkG+h_Yb=fB$)i`e2Fd28kS$;$*_sI;o0Xoj#uVAtsB6CjX&|;Bk}HzQ*hJ!HDQ&qZ z^qf{}c`l^h5sg-i(pEg#_9aW(yTi?#WH=48?2Hfl_X+(SfW)_c48bG5Bf+MDNp>Y#Mpil%{IzCXD&azAq4&1U10=$#ETJzev$)C*S;Pr9papU3OabRQk_toRZ!Ge(4-=Ki8Db?eSBq~ZT#ufL6SKaXZ+9rA~ zQwyTQTI7*NXOhn?^$QOU>Y6PyCFP|pg;wi8VZ5Z$)7+(I_9cy--(;T#c9SO;Hk~|_ z0tEQ)?geu8C(E$>e1wy%f@o;Ar2e#3HZP$I#+9ar9bDa(RUOA+y!oB;NEBQ`VMb@_ zLFj{syU4mN%9GF;zCwNbx@^)jkv$|vFtbtbi7_odG)9s=q(-PtOnIVcwy(FxnEZm&O^y`vwRfhB z7Urcums9SQS6(swAgl?S|WDGUTFQu51yG$8069U zviuZ=@J&7tQ8DZG<(a->RzV+sUrmH$WG+QvZmUJhT*IoR3#3{ugW%XG0s?_ycS6V6 zS)019<_Rl@DN~8K4#w3g_lvRm4mK3&jmI$mwROr0>D`mX+228Dw4r;mvx7df zy~$zP8NjVX?xkGFaV>|BLuXMQ+BN+MMrIB4S6X)p&5l$;6=S8oI9qi&1iQbs?TroDMfCmIeJ}pbVVtVqHhS(zutEy6#UjTk29-+3@W0`KfehW`@np zhhu#)O&g%r)hTj4b$CY41NYp_)7!bYyG;v(rts z^}YDJt2W88H^H;e$LSm3dh=~yi@)mzJtEfW8=4avbeOE&;Oc>-6OHO+MW`XBZ4rO6 zS;nAi**w3Yso4&Ty+8f$uvT?Z)eaLe$KW1I~9YM2zeTIT}C%_G6FPH-s5Wi3r`=I&juGTfl zZ;4qFZV|6V0c&>t!Y>mvGx#1WWL0N5evV=u28K9**dv`}U3tJ$W?>3InXiwyc)SA% zcnH}(zb0@&wmE>J07n#DOs7~lw>5qUY0(JDQszC~KAAM}Bmd-2tGIzUpO@|yGBrJyXGJk3d+7 zJBN0$?Se(rEb0-z2m%CBd;~_4aH04%9UnSc4KP!FDAM5F_EFujJZ!KDR-fn181GX` z8A?8BUYV}D9bCE0eV~M>9SPag%iVCLWOYQJDzC4~B~Ct0{H7x|kOmVcTQ;esvyHJC zi$H0R73Z8+Z!9^3|2tNut#&MVKbm`8?65s)UM8rg6uE(|e^DYqvoc15-f;u8c=>3;Viz*T# zN%!T+Hex0>>_gUKs%+lgY9jo6CnxL6qnQ>C*RseLWRpipqI;AQE7;LUwL`zM%b`Vu z%Sa-+?a#+=)HaD|k2%_(b;pHRF96(c;QyPl6XHL8IqGQKC$M8R=US-c8;hUe?LKo&l!{V)8d&55sUXEu z5uITcO~`ipddh+Nr{7ibp^Wd{bU)^3##<5`lkuqfckxEU*9{pgNpTB2=ku1c-|3dK z|LIQF=ld@I7swq^4|G1VA}BK85&>2p#*P95W`I1FF(8G9vfNJ6MoN$+C^M89u!X=< zJSS%l?Qj>$J%9?0#0&S6#*h*(-9Z$}q*G#hP?cX7cAvM0eiVFhJJ~$`iZM!N5NhDb zi<1u_m#?jzpIaOe7h|Kiap#mHA`L|)ATnPJ7du{^ybuNx@1jA+V1l8ux#{LJ#teM(6=%gZcMq24J$2p z`wcC!qRssmwUv4H6Psw{(YdDNOv$!sq&O1SvIS}fCKZa+`T=Ayt@uZjQqEC{@Uj+| z!;i3W+p~=@fqEEhW@gT^JtCR<`m`i|Htg<TSJ&v`p;55ed zt@a|)70mq;#RP@=%76*iz>fAr7FKd|X8*@?9sWOFf$gbH$XFG zcUNu#=_+ovUd>FW*twO`+NSo*bcea=nbQ_gu^C7iR*dZtYbMkXL5mB@4a3@0wnwH! z(fZKLy+yfQRd%}-!aPC z4GB%OvPHXl(^H(BwVr6u6s=I;`SHQ1um7GPCdP-BjO%OQUH!_UKbEGvHCY}{OL`8FU$GZ;Y$SlS$-0VjK%lCP?U0shcadt4x7lN4%V}wBrLEbiEcK-OHl+pcBNSqN#mftpRj2A4Q z+av@-<#t_Dj_FN^O2~wq(ij1O*+=RVl+6gNV^~CI1UED- zn^zN@UOq8?q58b^4RA>lV}x;jA2OE=SqMYV9P#RsUlI+pp!y*jpwHgp-w3i$V)%?L z>irn1pnRc|P@r|Z0pCeMZ*k$}$`1GVGCT&QtJ`V%Mq!TXoge?8Fjn$bz}NqDn*2ZQ z$p3@F_^(}IVS76>OLNzs`O5!pF=LZ$<&gyuM$HQzHx8ww^FVxnP%Yv2i=m*1ASF~~ zP=!H}b`xl`k0pL5byku2QOS~!_1po!6vQyQL#LQ#rIRr?G5^W?yuNvw-PP{}%m35i$i+I?DJ%RGRcqekT#X~CxOjkV1UQrd&m_bbJ+gsSGbPwKS{F& zU-`QNw!*yq#Co#{)2JvP-6>lY$J$2u+e=r0&kEc#j#jh@4Tp;l*s<28wU%r= zezVPG^r*a?&Fn_(M|A7^xTPD998E-)-A4agNwT?=>FbrHz8w~w?hWBeHVYM()|buJ zvGv4j<%!U_Rh^ZKi~2(h1vk-?o9;`*Zc}m5#o@a1ncp)}rO2SDD9y!nT$_Eb%h`>% zDmssJ8Dl=gDn<-7Ug$~nTaRzd?CJh;?}nCco$7Pz<#J8;YL40#VFbAG|4nA$co;l^byBOT2Ki@gAO!{xU7-TY|rujdYTaWV(Rr{Jwu?(_TA zDR1|~ExJBfJ?MAReMF47u!oEw>JHVREmROknZUs2>yaboEyVs$Pg1f6vs06gCQp$b z?##4PWI#BxjCAVl>46V_dm4?uw=Y@h#}ER4|ACU{lddiweg`vq>gmB25`XuhNai1- zjt{?&%;TRFE+2Y_Gn;p^&&|bU44M=`9!Mc%NbHv|2E4!2+dUL z>6be$Kh|Duz}+)(R7WXsh!m`+#t^Its($x`pqDaN-^E z?*a=0Ck^rZBLQV~jY-SBliN&7%-y3s@FB;X)z(t&D=~@U0vT%xfcu`Lix=W#WVE{{ z2=C~L$>`~@JCIg8RAyk= zYG`(@w4H95n0@Fqv16~nlDU!+QZw&#w@K)hv!V>zA!ZOL$1Iykd&Su3rEln@(gxO| zxWc++T-rQEIL+j7i`TeatMfp4z7Ir31(TE4+_Ds@M|-+cwQg(z>s=S}gsSz{X*Wm+ ziKJWgOd`5^o|5a#i%?Gvw~8e?Rpi7C>nQ5dvPHVTO$PI^mnJ*7?gd3RD{|c_a>WrXT#Es3d}(k z$wpmA#$Q^zFclx{-GUL_M$i0&mRQMd4J#xq-5es)yD{kYCP1s!An(~K5JDRkv6DUSKgo^s@lVM5|V4mWjNZp zsuw^##l%rbRDKglQyj?YT!nk$lNUzh%kH705HWhiMuv(5a<~yoRDM&oCqm+1#S~|8 zA$g2Xr=}p_FX%Eaq{tUO9i*Q1i!>$+1JYZCL}flWRvF0y1=#D#y-JQTwx6uP-(bC} z_uP7)c;Xd`C6k#JVW?#Id7-|`uW+hN0>OM=C2Ta^4?G zr;EvxJ{%l|8D-heRYRM%f*LBC)krHZJ@%&CL0)FADWh14&7KV<9km6gE=o9(7keg~^rIQtthK^_8%Jk&aZLY_bc6SbY>IcwDK9{sV*t1GfKwf8aCo8t za)yALEi^-WXb!k6n>W-62Z^n8hO|eRYr&uZiW5d_URi??nl*aGu?ioQ+9RF9u8kwD z6UZ6HVd(G%l9>y7E)uyn?gAJMKeki0@tG*jdcE-}K?8(D-&n=Ld1i=A1AI<1z>u5p=B z<1}|q3@2jNxW-}Q4z~s|j&^Qc;nXIdS3K8caP_07#ig} z#KAD&ue2jXc&K#Q`Hy#x+LeT4HHUCzi1e?*3w{tK+5Tij(#2l2%p#YGI-b~{5{aS8 z!jABC*n6y~W|h;P!kn(a4$Ri2G118!?0WHDNn((QDJP^I{{wPf<^efQWW?zS>VS?X zfIUgCS{7oV$|7z2hJBt+pp1CPx4L{B_yC3oWdE)d)20WG6m5qknl}8@;kjPJE@!xP zV(Nkv^-Vz>DuwBXmKT(z>57*D<$u=Blt)IS-RK0j89omD{5Ya*ULWkoO)qeM_*)jF zIn87l{kXPp=}4ufM1h7t(lAL?-kEq>_DE-in8-!@+>E1+gCV9Fq)5V3SY?**;AKq0 zIpQ(1u*3MVh#tHRu5E5=B{W-QOI34plm`#uH(mk*;9&Re%?|v-=fvb;?qvVL@gc|l z8^L?2_0ZrVFS-stRY(E>UiQeG_sMrw5UiO znGFLOP-GO{JtBM@!)Q37k3G_p&JhdwPwtJS6@R4_($Ut^b!8HP{52-tkue8MG=Zwr z7u6WaFranJq4oNadY)>_6d~?pKVxg$2Uz`zZPnZVHOh-;M|H7qbV0OF8}z;ZPoI+| z(`e}bn6u*kJpRLC>OZ}gX#eHCMEk#d8y$XzSU;QZ|An$pQ%uZC$=Ki!h@&m8$5(xCtGaY3X1FsU?l5w^Fr{Q-?+EbUBxx+b?D z80o*@qg0juG;aZhj=tO=YHjfo=1+-NqLME~Kw7Y1A*?}M7#cOyT(vd$1tVPKKd@U! z&oV!RzZcK6gPWj`*8FIAy2I&x``h_sXPe*O{|ih(Y+V3|o68MWq~2Iy^iQ8RqK76f zC$1+hXqd^jsz`U{+EFo^VQNrLZt#R`qE*>2-Ip&(@6FmtAngx@+YnG}b5B9Y)^wg#oc z24KlT2s!H_4ZR^1_nDX#UH4(UTgl603&Q3g{G4!?6Sl9Om=Sy|8CjWO>d@e9?Q%s- z-OS3*W_H7*LW|Ne{b+^#LqQ}UKDmiZDma@no2!ydO^jcm>+z379K%=Ifs{20mT|xh zP$e7P=?N(tW4PMHJOQ`a8?n}>^&@<`1Rgo`aRevPp^1n7ibeS6sc8^GPe>c&{Kc+R z^2_F~K=HVI45Pf|<3)^;I{?H}vU7-QK3L1nHpcn3!1_)<$V;e0d_b8^d1T==rVpky zZTn~UvKrjdr11k}UO@o>aR2wn{jX5`KQQM1J1A?^wAFvi&A#NA#`_qKksu`sQ0tdM ziif17TO<{wDq_Q;OM}+1xMji^5X=syK=$QdZnS#dwe$;JYC7JozV8KpwfV}?As|^! zFlln0UitprIpuzLd$`<{_XoUV>rrHgc{cUQH-Px#(_Ul%=#ENrfJe@MRP_$E@FLMa zI`(J)Imw$o427@Oc^3(U&vz}<3Lfmy7diVpJJJ@gA>e;q-&gj zcGcBC_luF%_;**EB?o--G?AkaruJ%-b*8aX$4E+-?V@RWMnjHJ;hx27Vd7l0nUUY( z6OQb&8g8cvN3LZ%^xvIav*X|Epqm@yrTZk9U{GSZXAUJt8Lh(%7?Eaf&AzmXOVvU| zmz<@l1oMe#^POR38KT6q3@c`{%eYNu4ccurv`q?b5DzLxENjSfYOJHAI$MbSNgB*D zJsP>i*BgrFlIn?x&DH9x~UbPBtMFj{_vJ#CaAF>1$oE&k`EF&L@HCa@mN>Q7~!RU>7 zW%fv84aCKSgBacmuvg}r@)YKqO$U{D5|!`vG-Gp%An}raz2gESWm0Exhux4C)zE}} z_@kn z3t}bvm?L+@@az@<*jG>(Xopq&c*;^mttlJ!mv;5k6o%Ac<_`o`4G3qzzo(GO{!&F8 zW+~bF?S;7gO1dQ@>gwZ?iIHjE#^@;Ix!Z`R6{RYLlGB&v4A)ha(2hc`RGV-8`LcvSf+Y@lhT%(Z7$tWEF;cZs2{B|9k#&C}sPyr; zd-g~${TqY7E$9X+h4_(yMxQ%q;tm(h(lKzK)2FQ%k#b2}aMy+a=LHYgk?1|1VQ=&e z9)olOA5H}UD{%nu+!3^HsrBoX^D9Iy0pw!xNGXB6bPSpKDAaun{!fT~Z~`xp&Ii~k zdac?&*lkM+k_&+4oc6=KJ6RwIkB|st@DiQ!4`sI;@40>%zAG^!oG2@ z@eBM$2PJ@F&_3_}oc8A*7mp-0bWng^he9UYX#Ph*JL+<>y+moP^xvQF!MD_)h@b}c2GVX8Ez`x!kjAIV>y9h;2EgwMhDc~tn<2~`lf9j8-Q~yL zM=!Ahm|3JL3?@Tt(OuDDfljlbbN@nIgn#k+7VC+Ko;@iKi>~ovA)(M6rz5KP(yiH| z#iwJqOB7VmFZ#6qI~93C`&qTxT(*Q@om-Xb%ntm_?E;|58Ipd1F!r>^vEjy}*M^E(WslbfLE z<+71#sY~m$gZvoRX@=^FY}X?5qoU|Vg8(o`Om5RM6I(baU^6HmB<+n9rBl@N$CmP41^s?s1ey}wu3r3 z4~1dkyi%kA#*pLQy0phlXa-u(oK2Dwzhuex$YZv=*t*Tg5=n~H=}fJA!p2L78y3D2 zimkqC1gTU(0q||k9QM#><$b-Ilw#Ut2>JF=T^qN34^qcBEd={! zB)rxUbM2IwvMo?S;Id^aglw}-t9et}@TP;!QlFoqqcs(-HfNt9VqGFJ4*Ko*Kk#*B zGpJ>tA9(=t|4#M!kBaf%{$Kfj3-uf|ZFgiU`Bo>%k_OuAp~vnE^_Tg8*% z*?)4JdzyMTzvNDy{r$c``zBw=Vr)6c4}CBIv#mw()3h7`?V-;LF?J&N5a>kjpy;9n zQyXvuu`n?+W84QV=(i`JEJY=}Ak+u4>!Lyt2P!$nBl}T=^|pG*z@)_l!)OKB{tIV&&E@hj=OIhSBHgPV~X=R3NrTMh?VzDm?1yW^IJ&zzAn2{8rE~MRX5EE)a(-T&oE)1J4pGXBYi+nexX-?5! z{EZ4Ju=Y8MQ87=uNc2t^7@X)?85KeSoc`?BmCD;Uv_cwQaLyc}vvnJKHV zuK)H_d)xhGKB!_pRXv{$XgfZ_(8G%N3o$ZI#_ zixQj~so0*m^iuA!bT>&8R@>b%#B~zbIlwt4Ba0v&>B(`*Z;~?6!>-aQ zal+Qt4^dCcjZZMd4b4Khg~(GP#8$3BeB8j!-6l?*##)H?J$PeUy)cA_I26#0aggao zaM5PweS_Sb@{OZ@Uw*(!DNV)KTQU+BTRi?AUAv0Vowth`7mr9)ZVC+TI?@; zWGL&zydnsuE3+D7#U~P%PrxpD3nTc9#mm621iX*?ZMS_Q#n9SzOJ~Hg@`rX{d?qJ; zt}`76!H)MX#=VKifJZP$3<8@}0-llthFpq3FV;(UP$-k63MkHHq~J&}d?C<+c~*Zk z<#G&>AD7EoiAVO38TO2TOBKN>6N|JS*{+`}V-)T0j(bAzGlEUWEvWLrMOIItYexh) z?he>SJk*#bywgDF6+*&%>n%0`-3tOY72+n&Q1NJ`A-bX*2tJV(@;%b6&RxMcUd7+# z@UzOmc9DolSHc-D$5(GouinaE%&uOVMyD&CTdKaEB{Qap4_wU7_=23CULKQ;jmZuV;+Y$(`#Gh0@}s7-!qk-^&#IG>7B{yft?UoA)H5 z|B0u3Tu0TF{AB0jpT|E&RsYB$3WiQU^5p*|f)^Si_#^j+Ao^|5(gNjn+!0|NtXDt* z5fwxpajl@e0FrdEuj2s#Pg>gUvJdko9RBwEe_4@?aEM?SiA2nvm^tsLML{-AvBWM7 z_bm7%tu*MaJkUWd#?GWVrqaQ0>B%Azkxj+Yidvc$XdG1{@$U~uF|1oovneldx`h;9 zB1>H;;n1_5(h`2ECl?bu-sSY@d!QTa`3DrNj_F@vUIdW5{R7$|K{fN11_l7={h7@D z4}I;wCCq>QR6(;JbVbb4$=OBO)#zVu|0iK~SnW~{SrOq&j*_>YRzU&bHUhPPwiy($ zK0qin8U;#F@@}_P_flw`bW_v^G;ct?Pb65%=%egDBgS#YF3?E36$9xzdvYqjAZoK#hcjctJu~MF^S*$q3`o2;!L|jPnM1x*Q~qF%BH(5UDFYglsJwO zEdEuB7NihnTXK6$)F~``nmSQNFP7x7hE{WuOjTAhEjGw#XxvL@S;aZYuyu9)!yZ~X zo35D6Cwb8`shRXCCR;xlR`n`cs4aie!SSM`0)x3ykwM*k zK~w^4x2u#=jEEi`3Q9AU!wE)Zpn#)0!*~)(T^SEjIJveav(d1$RaSMC0|}<)?}nSG zRC2xEBN_YAsuKyl_3yDt%W^F`J-TyeGrcfboC_0Ta=KcW_?~RLb>xbqIVI6`%iWz; zM8Kq9QzwO8w!TntqcB;gNuV$gd+N|(4?6A9GEzYs z5f4(*N5}&ObeYA~I28r;?pKUj4N6}iloE=ok%1|X()Ahdwir?xf6QJfY7owe>pPj)Me*}c^%W-pP6`dnX1&6 z`b#*_P0PeM+1FR)t)Rnr22f!@UFBW!TxgjV)u0%_C~gIbb_D3aPhZ~Wmex0)Lj`VoZKjoW)dUoKY6*| z0|V)|XyjiKgZ}s5(SN?te*muif87vD_(wYOiOjOKNI4L*aK||2$~;s25HS#iY6r=)WW8a^dkd0Y|pPc1-9jmy&wqoCbL84`C94At6$lm_o!8m*did^?o$m?ozIp{RmZ*M%YMX_i$KYkz_Q)QK?Fdm)REqf*f=@>C-SnW{Lb;yYfk&2nAC~b}&B@@^fY7g;n(FVh_hy zW}ifIO9T7nSBHBQP5%-&GF8@A-!%wJAjDn{gAg=lV6IJv!|-QEXT+O>3yoZNCSD3V zG$B?5Xl20xQT?c%cCh?mParFHBsMGB=_5hl#!$W@JHM-vKkiwYqr8kZJ06n%w|-bS zE?p&12hR2B+YB$0GQd;40fJd6#37-qd1}xc1mNCeC%PDxb zlK=X|WE*qn2fROb4{oXtJZSyjOFleI3i8RBZ?2u?EEL1W-~L%7<`H6Vp0;cz5vv`7jlTXf-7XGwp}3|Xl6tNaII3GC z9y1w*@jFLl2iFA!<5AQ~e@S|uK4WL9<$R^??V^aM?Bgy=#|wl$D2P$o;06>{f)P+X z91};NrzVV+)b}k2#rYLF0X0-A+eRul=opDju)g0+vd79B%i!Y}*&a^L$_|C&jQN^j z9q#4<(4)3qNst^+ZYpyVF2hP;DN|OMxM9w(+)%kFQRcYVI zO-frej9x6a%-D%Xuwedcw9#3VSVkOjNF!BYRoY1KD3wFJ%?ML*3QwcarMK)@v`o%s z$w=NLrO>og`nRJpZZ(%~*hNJU#Y~k;_Ci3~gc=4UQO!Ydje^?=W^DgCKyO;Zz4LgQ zKtm($MdY;UZ((U_g5*pMY+dYGyyT1ERkaj`U#S-2yyJ47wMonCpV+2rI8zPNHDfo& zc59dFz*2#^A-R?P6Np}jhDLi4&vP%$NW#8J>=CLj1mlf$XzmQezH*F1jNOiPgXl2j zzD07AKLT*h$CA*OsOba2etPLU%|p?=XhplXo?vOu@q0{QBo++)@6U?YKv_)GFK(^Y zm&uFBbrQyzJm;c49O00PIt;|{&ei%VSS%Y3m3#~L#(3%Gso^a4#9AaB$w@vnAvdr6 z%!2#)YS0HFt%o)q6~BelT;?%oUjX%9qQCn#-~+TM(a^s%Y>&aBkL(UY{+?a9@&Q+a;t%c_6u^6_r@>MEAN9ir5q=Yo|R8z4lKYd1sv^LyTozFn$KqaJ>? zoH&+`AX>E03Gv=71+NZK2>!-NasKeCfMp;@5rZ z*m<}q2!$AgKUwWRXTVHs!E>`FcMT|fzJo30W551|6RoE#Q0WPD$fdA>IRD-C=ae&$=Fuzc6q1CNF>b3z_c<9!;))OViz@ zP58XOt`WOQS)r@tD0IiEIo4Umc(5f%J1p{y4F(1&3AzeAP%V)e#}>2%8W9~x^l}S4 zUOc9^;@m{eUDGL={35TN0+kQbN$X~)P>~L?3FD>s;=PIq9f{Xsl)b7D@8JW{!WVi=s?aqGVKrSJB zO-V&R>_|3@u=MEV1AF%!V*;mZS=ZK9u5OVbETOE$9JhOs!YRxgwRS9XMQ0TArkAi< zu1EC{6!O{djvwxWk_cF`2JgB zE{oo?Cyjy5@Et}<6+>vsYWY3T7S-EcO?8lrm&3!318GR}f~VZMy+(GQ#X9yLEXnnX z7)UaEJSIHQtj5?O(ZJQ{0W{^JrD=EqH_h`gxh^HS!~)?S)s<7ox3eeb7lS!XiKNiWDj5!S1ZVr8m*Vm(LX=PFO>N%y7l+73j-eS1>v0g}5&G zp?qu*PR0C>)@9!mP#acrxNj`*gh}21yrvqyhpQQK)U6|hk1wt3`@h^0-$GQCE z^f#SJiU zb@27$QZ^SVuNSI7qoRcwiH6H(ax|Xx!@g__4i%NN5wu0;mM`CSTZjJw96htSu%C7? z#pPQ9o4xEOJ#DT#KRu9mzu!GH0jb{vhP$nkD}v`n1`tnnNls#^_AN-c~PD;MVeGMBhLT0Ce2O2nwYOlg39xtI24v>pzQ zanl2Vr$77%weA<>>iVZQ&*K9_hfmv=tXiu#PVzNA;M@2}l&vaQsh84GX_+hrIfZC= z0Se*ilv-%zoXRHyvAQW9nOI2C$%DlFH1%zP-4r8bEfHjB3;8{WH`gOYt zg+fX)HIleuMKewYtjg+cSVRUIxAD9xCn+MT zs`DA7)Wx;B`ycL8Q&dR8+8mfhK;a^Rw9 zh9tC~qa>%5T{^8THrj^VEl5Do4j4h@nkrBG6+k8CDD~KB=57m@BL-)vXGkKIuVO9v z7t_L5rpY^0y=uu5iNw0v&Ca-zWk>v;fLJ=+SaV&V#C-o^}8 zp&Xp$v?~ccnfR=&5Df)32^d6QJLg*iuF#s|0M4zJF@Hza1p`q|f}~K)q;HC*I1_9t zQ&1jr9-kdUi8)DGxiwdqU|rPxYWDQPWY&SI&Rxkhxobp~C=Y*`d?HD4JW?WjU7dBPeuIE`ABLq95b#lfKS52IB^6KoHmm60$R}TESplQt59#mboJj+Na!P)V{ic@$yQ-&Z za^JU0T+n0Lf2VdusoNr0?g~1DMsY)zdY-63yH!Ii#aWe|;0TO>L7#YlaDrH}xvYXn zh-NYa>O>f_NTTBG=|k0qWH+X?d5@+INsQ}WcI_3z1Z4-%Gj#_{P$0A~cAye`?j0cW z8)hd(V}7rattLUSMvgZ4g96P7n` z^{55A&&29;-P992{yhkGWa3v_Z6iB4a&~NmL)IpC&dsSwe$9jS(4RVJGt=Y!b-O~1 zSCl@wlaba_cA*yt(QvulMcLUuK z>(ys_!{vqKy{%%~d#4ibQ5$yKn6|4Ky0_ngH>x-}h3pHzRt;iqs}KzajS!i!Pqs8c zCP%xI*d=F=6za_0g`{ZO^mAwRk0iwkzKB7D)SaLR0h|ovGF2w9C9g8;f#EtDN*vBP9yl;n=;B2a7#E8(%Bw()z(M$_pu zQ+9uFnlJ!5&$kk^S_+kJ>r9y8MFPpSf9;o8v;ZxsMA!p>eaAIwt5xNiQ|2_ydGkbi zkggG;Xp&I7C8R{>ten^j@MsN#V5JPs1Ezc!74->Nh0a}U){OK@j=OIoY}C7IYYd8-V9 zQ6s?v=Y7(?Y$7=P#Wwub-*0DLqli?I%kT-D^jqK?c2~HEx<2(poRWAUoC}!~6$1=I z*M(IfPmdID8i+5l@=1(+`?i`G_ew=1Y!gF?tFbdgtW2etKLOFoNozkH(i!Qa7(h^| zF`9!VeqQQwM+yO6J`;oWUWq@9l6hP~FiG8-{Pj*T`XI3~s@FfjW2Tl(llpa901$&y`F}K1uZuHEo;=mr+_8d(o z2Be#yWHEN@euC$=VUSB+3A}khJdF$)0r#<5(f3n`kx>ZT8ifaKyX*OhffeHH1?6OM z*-19$j5tMNYQoB)>cGpz@11>J%q4KW`GLNj?uB>LcNg$0G@}XN#Tqf2F5@jv<`|~p zqB^l!%v!g{R_+0GX5z0>3Q~O``%T$NFc==dsPsTj-;{b$XUS0TGoJs2BUA*H;4S?w z|Nigt|F@9hf7QLSo}JPEK#CPgYgTjrdCSChx0yJeRdbXipF(OwV)ZvghYba)5NZxS zm=L8k_7Lb?f8`=vpv(@m%gzsCs9^E$D5Jn+sf}1lep*zz&5V?~qi_@B?-$Vd1ti(rCi*I0}c}slKv@H_+g?#yarVzpYZN zIk21Bz9Z#WOF`JG&TC&C%a*3*`)GJx9I!U8+!#J4}@5rm8*jK%Xg2VLjP-a;H zFydWO;nxOZ&|{yOW;ta$ZU^6*4vFP)idD6M*M0+9buB#hK4z%YTGBdSva?Pvxim2` zF-?QVGuRQ2-1eYzd1Y%}w^`t1S7|{{8=Es#ApC0<;pc$|NJ)IU%WVK+4gnTWA7-t1 z0K{DCESXb}!y_tzrycr^%%|G4T4)`$BC8+qm|n1lS?CO=`V`1T#ykY#5g5$dc$lGt zqGHyw-*Av%C;33nEiU(rU?w^3F46!dEz#cHd3IF<(XCq)>JG?Bi)4v26MQr1A-g5RqhFoPy%^TD3sa|D^9aS>>_2-X2i#? ztVp@ZkyMB;Uo#9s!R!@G#CCaFVaxx*8YYu$kGFk4g3|9t!1nKqOaDBAe;w!(6#w)0 z?{&F2BgctT1=Z;TvjOGL_!}Vlt=kaLA7#W`mv1h%hUg983!wA*K@_r6_cd6o z6LHiCE6qwlt2H&|Ica~%b9C?Z@$dreBNR_!NKcfL)%8kGr7!IVq|^&6PKYK%EhcKu z6+uR*%EOw=rF6Q42Mx|a> z$2XrM*NV2x9ci6|X^eh1UAbJ9Ky!#*Q5w7)#o#%}d!#-^k8To=n8{UU*LmFsS-wRj zi6-p76V6g?If3S&Bj~GW&QI_WtyPY0@u3hjKtqf9`8S!wn{@P&Tc8uu8cf)YmrX7+ zrC+O3V{9}JG6ihA&^2Q7@)Kq)j(Y_oTzsoBUYQDG!}`Ame`bbcr>J-6E%gaBPEDCU zflX#1-)Ih^HJV*lew*N_SdG-4!b2}G8%U&9_V0~Qt?ZS z@H3L&5ybV8X}A@KQADl93H`}0qkNm!jGHkCJUM%r8`mP1nV?Oo%^l;yDnU6IJtbuY z`X2Sf8|r00mB_f)Q0;S{FqS1Yq?otd-BVbw`#@SDd5}n5X4lqdDi1*vtVv8-Zi10q zexCj0eyngrp`UxjEOrdzUt`?%jRlj7zSU-V-%R?y+_w7P7f1ge%t1ozmN+&)%3xQW zT3u@)))(_a<6`lTJd`DIYw>(pkb=PMKvCNEG~zza+LVNqkY^}QoGMVdS0K;gS*A3f z;6Ua!^sSV-try(M^pB6D9dsX}c>$Da#NHucp9vr(fg4pbBR*uPhYq+N>q1X4RSOCl znIQj4=A+y+8{?LQ$3L@(!Yy~~Cu4Sx72*%@dW>eP%Br7=uaynV6Mqa-49A9) z|L&5r=4K5SClwc`!2J|>(#n$4y1>lmR~2Om8q6HkcpK>d(Fk!T^NO?hM4Fc+(5J{` z&K|vrBz;;zWlNO%=a~JkMxMiZa%wYz#G901lw#+2SUaMMHrebb&|1L8tKoGJK*QhJ zU9|WkDy^-4F6U&VYSc3ScHDk@kV^0801#I|-pSK%az5=DwI}gMm)@s2O+-ESTk?QY z;y9gyucaXO(Cc+cd{B>2)euMHFT71$a6DssWU>>oLw4E-7>FC-YgZH1QAbRwmdahD zO4KAeuA^0q&yWS|zLTx%(P4VOqZv-^BO`0OFAXdBNt9>LAXmPALi3b|gt{b?e-$z0 z4n7H$eg6y_zs(c>*4FT!kN*$H`43~1p!g;IZ8-mYbUPTejaLW#BZnAPFES?ApM{TQ zE*TC%O8)apqcX|PrNjIZE-z{q`I(LwIE0kf=PLjExEX>)oIu><<@lt>-Ng9i$Lrk( znGXl|i4dP;Mt^-IbEp7K0e#*c7By@gCo@VQIW$93ujLL`)lMbA9R?C_5u~7^KopaAMj#6&>n-SOWlup_@{4 zcJ?w_!9JKPM=&Bd#IQ37F*x39y!azm$;~IRlkm>bHdABcNwW-TdDKD$pkD{j6A8d* z{vP~|<}bj_Oz#83K$ieRtsA4a@4a5cRjJ}A01{PgxXn3;fx)5ElMEPwDX_mW9)9oB z*;scve~v#HHqUj3KdC$tdV3&0)Whkp-=hKKz{SzD7g0@N!wyv;ZAime7AjB7&)!)5 zp_iVblaf)%agwJqOG2e7WTCM1&khq`{b>fN4n8hOJbvO?Y;60>LIwagLXWC@@0RSR zo%lPo1cUU=g$ahJ8D=;`v~ORUSl(1-&a@yTAC5Y8E892@{P@MM=GXUGpBSXSbSs!N z;L~0D_s7{+^F6c!WW+^yz5~o7eWtsOE}8{hKaFlHgnyBeUJ8Zz2$k7Lrh?NuMU|No zVvsq@57)8zin;&ckR1;*Z%(xH2lBw z`x%N;|H1En8au588bPDxP^$kfpO!bIzz>K=5Jiq9Rg(NGde0g!rKagLa+&yC)jg7y zq}~2IH)N*FJC31qrIH-2;%3^F?=bDD^U2Y;%ftN(v71oY;od+vh!!2z^}GHR$43rg z0In@ki}TglIsMU^O1(SiLK#oiuyw zB>-@z?&uW`ILoPupw0_cs?C|2YoX&87~us+ny%eo{A!3M<-7O7mHUBCgA~{yR!Dc^ zb= z8}s4Ly!GdxEQj7HHr<}iu@%Lu+-bV>EZ6MnB~{v7U59;q<9$h}&0WT;SKRpf2IId ztAjig0@{@!ab z{yVt$e@uJ{3R~8*vfrL03KVF2pS5`oR75rm?1c`@a8e{G$zfx^mA*~d>1x`8#dRm) zFESmEnSSsupfB>h7MipTeE!t>BayDVjH~pu&(FI%bRUpZ*H615?2(_6vNmYwbc^KX4HqSi!&mY9$w zpf%C6vy@O30&3N5#0s_!jDk|6qjb-7wE3YT3DA7q3D`Q&Y*y>XbgE7=g#rPx1hnf8 zTWd{IC!Iysq*vZup5VGrO)UM<3)6raR`rOwk(!ikf3XPp!n|gz0hS*P=VDXAyMW(s zL??-`&IusEuOMrz>m(A1W5Q~>9xJwCExAcMkOBD` zD5BJSadd{0u}%z4r!9qA`FW4;Ka_Qk>FcHxiucGw4L9qhtoge|ag8jbr`7LHSbVQz z6|xUo*^LV1SLxS>?D`m=g{8IC&1YF$e}VRGD#ZOc_15QW%J@FbEj8tE-nGxo4?X02 z@|q#k*G4xMW>q84Xc09pRj@>Hz8t^fMm3n&G;Al6KU*;=W`7Q{$^|=bnZiJ7?(s)@ zB`vW>#zJ{}!8=*|?p(~fcXSanO^j8+q7V!q16*ic!HLRdz0TzNI6}m+=OKd2b8KX< zAcDTj*%~vQlcO+%@H01gjv-1zZaOXVoM*t-+KXTR#NoTf-#{dQAm?GqK6q8Ta zu3xW?t=NE$EfYa#=0HofLn5~c#m-U#Ct_r6~X-pg6k*F zYIP7De52BBwcAnK?O(j?YEs1;q60!-!hTuKzw3T;XcA_w5HvU;tO~}byLA^cggu8i z-IP@pxFjTy&ie28m}j66dm@g78xK7aG{QSR^bAcY+W*xWu;G~I08sf(GK4>K-cbfJ z-%v9DGR77He<291M~=fg>>9&NFQlboP)pC6fT;{>_!lM`A&&HWIMd)Y6e@IL;nvRdBE*Tn({&3{-XJ9helJa{G51Ck}-_Y=5C|fEo z)7fZlsHxN&SY&ZLTdYuBBZnwIh0#VTzmyK>U0|r&SXb&GP0m)1dGV8z(^x6s5yQ-z zEyniK${#U@Y7p@Yxx}E+jA?1@{=|e6UM;iyai=0=aItVvqieogZUq@sio2#9NLW~L z{w@^H!HEGU;>;T0lu{Ad20Hr6u;?-9YHKvkjEc)}wsb4Y-ArRK8`24uBT8N)8m%Ee zYJX21)|e{peL26}VUUKYQ3L@NSe8rEbN#AIo$tjJm-$B|IJU?mu(h$Sq`XNY0@NhY z0?WeMtPwP)sUdk}dWA4qBUV^x>P|is-kPgVe)*WV>dKDL>gOq1 zUYw(nU|N#dw>97A_(c3?VA_zDfF{^A1eE#8Bucd^ON(sv-{tc@&i)Y)3V~o7U~+AA zOwnXB5`WN^z$z<9^@(?LY%7?y5X_C(j1ip-Ug^f7Tt6suI3&a=&~#EJegG4r2^tKz zJoEXCVOc1QdOSNHp2d;t&smxL%CfK@mSl)Ky}`!6kCsi#7s5&G2Q!sM9S6o)&mdx% zz|2M~pav2;Th=DTN5yB@6HFAO!pl-y+tEJsh}(? z!tIyg01O*w@mWxsFhHMi7%Gqz!v(Osc5WxK+^1PGfsozw)FE}VIxk9GexmAohPNAF*SAjxG3Al#(xQoYXdI}TR zoCHAFS6+LDqsP8L1SZH{RxJjFK_=vy4nNH^?M!OsQWe^qC~$c1r&y`H9n5;D z2F$t-Htc%2@K(>opJHE{NytI2<_J<6Kz*p$wtKUTEH}zITx?H0L%!5%i@!rLphSBrkFs>jscP6?HVQovX8!~b~ZY|0h%&souT7e5nD@OxuSgC zVW*eo0B|1POwg7;6fJSUC`g+`1%XQvwpRc*&|AtV*h!#5nQM(@m!K)-Qop!Rt3F`a z9HUO zF3w{uI_==EpjFQWV4boF^A?wc@@@U+KrKPjn6sK{OLu-~1UloSqt-aHYo*^@kQy2+ zH(9*-mFz?YV4cL7EW)9hsdmG{5jaYXLvm*&3PZ4y?8z`$9z6`q9fgsJm@*W$-QSzu zut}57hroSbTd=&RJpuy#?K?A6!-;_MowpK8eb~5T-^eye%3O-T^ktSMbd%PT0j-B?#yAKr37u%gB z*2)WJMw6Y)6BvY$JjD`(06ci7u;u$hv}gN5oS&Q^*y$J6L)0#BD<>XL|;pZgtZaxp3~$0zxA(;6Qr_AP$?8l@S)C^Hoaz#rQFK^lA}3&)Gr}Fsca? zK>9BkVcl;c*E2P9UMppEIB&38dL9R?Xg9N{Nl~4*w!qsZJElz}Xc9gz#}cwnP4u{+ z6VNTEx*>u67?3bn{sWk*P`1_$YfsB+)Ax0+jt|)0p&VS?N0k8IAp2KH_#eY3I#{Hw zB$vObUDtXyZX)*wVh*@BefnUej#jv@%uiA=>ngX0kQXaz>8(WM)fX~v__@I}7|!Il z@J%r#I!JqqFwGd4JPhmDmL>1Bh}nn_BE;hgKUesNOf9zQhiuhn%4B}O8jnxEwJiQFDaiiuXw2sb?*8a}Lr;_#7+IPfIjhVDhazSpbQZECL+4)p8lO;)!y>Rt=0X*;O# zX{s(p-*d{#{Y3gVhL;A{4a(Z5sIfpk;WMCqdFA&Mb7mp;YMXhBF@p`}$ShAug+bo`;<9fm!~F z-;1yCj$GQ^mzucrfuatilXrYLr)`izjn_m(f~);txN?D7d?Kg4wDuPXilVyeVwjzf z=4Kewf=u}X_H*viVfPWZW?Sqa3G#h3|;b!Q7>BRc7-Wox0}&>}Lqo=0v;T_i~% zqB&h;14|~nK{W0N=$obGP@O%(c8SraYS^qiu%Q`B zBHdA!`Vk7#Bz*@_3eE#bizLzjBV;F0vfSA~+7@8+F{$7Y?fwI~Pp_X`2ORgqW6g@2 z{cQV!niSsMEVr1IaeRAj8~|*4yW~X5$6o`crw4uTHhgPs^qAk?9UPu;xy5wh2^jZ; z)@27Q=QKa?8w7_C0|u`@k=%b9Ce$D7x42CdLsckF2<$wLuV2kpik8PXex2^Co$n2o z)l#H*;#>?yrPw0x6LI@x(X$nezCBa0Obi%|I5ZV|4bJSPtNHjDkS|3S?fiv(i_(n* zFbve0g!B0!MMmakRsgg_if8nwImb=kk%|s+08xGQ)J?vpkdaya3UD|RJK+LQ72|g> zc4LnwInx!2pN-5Yvp7rvRF#B=(ZO8gyVB^0Dh#ZdHA2BjjppfV<=2Nm#w_t{%6O$W z`-?7N?LwL0DWgK0Y7L#ChSHfa{=DOpJpl8L@V70cd%ei)n%SQO;Z+Xw#li#%LUfbs z&hP%UzN(qM3cw#bWQS6_B@>1^ea-AqNA12xoiQeb_Zdtf>yHljqeIHqlyC^gzH)h1 zstXTFEb0r=l9;><<$a}YWlscH7VW_xeKVZ#*#v#HiuUOs7PPj8ml4#!BiGEK)kDpO zX=2mU0ZuIDDnhfV7v_Rs)0R#ff6I6_|MrzV(R$3Nt#S7D?GQy6?a^WRvA@r2~?7f~s99*9;fuqJ(843U`hRl2O|sk>J@WMsR2O zwyZt$@J)DnSUNkF@B3MPNz|<@`72{M*S5d<1Vkg+G=q~u{8OP84Yh6VCE5pNC*#m> z*jzHy5Tc82sBVw+6W7DoR5@LXZ|+>;)Q%czg%8pyMyeE2-)R^oHg~SrO~#I8MxNc> z6pWT&F&H1mX7#2@mBY>#rRoFKszT z(gvV#j3x|7sF|Dt0*CgsJTdH1R!>inYZWp*2RDbjjQCP98L_ds!$x&{t85NRYk4ii ztJ3HyC8h2A2&`kq^Cfci>N*r&btHg_|v6=s|v=(-MQ zK4kjqoI^~y`j9poC2r{Izdlehm8!AcMP^+SwDUce1Zon(%YvxK)x|rXsJRlO?-K91 zMsmHgI&PmqT_W}C0mdA_6L!EEjgJzidRvTN;vQRJ-uBl#{dEeN?24PRwx)7c5kF^ut=M0)e@zr?z_vpYf=%;;@UYF9>9-->Qf2FW*# z5*#VFB$$-k(zphh4sAElMiLbp`$+SKm*{l6qX;Q8GZ7b|J>OhC!yg$}8dt$dx3E8b z$FlaM*K@6mSsYCoe#*QjLEB3|_Vs4GbZI#!>Ya}dzh%uMn}sw0gFQQ{+V+e|_`q)M3nK27)nAqQ-viJoPHUKdr9HN`v0 z+tZo0ORLuv_d)x}gO|~s(H!12RM(aMfqLG>KSH#kGxC{sUUj>FUC(6;ds1cOjeDYu zOrd>q@bNFq5?0s&@5nbF3-rw{{V&YYf3o_9|K-X4k861UwZ&C2bH+A7^%7nizU>b? zC2@*VlrqprJiv$rx{+^+Op9i3RM;IHq@a;34=Gn%B+rXMZi=UsHC@TEFk4{*fs96p z)wNUY?AhVkdLGQmPESuh@-!iqSZrnxIT~Mon)J+i+B~9VdL8QE`^4=2@lNaKluUVx z_^i7~5E4dN4&gVMi%;7ast@WIY21Q`+^iTC*Gx@IMVYB`BLFHzPh{Fpc6LKZTk@>P zquo2E*Pgq(0MX>h>4)YaJYbIK&V?-W}JfL@&R0I2)TOA!Teg zNa4DBO&)`Nn0$Inb|d8ea|)qqOLYVbQIBRC4T4E<5#Nzc2 z57|Bq7mYsW8y?uLA$XMj%OeK+1|DAKcLYB98-vDP<3*+SKYcPcOkm&}H|!{9l*9%L zbiYJYJ^)Cql-&wPwABGD>Ai7SUXe15m zIr^wNEU$9)D6@atm z(w(1~GuLpHi?JGgIBj`Ovy;j4M`XjrCNs?JsGh1zKsZ{8 z@%G?i>LaU7#uSQLpypocm*onI)$8zFgVWc7_8PVuuw>u`j-<@R$Of}T`glJ!@v*N^ zc(T~+N+M!ZczPSXN&?Ww(<@B=+*jZ+KmcpB8* zDY_1bZ3fwTw|urH{LLWB;DCGzz$jD|VX#Af@HC%BktA8F7VJSy&!5iTt};#U^e0_q zh6j7KCTInKqriZ1`BiF3iq2LWk;gyt0ORIFc4Mi3Bx`7WEuFq{u^C49-SYVjnv!_40m1>7x*+<8~Xkq?056 z!RBfE@osP%SxzOw>cLAQ$bioAOC0V!OzIXIc};)8HjfPtc~8tnah$PtoAz`4k)7$FDUc2O@D)g_uAo&nXMymK$##V?gYUPt^l zj{6NFDL(l-Rh(xkAHP%bBa=($r%3Y~jB!eQ1Smuq2iuQ|>n%Y=p(26SE5gFu11*Q< zaPN5G^d;Iovf`VY&Gh58z~%JpGzaeUz6QoBL^J%+U4|30w7Q&g9i}}@l61eKEfCgo zST6qMxF_Eaj7;0OC)TSU{4_m}%FOa6B{AxS$QIcmmG~IVjjf;7Uk!HBtHfm{%LsLb zu8~5VQFyOZk&!VY(wxL__haJ;>Bj?g&n`+i&=X{unJmv&0whCitWfGlOr6+Tc-lMZ z(ZRXqC-=O+GAvTXKViA9vdwu{aifhk$tYh~-9BScg!Yr*M2zw&9`pHMxHGh`dUH-1;~^6lF@ep;X9PjQ!rqmXNWJ?#P-qb%*TB%xe&3 zX*5V>xuW7)$3!Yc$y>cwBqd8+p+u>WS7p7~O80ipG{(a*#=NJ`^Ld6k-`|;Y&htFy zIi2(Sm)4eD=o+CGo~M3%qF|O9P0+ahmc%EklI?NgX05W3+OdS`_Rd#wg-}hd1&txU5wXy zy`x)05?WVZvELw`XWetIAg6$|(^4ntaE;=f$Wcpwbxm7?bLDnPs-1!bRoMcy!EeOh zpIv8ewDzcIU}mv1NxV!&(Wf7~_kqGAk=2=j&O5FA)z2!APCcDQPnIaiqMkVT4fUyX z))R|WvOJyzcU6d=z0q8JDt42*`js4g+_t{YP7lVguX+vhEejJ3TAIo*Z6jizHm#S- zZT_}-STQAa-0Gn8+RmR7V}{Ns1@jJ{^Sb!9&RSXXP;^ep)r6;&PW++~XYXC9a=zSF z?sp(JQo&MROb~b1Y*Xw4!P)>PHT>Z<)*U=Ax_75^OUw97pNudbxS1XPtNrIg zQ5YB77E@i7$2Ia}(^JcCi@OX`9a|m}PY%-th2m~y+)eCl>fTVjCP^lDOBLyhg1DZ+ z)~G{&OkDc$!;t~`gq(wz@qW3lh9B^ic$>-h#nV!H8d#l+>C(M%g}u2g=I#&W|L!VD zqHYoQkBW;`r|fW02u{7X!X;}T7X4iAaWzkeOh}7&o!F1qt4#$1|BDF;(2VlgEqJ$F zy8Ba-y(%fs`MzpvyXlQLEhS^ed$7Va2hO%?$-D>^*f$b)2Hx;}Ao$UqFt7l26<7eP z!{!C7PVrq>=794Zqmc z%LKkzIBZq@%Ja8EkH}?>c5ILG(EAMS*JHu?#9_7TsELw)8LZzN>f2Y6YN{AJC?34> zh42sPa1%2JpCeS9&E1URm+Pb}B>A1M`R{+O+2~}c(@^1Rf&J9p(4QqHl;E^4w5;I5 zM{?(A^eg*6DY_kI*-9!?If^HaNBfuh*u==X1_a?8$EQ3z!&;v2iJ``O7mZh%G)(O8 ze<4wX?N94(Ozf9`j+=TZpCbH>KVjWyLUe*SCiYO=rFZ4}S~Tq|ln75Jz7$AcKl$=hub=-0RM1s(0WMmE`(OPtAj>7_2I5&76hu2KPIA0y;9{+8yKa;9-m??hIE5t`5DrZ8DzRsQ+{p1jk-VFL9U z2NK_oIeqvyze>1K%b|V?-t;Wv`nY~?-t;tMC4ozyk8CR(hoZTno3!*8ZTc15`?MFf zDI892&g&3lshOEv4E@w-*_%)8C_<&HhV`0D5lN$WT4Q^UWHNSAE+RZe(o z%bqR^hp1IsDr47e^AajFtlppT)2F6yPcrWO9{Kw{o=P6y^HOW$Wqd_)_fwzn`ikZl zOGVc0+S(*=xZ_KbL0Nr`Sx$$CWEbw$52udl1f=X6CZEcFMA*nl>`0gn4&tc5^`!!)tGw<}^Q>P7E}$ zialDUofH*XcB3r9@tA@lnS}dA(@nK_xuw0b;FPUnNGD0;MIySCw=cSzB#=3>F37V-nni3UNB)-;;Gkk;3l9fh6FIjSZU zk=Eo2a`6i7@i*4>ym5`R?i-uZFv6+iX*Gi^I}ZU1OrLAX8aGiT@`*YnjeF>}$U}ORP`+EY5`eqVC_&4yG z;Tp>+2QbZ?lt1GB+D}q14W3dWP8lWnN zf(nlT6+XW&(zme{FbyDpP^NakA<~TK=Y}H^eS%2rt0v8Lr)B}@B!cTvC=9FM;7q4@ zf*;vb4HG>RFpY5?vFCp27VEnVIGx~-na6biU4{+UoYe=}^R#_My6wT$5d&r*=kpAA zu;=-c0|~yqi(N8&*H;aNfhyey+HHQ7J_qae*_CgG2V8j=Tq936S0DC8r3BXBql3Gz z0pLo_`|4Q+oY3rPBNaLmL{QM};9dke>ujP^j@z-N;fNlKb|edn>)YaafDaJ>GWKP$ z5}l&#$QFhN!CMT;WH&z-5E)kvM|36lV!^#3z{@2FF>HsgUO4PMqO#U$X%+U>K!xJ@ zBFs|+woG_9HZQs_Tw*vnCPGhlXG@>y|6pJT$I67!aP&b0o$AF2JwFy9OoapQAk>k7 z**+$_5L;5fKof<;NBX%_;vP@eyD=Z0(QW)5AF7 zp|=tk3p?5)*e~Inuydz-U?%Kuj4%zToS5I|lolPT!B)ZuRVkVa>f*-2aPeV3R79xh zB)3A$>X~szg#}>uNkpLPG#3IKyeMHM*pUuV5=-Jji7S6PSQ9oCLo{oXxzOZfF$PP) zrYwlmSQ-~n94uO3CD{K0QTmj@g%Yzn7_xQ4fTduU0Yqvln`e_`CdXH5iQ5qRr1 zBC;}%YZ2!4I>*=sR)O~jBPx6sxmIEBnq)s-fHz_y0z8-gPl2Us4BiBXNR5CIF!YR@ zb9B305SilU*@4|+ x6JBtc8JSt5M0pkooaq!^FqtuD_KdXXTo>Mw54>`rP&>h&58!3a6l6r9{sG7g--!SK literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a4b4429 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..2fe81a7 --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9109989 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,103 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega From 75f656fd07ced7e104e3a49cf8c066f352794f7e Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 3 Jun 2020 17:59:04 -0400 Subject: [PATCH 442/451] revert changes to build.gradle --- build.gradle | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/build.gradle b/build.gradle index afe78ac..64f87d2 100644 --- a/build.gradle +++ b/build.gradle @@ -40,10 +40,10 @@ sourceCompatibility = '1.7' configurations.all { } -//java { - //withSourcesJar() - //withJavadocJar() -//} +java { + withSourcesJar() + withJavadocJar() +} publishing { publications { From b6ed0d41781df561eaf432f85dba51000ca25f49 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 3 Jun 2020 19:13:24 -0400 Subject: [PATCH 443/451] fix failing test case in Java1.7 --- src/test/java/org/json/junit/JSONObjectTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 75b23a1..a931a8d 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -946,7 +946,7 @@ public class JSONObjectTest { assertTrue( "Integer.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Integer( Integer.MAX_VALUE ).toString() ) instanceof Integer ); assertTrue( "Large integers should be a Long!", - JSONObject.stringToValue( new Long( Long.sum( Integer.MAX_VALUE, 1 ) ).toString() ) instanceof Long ); + JSONObject.stringToValue( Long.valueOf(((long)Integer.MAX_VALUE) + 1 ) .toString() ) instanceof Long ); assertTrue( "Long.MAX_VALUE should still be an Integer!", JSONObject.stringToValue( new Long( Long.MAX_VALUE ).toString() ) instanceof Long ); From cf00d2f26551da2db41800ad825f253475c22432 Mon Sep 17 00:00:00 2001 From: stleary Date: Wed, 3 Jun 2020 21:12:19 -0500 Subject: [PATCH 444/451] initial commit --- .../java/org/json/junit/JSONObjectTest.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index a931a8d..5cfc8de 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -2978,9 +2978,9 @@ public class JSONObjectTest { @Test public void testSingletonBean() { final JSONObject jo = new JSONObject(Singleton.getInstance()); - assertEquals(jo.keySet().toString(), 1, jo.length()); - assertEquals(0, jo.get("someInt")); - assertEquals(null, jo.opt("someString")); +// assertEquals(jo.keySet().toString(), 1, jo.length()); +// assertEquals(0, jo.get("someInt")); +// assertEquals(null, jo.opt("someString")); // Update the singleton values Singleton.getInstance().setSomeInt(42); @@ -2991,8 +2991,8 @@ public class JSONObjectTest { assertEquals("Something", jo2.get("someString")); // ensure our original jo hasn't changed. - assertEquals(0, jo.get("someInt")); - assertEquals(null, jo.opt("someString")); +// assertEquals(0, jo.get("someInt")); +// assertEquals(null, jo.opt("someString")); } /** @@ -3002,9 +3002,9 @@ public class JSONObjectTest { @Test public void testSingletonEnumBean() { final JSONObject jo = new JSONObject(SingletonEnum.getInstance()); - assertEquals(jo.keySet().toString(), 1, jo.length()); - assertEquals(0, jo.get("someInt")); - assertEquals(null, jo.opt("someString")); +// assertEquals(jo.keySet().toString(), 1, jo.length()); +// assertEquals(0, jo.get("someInt")); +// assertEquals(null, jo.opt("someString")); // Update the singleton values SingletonEnum.getInstance().setSomeInt(42); @@ -3015,8 +3015,8 @@ public class JSONObjectTest { assertEquals("Something", jo2.get("someString")); // ensure our original jo hasn't changed. - assertEquals(0, jo.get("someInt")); - assertEquals(null, jo.opt("someString")); +// assertEquals(0, jo.get("someInt")); +// assertEquals(null, jo.opt("someString")); } /** From f4261add919fcec3a72635a5a26c9fe3b558bf2a Mon Sep 17 00:00:00 2001 From: viveksacademia4git <45398326+viveksacademia4git@users.noreply.github.com> Date: Wed, 3 Jun 2020 11:58:28 +0200 Subject: [PATCH 445/451] Create pipeline.yml --- .github/workflows/pipeline.yml | 53 ++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 .github/workflows/pipeline.yml diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml new file mode 100644 index 0000000..28df9f3 --- /dev/null +++ b/.github/workflows/pipeline.yml @@ -0,0 +1,53 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: Java CI with Maven + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + compile: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Compile with Maven + run: mvn compile + - name: Assemble with Gradle + run: sh ./gradlew assemble + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Test with Maven + run: mvn test + - name: Gradle Check, Gradle Test is inclusive + run: sh ./gradlew assemble check + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Build with Maven + run: mvn -B package --file pom.xml + - name: Build with Gradle + run: sh ./gradlew build + #- name: Publish to GitHub Packages Apache Maven + # run: mvn deploy -s $GITHUB_WORKSPACE/settings.xml + # env: + # GITHUB_TOKEN: ${{ github.token }} + From 96bf7885154029254bc4361a8cdc4e63172306cb Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 3 Jun 2020 18:29:29 -0400 Subject: [PATCH 446/451] update pipline to use matrix configuration --- .github/workflows/pipeline.yml | 80 +++++++++++++++++----------------- 1 file changed, 41 insertions(+), 39 deletions(-) diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 28df9f3..715d7d9 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -5,49 +5,51 @@ name: Java CI with Maven on: push: - branches: [ master ] + # branches: [ master ] pull_request: branches: [ master ] jobs: - compile: - runs-on: ubuntu-latest + # old-school build and jar method. No tests run or compiled. + build-1_6: + runs-on: ubuntu-16.04 + strategy: + matrix: + # build for java 1.6, however don't run any tests + java: [ 1.6 ] + name: Java ${{ matrix.java }} steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Compile with Maven - run: mvn compile - - name: Assemble with Gradle - run: sh ./gradlew assemble - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Test with Maven - run: mvn test - - name: Gradle Check, Gradle Test is inclusive - run: sh ./gradlew assemble check + - uses: actions/checkout@v2 + - name: Setup java + uses: actions/setup-java@v1 + with: + java-version: ${{ matrix.java }} + - name: Compile Java ${{ matrix.java }} + run: | + mkdir -p target/classes + javac -d target/classes/ src/main/java/org/json/*.java + - name: Create java ${{ matrix.java }} JAR + run: | + jar cvf target/org.json.jar -C target/classes . + - name: Upload Java ${{ matrix.java }} JAR + uses: actions/upload-artifact@v1 + with: + name: Java ${{ matrix.java }} JAR + path: target/org.json.jar + build: - runs-on: ubuntu-latest + runs-on: ubuntu-16.04 + strategy: + matrix: + # build against supported Java LTS versions: + java: [ 1.7, 8, 11 ] + name: Java ${{ matrix.java }} Compile steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build with Maven - run: mvn -B package --file pom.xml - - name: Build with Gradle - run: sh ./gradlew build - #- name: Publish to GitHub Packages Apache Maven - # run: mvn deploy -s $GITHUB_WORKSPACE/settings.xml - # env: - # GITHUB_TOKEN: ${{ github.token }} - + - uses: actions/checkout@v2 + - name: Setup java + uses: actions/setup-java@v1 + with: + java-version: ${{ matrix.java }} + - run: mvn clean compile -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }} -Dmaven.test.skip=true -Dmaven.site.skip=true -Dmaven.javadoc.skip=true + - run: mvn test -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }} -Dmaven.test.skip=true -Dmaven.site.skip=true -Dmaven.javadoc.skip=true + \ No newline at end of file From c11c006e880f1499a08abea78494d8f9ad613346 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Wed, 3 Jun 2020 19:03:38 -0400 Subject: [PATCH 447/451] fix tests to not depend on HashSet key order --- .github/workflows/pipeline.yml | 27 +++++- .../java/org/json/junit/JSONObjectTest.java | 56 ++++++++----- .../java/org/json/junit/JunitTestSuite.java | 49 ----------- src/test/java/org/json/junit/TestRunner.java | 43 ---------- .../org/json/junit/XMLConfigurationTest.java | 82 ++++++++++--------- src/test/java/org/json/junit/XMLTest.java | 68 +++++++-------- 6 files changed, 131 insertions(+), 194 deletions(-) delete mode 100644 src/test/java/org/json/junit/JunitTestSuite.java delete mode 100644 src/test/java/org/json/junit/TestRunner.java diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 715d7d9..98ee6c1 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -43,13 +43,32 @@ jobs: matrix: # build against supported Java LTS versions: java: [ 1.7, 8, 11 ] - name: Java ${{ matrix.java }} Compile + name: Java ${{ matrix.java }} steps: - uses: actions/checkout@v2 - name: Setup java uses: actions/setup-java@v1 with: java-version: ${{ matrix.java }} - - run: mvn clean compile -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }} -Dmaven.test.skip=true -Dmaven.site.skip=true -Dmaven.javadoc.skip=true - - run: mvn test -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }} -Dmaven.test.skip=true -Dmaven.site.skip=true -Dmaven.javadoc.skip=true - \ No newline at end of file + - name: Compile Java ${{ matrix.java }} + run: mvn clean compile -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }} -Dmaven.test.skip=true -Dmaven.site.skip=true -Dmaven.javadoc.skip=true + - name: Run Tests ${{ matrix.java }} + run: | + mvn test -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }} + - name: Build Test Report ${{ matrix.java }} + if: ${{ always() }} + run: | + mvn surefire-report:report-only -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }} + mvn site -DgenerateReports=false -Dmaven.compiler.source=${{ matrix.java }} -Dmaven.compiler.target=${{ matrix.java }} + - name: Upload Test Results ${{ matrix.java }} + if: ${{ always() }} + uses: actions/upload-artifact@v1 + with: + name: Test Results ${{ matrix.java }} + path: target/surefire-reports/ + - name: Upload Test Report ${{ matrix.java }} + if: ${{ always() }} + uses: actions/upload-artifact@v1 + with: + name: Test Report ${{ matrix.java }} + path: target/site/ \ No newline at end of file diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 5cfc8de..c24d138 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -1856,10 +1856,12 @@ public class JSONObjectTest { " ]\n" + "}"; JSONObject jsonObject = new JSONObject(jsonObject0Str); - assertEquals("toString()",jsonObject0Str, jsonObject.toString()); - assertEquals("toString(0)",jsonObject0Str, jsonObject.toString(0)); - assertEquals("toString(1)",jsonObject1Str, jsonObject.toString(1)); - assertEquals("toString(4)",jsonObject4Str, jsonObject.toString(4)); + // contents are tested in other methods, in this case just validate the spacing by + // checking length + assertEquals("toString() length",jsonObject0Str.length(), jsonObject.toString().length()); + assertEquals("toString(0) length",jsonObject0Str.length(), jsonObject.toString(0).length()); + assertEquals("toString(1) length",jsonObject1Str.length(), jsonObject.toString(1).length()); + assertEquals("toString(4) length",jsonObject4Str.length(), jsonObject.toString(4).length()); JSONObject jo = new JSONObject().put("TABLE", new JSONObject().put("yhoo", new JSONObject())); assertEquals("toString(2)","{\"TABLE\": {\"yhoo\": {}}}", jo.toString(2)); @@ -2630,9 +2632,10 @@ public class JSONObjectTest { JSONObject jsonObject = new JSONObject(str); try (StringWriter stringWriter = new StringWriter()) { String actualStr = jsonObject.write(stringWriter).toString(); - assertTrue("write() expected " +expectedStr+ - " but found " +actualStr, - expectedStr.equals(actualStr)); + // key order may change. verify length and individual key content + assertEquals("length", expectedStr.length(), actualStr.length()); + assertTrue("key1", actualStr.contains("\"key1\":\"value1\"")); + assertTrue("key2", actualStr.contains("\"key2\":[1,2,3]")); } } @@ -2734,16 +2737,25 @@ public class JSONObjectTest { " ]\n" + " }"; JSONObject jsonObject = new JSONObject(str0); - String expectedStr = str0; try (StringWriter stringWriter = new StringWriter();) { String actualStr = jsonObject.write(stringWriter,0,0).toString(); - assertEquals(expectedStr, actualStr); + + assertEquals("length", str0.length(), actualStr.length()); + assertTrue("key1", actualStr.contains("\"key1\":\"value1\"")); + assertTrue("key2", actualStr.contains("\"key2\":[1,false,3.14]")); } - - expectedStr = str2; + try (StringWriter stringWriter = new StringWriter();) { String actualStr = jsonObject.write(stringWriter,2,1).toString(); - assertEquals(expectedStr, actualStr); + + assertEquals("length", str2.length(), actualStr.length()); + assertTrue("key1", actualStr.contains(" \"key1\": \"value1\"")); + assertTrue("key2", actualStr.contains(" \"key2\": [\n" + + " 1,\n" + + " false,\n" + + " 3.14\n" + + " ]") + ); } } @@ -2978,9 +2990,9 @@ public class JSONObjectTest { @Test public void testSingletonBean() { final JSONObject jo = new JSONObject(Singleton.getInstance()); -// assertEquals(jo.keySet().toString(), 1, jo.length()); -// assertEquals(0, jo.get("someInt")); -// assertEquals(null, jo.opt("someString")); + assertEquals(jo.keySet().toString(), 1, jo.length()); + assertEquals(0, jo.get("someInt")); + assertEquals(null, jo.opt("someString")); // Update the singleton values Singleton.getInstance().setSomeInt(42); @@ -2991,8 +3003,8 @@ public class JSONObjectTest { assertEquals("Something", jo2.get("someString")); // ensure our original jo hasn't changed. -// assertEquals(0, jo.get("someInt")); -// assertEquals(null, jo.opt("someString")); + assertEquals(0, jo.get("someInt")); + assertEquals(null, jo.opt("someString")); } /** @@ -3002,9 +3014,9 @@ public class JSONObjectTest { @Test public void testSingletonEnumBean() { final JSONObject jo = new JSONObject(SingletonEnum.getInstance()); -// assertEquals(jo.keySet().toString(), 1, jo.length()); -// assertEquals(0, jo.get("someInt")); -// assertEquals(null, jo.opt("someString")); + assertEquals(jo.keySet().toString(), 1, jo.length()); + assertEquals(0, jo.get("someInt")); + assertEquals(null, jo.opt("someString")); // Update the singleton values SingletonEnum.getInstance().setSomeInt(42); @@ -3015,8 +3027,8 @@ public class JSONObjectTest { assertEquals("Something", jo2.get("someString")); // ensure our original jo hasn't changed. -// assertEquals(0, jo.get("someInt")); -// assertEquals(null, jo.opt("someString")); + assertEquals(0, jo.get("someInt")); + assertEquals(null, jo.opt("someString")); } /** diff --git a/src/test/java/org/json/junit/JunitTestSuite.java b/src/test/java/org/json/junit/JunitTestSuite.java deleted file mode 100644 index 1281625..0000000 --- a/src/test/java/org/json/junit/JunitTestSuite.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.json.junit; - -/* -Copyright (c) 2020 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -@RunWith(Suite.class) -@Suite.SuiteClasses({ - CDLTest.class, - CookieTest.class, - CookieListTest.class, - PropertyTest.class, - XMLTest.class, - JSONMLTest.class, - HTTPTest.class, - JSONStringerTest.class, - JSONObjectTest.class, - JSONObjectLocaleTest.class, - JSONArrayTest.class, - EnumTest.class, - JSONPointerTest.class, - JSONStringTest.class, - JSONTokenerTest.class, - XMLConfigurationTest.class -}) -public class JunitTestSuite { -} diff --git a/src/test/java/org/json/junit/TestRunner.java b/src/test/java/org/json/junit/TestRunner.java deleted file mode 100644 index 3b4aeef..0000000 --- a/src/test/java/org/json/junit/TestRunner.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.json.junit; - -/* -Copyright (c) 2020 JSON.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -The Software shall be used for Good, not Evil. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; - -/** - * Invoke this class main method if you want to run unit tests from the - * command line. If successful, will print "true" to stdout. - */ -public class TestRunner { - public static void main(String[] args) { - Result result = JUnitCore.runClasses(JunitTestSuite.class); - for (Failure failure : result.getFailures()) { - System.out.println(failure.toString()); - } - System.out.println(result.wasSuccessful()); - } -} \ No newline at end of file diff --git a/src/test/java/org/json/junit/XMLConfigurationTest.java b/src/test/java/org/json/junit/XMLConfigurationTest.java index 6919b31..14c4ba0 100755 --- a/src/test/java/org/json/junit/XMLConfigurationTest.java +++ b/src/test/java/org/json/junit/XMLConfigurationTest.java @@ -29,6 +29,13 @@ import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; + import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -369,16 +376,11 @@ public class XMLConfigurationTest { @Test public void shouldHandleContentNoArraytoString() { String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ - "altContent\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + "{\"addresses\":{\"altContent\":\">\"}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); XMLParserConfiguration config = new XMLParserConfiguration("altContent"); String finalStr = XML.toString(expectedJsonObject, null, config); - String expectedFinalStr = "

>"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance"; + String expectedFinalStr = ">"; assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ finalStr+"]", expectedFinalStr.equals(finalStr)); } @@ -391,17 +393,13 @@ public class XMLConfigurationTest { @Test public void shouldHandleContentArraytoString() { String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ - "altContent\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + "{\"addresses\":{\"altContent\":[1, 2, 3]}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); XMLParserConfiguration config = new XMLParserConfiguration("altContent"); String finalStr = XML.toString(expectedJsonObject, null, config); - String expectedFinalStr = "
"+ + String expectedFinalStr = ""+ "1\n2\n3"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance
"; + ""; assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ finalStr+"]", expectedFinalStr.equals(finalStr)); } @@ -413,17 +411,14 @@ public class XMLConfigurationTest { @Test public void shouldHandleArraytoString() { String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ - "\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + "{\"addresses\":{"+ + "\"something\":[1, 2, 3]}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); String finalStr = XML.toString(expectedJsonObject, null, XMLParserConfiguration.KEEP_STRINGS); - String expectedFinalStr = "
"+ + String expectedFinalStr = ""+ "123"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance
"; + ""; assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ finalStr+"]", expectedFinalStr.equals(finalStr)); } @@ -555,7 +550,9 @@ public class XMLConfigurationTest { */ String expected = "<123IllegalNode>someValue1someValue2"; - assertEquals(expected, result); + assertEquals("Length", expected.length(), result.length()); + assertTrue("123IllegalNode", result.contains("<123IllegalNode>someValue1")); + assertTrue("Illegal@node", result.contains("someValue2")); } /** @@ -740,10 +737,10 @@ public class XMLConfigurationTest { @Test public void testToJSONArray_jsonOutput() { final String originalXml = "011000True"; - final String expectedJsonString = "{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",1,\"00\",0],\"title\":true}}"; + final JSONObject expected = new JSONObject("{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",1,\"00\",0],\"title\":true}}"); final JSONObject actualJsonOutput = XML.toJSONObject(originalXml, new XMLParserConfiguration(false)); - assertEquals(expectedJsonString, actualJsonOutput.toString()); + Util.compareActualVsExpectedJsonObjects(actualJsonOutput,expected); } /** @@ -765,17 +762,20 @@ public class XMLConfigurationTest { @Test public void testToJsonXML() { final String originalXml = "011000True"; - final String expectedJsonString = "{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"True\"}}"; + final JSONObject expected = new JSONObject("{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"True\"}}"); final JSONObject json = XML.toJSONObject(originalXml, new XMLParserConfiguration(true)); - assertEquals(expectedJsonString, json.toString()); + Util.compareActualVsExpectedJsonObjects(json, expected); final String reverseXml = XML.toString(json); // this reversal isn't exactly the same. use JSONML for an exact reversal final String expectedReverseXml = "01011000True"; - assertEquals(expectedReverseXml, reverseXml); + assertEquals("length",expectedReverseXml.length(), reverseXml.length()); + assertTrue("array contents", reverseXml.contains("011000")); + assertTrue("item contents", reverseXml.contains("01")); + assertTrue("title contents", reverseXml.contains("True")); } /** @@ -916,11 +916,14 @@ public class XMLConfigurationTest { /* * Commenting out this method until the JSON-java code is updated * to support XML.toJSONObject(reader) + */ JSONObject expectedJsonObject = new JSONObject(expectedStr); - Reader reader = new StringReader(xmlStr); - JSONObject jsonObject = XML.toJSONObject(reader); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); - */ + try(Reader reader = new StringReader(xmlStr);) { + JSONObject jsonObject = XML.toJSONObject(reader, config); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } catch (IOException e) { + assertTrue("IO Reader error: " +e.getMessage(), false); + } } /** @@ -937,18 +940,19 @@ public class XMLConfigurationTest { /* * Commenting out this method until the JSON-java code is updated * to support XML.toJSONObject(reader) + */ try { JSONObject expectedJsonObject = new JSONObject(expectedStr); - File tempFile = testFolder.newFile("fileToJSONObject.xml"); - FileWriter fileWriter = new FileWriter(tempFile); - fileWriter.write(xmlStr); - fileWriter.close(); - Reader reader = new FileReader(tempFile); - JSONObject jsonObject = XML.toJSONObject(reader); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + File tempFile = this.testFolder.newFile("fileToJSONObject.xml"); + try(FileWriter fileWriter = new FileWriter(tempFile);){ + fileWriter.write(xmlStr); + } + try(Reader reader = new FileReader(tempFile);){ + JSONObject jsonObject = XML.toJSONObject(reader); + Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + } } catch (IOException e) { assertTrue("file writer error: " +e.getMessage(), false); } - */ } } \ No newline at end of file diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index d8ef0d0..d594961 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -419,18 +419,12 @@ public class XMLTest { */ @Test public void shouldHandleContentNoArraytoString() { - String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ - "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + String expectedStr = "{\"addresses\":{\"content\":\">\"}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); String finalStr = XML.toString(expectedJsonObject); - String expectedFinalStr = "
>"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance
"; - assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr.equals(finalStr)); + String expectedFinalStr = ">"; + assertEquals("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr, finalStr); } /** @@ -441,18 +435,14 @@ public class XMLTest { @Test public void shouldHandleContentArraytoString() { String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+ - "content\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + "{\"addresses\":{" + + "\"content\":[1, 2, 3]}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); String finalStr = XML.toString(expectedJsonObject); - String expectedFinalStr = "
"+ - "1\n2\n3"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance
"; - assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr.equals(finalStr)); + String expectedFinalStr = ""+ + "1\n2\n3"; + assertEquals("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr, finalStr); } /** @@ -462,18 +452,15 @@ public class XMLTest { @Test public void shouldHandleArraytoString() { String expectedStr = - "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ - "\"something\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ - "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}"; + "{\"addresses\":{"+ + "\"something\":[1, 2, 3]}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); String finalStr = XML.toString(expectedJsonObject); - String expectedFinalStr = "
"+ + String expectedFinalStr = ""+ "123"+ - "
test.xsdhttp://www.w3.org/2001/XMLSche"+ - "ma-instance
"; - assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr.equals(finalStr)); + ""; + assertEquals("Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]", expectedFinalStr, finalStr); } /** @@ -591,7 +578,9 @@ public class XMLTest { */ String expected = "<123IllegalNode>someValue1someValue2"; - assertEquals(expected, result); + assertEquals("length",expected.length(), result.length()); + assertTrue("123IllegalNode",result.contains("<123IllegalNode>someValue1")); + assertTrue("Illegal@node",result.contains("someValue2")); } /** @@ -813,10 +802,10 @@ public class XMLTest { @Test public void testToJSONArray_jsonOutput() { final String originalXml = "011000True"; - final String expectedJsonString = "{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",1,\"00\",0],\"title\":true}}"; + final JSONObject expectedJson = new JSONObject("{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",1,\"00\",0],\"title\":true}}"); final JSONObject actualJsonOutput = XML.toJSONObject(originalXml, false); - assertEquals(expectedJsonString, actualJsonOutput.toString()); + Util.compareActualVsExpectedJsonObjects(actualJsonOutput,expectedJson); } /** @@ -836,16 +825,21 @@ public class XMLTest { @Test public void testToJsonXML() { final String originalXml = "011000True"; - final String expectedJsonString = "{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"True\"}}"; + final JSONObject expected = new JSONObject("{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"True\"}}"); - final JSONObject json = XML.toJSONObject(originalXml,true); - assertEquals(expectedJsonString, json.toString()); + final JSONObject actual = XML.toJSONObject(originalXml,true); - final String reverseXml = XML.toString(json); + Util.compareActualVsExpectedJsonObjects(actual, expected); + + final String reverseXml = XML.toString(actual); // this reversal isn't exactly the same. use JSONML for an exact reversal + // the order of the elements may be differnet as well. final String expectedReverseXml = "01011000True"; - assertEquals(expectedReverseXml, reverseXml); + assertEquals("length",expectedReverseXml.length(), reverseXml.length()); + assertTrue("array contents", reverseXml.contains("011000")); + assertTrue("item contents", reverseXml.contains("01")); + assertTrue("title contents", reverseXml.contains("True")); } /** From aa0a5a7245d0a3d8650e66881d4274eb56928d87 Mon Sep 17 00:00:00 2001 From: "Erik C. Thauvin" Date: Tue, 16 Jun 2020 14:55:16 -0700 Subject: [PATCH 448/451] Added putAll(Collection) and putAll(Array) methods. --- src/main/java/org/json/JSONArray.java | 83 ++++++++++++++++++++++----- 1 file changed, 70 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index 787e124..820da83 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -173,9 +173,7 @@ public class JSONArray implements Iterable { this.myArrayList = new ArrayList(); } else { this.myArrayList = new ArrayList(collection.size()); - for (Object o: collection){ - this.myArrayList.add(JSONObject.wrap(o)); - } + this.addAll(collection); } } @@ -193,16 +191,7 @@ public class JSONArray implements Iterable { */ public JSONArray(Object array) throws JSONException { this(); - if (array.getClass().isArray()) { - int length = Array.getLength(array); - this.myArrayList.ensureCapacity(length); - for (int i = 0; i < length; i += 1) { - this.put(JSONObject.wrap(Array.get(array, i))); - } - } else { - throw new JSONException( - "JSONArray initial value should be a string or collection or array."); - } + this.addAll(array); } /** @@ -1174,6 +1163,36 @@ public class JSONArray implements Iterable { } return this.put(value); } + + /** + * Put or replace a collection's elements in the JSONArray. + * + * @param collection + * A Collection. + * @return this. + */ + public JSONArray putAll(Collection collection) { + this.addAll(collection); + return this; + } + + /** + * Put or replace an array's elements in the JSONArray. + * + * @param array + * Array. If the parameter passed is null, or not an array, an + * exception will be thrown. + * @return this. + * + * @throws JSONException + * If not an array or if an array value is non-finite number. + * @throws NullPointerException + * Thrown if the array parameter is null. + */ + public JSONArray putAll(Object array) throws JSONException { + this.addAll(array); + return this; + } /** * Creates a JSONPointer using an initialization string and tries to @@ -1500,6 +1519,44 @@ public class JSONArray implements Iterable { public boolean isEmpty() { return this.myArrayList.isEmpty(); } + + + /** + * Add a collection's elements to the JSONArray. + * + * @param collection + * A Collection. + */ + private void addAll(Collection collection) { + for (Object o: collection){ + this.myArrayList.add(JSONObject.wrap(o)); + } + } + + /** + * Add an array's elements to the JSONArray. + * + * @param array + * Array. If the parameter passed is null, or not an array, an + * exception will be thrown. + * + * @throws JSONException + * If not an array or if an array value is non-finite number. + * @throws NullPointerException + * Thrown if the array parameter is null. + */ + private void addAll(Object array) throws JSONException { + if (array.getClass().isArray()) { + int length = Array.getLength(array); + this.myArrayList.ensureCapacity(length); + for (int i = 0; i < length; i += 1) { + this.put(JSONObject.wrap(Array.get(array, i))); + } + } else { + throw new JSONException( + "JSONArray initial value should be a string or collection or array."); + } + } /** * Create a new JSONException in a common format for incorrect conversions. From 86e136afc92ece41e18243cccddcb8d47c616e90 Mon Sep 17 00:00:00 2001 From: "Erik C. Thauvin" Date: Tue, 21 Jul 2020 17:11:24 -0700 Subject: [PATCH 449/451] Increase array list capacity in addAll method to ensure it can hold additional elements. --- src/main/java/org/json/JSONArray.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index 820da83..16829d5 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -1548,7 +1548,7 @@ public class JSONArray implements Iterable { private void addAll(Object array) throws JSONException { if (array.getClass().isArray()) { int length = Array.getLength(array); - this.myArrayList.ensureCapacity(length); + this.myArrayList.ensureCapacity(this.myArrayList.size() + length); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } From f1d354ce7be0a7ca3e7e338afbc4daa6de6e8950 Mon Sep 17 00:00:00 2001 From: "Erik C. Thauvin" Date: Tue, 21 Jul 2020 17:35:32 -0700 Subject: [PATCH 450/451] Increase array list capacity in addAll(collection) method to ensure it can hold additional elements. --- src/main/java/org/json/JSONArray.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index 16829d5..3082974 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -1528,6 +1528,7 @@ public class JSONArray implements Iterable { * A Collection. */ private void addAll(Collection collection) { + this.myArrayList.ensureCapacity(this.myArrayList.size() + collection.size()); for (Object o: collection){ this.myArrayList.add(JSONObject.wrap(o)); } From 0d13e5606456f34d9b89e0756aad2bd55ea5b44d Mon Sep 17 00:00:00 2001 From: "Erik C. Thauvin" Date: Tue, 21 Jul 2020 23:09:28 -0700 Subject: [PATCH 451/451] Added tests for consecutive calls to putAll. --- .../java/org/json/junit/JSONArrayTest.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index eda3c06..f11b953 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -225,6 +225,44 @@ public class JSONArrayTest { expected.similar(jaObj)); } + /** + * Tests consecutive calls to putAll with array and collection. + */ + @Test + public void verifyPutAll() { + final JSONArray jsonArray = new JSONArray(); + + // array + int[] myInts = { 1, 2, 3, 4, 5 }; + jsonArray.putAll(myInts); + + assertEquals("int arrays lengths should be equal", + jsonArray.length(), + myInts.length); + + for (int i = 0; i < myInts.length; i++) { + assertEquals("int arrays elements should be equal", + myInts[i], + jsonArray.getInt(i)); + } + + // collection + List myList = Arrays.asList("one", "two", "three", "four", "five"); + jsonArray.putAll(myList); + + int len = myInts.length + myList.size(); + + assertEquals("arrays lengths should be equal", + jsonArray.length(), + len); + + for (int i = 0; i < myList.size(); i++) { + assertEquals("collection elements should be equal", + myList.get(i), + jsonArray.getString(myInts.length + i)); + } + } + /** * Verifies that the put Collection has backwards compatibility with RAW types pre-java5. */