diff --git a/.travis.yml b/.travis.yml index c8361bc3..6ba6a68d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,4 +18,8 @@ script: - mvn -U -C -Pstaging,oss-release -Dnon.final=true -Dgpg.skip=true clean verify - cd .. - mvn -U -C -Pstaging,oss-release -Dnon.final=true -Dgpg.skip=true clean verify + - cd tck + - mvn -U clean install + - cd ../impl-tck + - mvn -U clean test diff --git a/impl-tck/pom.xml b/impl-tck/pom.xml new file mode 100644 index 00000000..7f24ba81 --- /dev/null +++ b/impl-tck/pom.xml @@ -0,0 +1,68 @@ + + + + + 4.0.0 + + org.glassfish + jakarta.json-tck + 1.0.0-SNAPSHOT + pom + + + tck-tests + tck-tests-plugability + + + + 2.0.0-SNAPSHOT + 2.0.0-SNAPSHOT + 2.0.0-SNAPSHOT + + + + + jakarta.json + jakarta.json-api + ${jsonp-api.version} + test + + + org.glassfish + jakarta.json + ${jsonp-impl.version} + test + + + org.jboss.arquillian.container + arquillian-weld-embedded + 2.0.1.Final + test + + + org.jboss.weld.se + weld-se + 2.4.3.Final + test + + + + diff --git a/impl-tck/tck-tests-plugability/pom.xml b/impl-tck/tck-tests-plugability/pom.xml new file mode 100644 index 00000000..c3e035df --- /dev/null +++ b/impl-tck/tck-tests-plugability/pom.xml @@ -0,0 +1,63 @@ + + + + + 4.0.0 + + + org.glassfish + jakarta.json-tck + 1.0.0-SNAPSHOT + + + jakarta.json-tck-tests-plugability + + + + jakarta.json + jakarta.json-tck-tests-plugability + ${jsonp-tck.version} + test + + + jakarta.json + jakarta.json-tck-common + ${jsonp-tck.version} + test + + + + + + + maven-surefire-plugin + 3.0.0-M4 + + + jakarta.json:jakarta.json-tck-tests-plugability + + false + true + + + + + diff --git a/impl-tck/tck-tests/pom.xml b/impl-tck/tck-tests/pom.xml new file mode 100644 index 00000000..006e7326 --- /dev/null +++ b/impl-tck/tck-tests/pom.xml @@ -0,0 +1,63 @@ + + + + + 4.0.0 + + + org.glassfish + jakarta.json-tck + 1.0.0-SNAPSHOT + + + jakarta.json-tck-tests + + + + jakarta.json + jakarta.json-tck-tests + ${jsonp-tck.version} + test + + + jakarta.json + jakarta.json-tck-common + ${jsonp-tck.version} + test + + + + + + + maven-surefire-plugin + 3.0.0-M4 + + + jakarta.json:jakarta.json-tck-tests + + false + true + + + + + diff --git a/tck/pom.xml b/tck/pom.xml new file mode 100644 index 00000000..dd7e80d6 --- /dev/null +++ b/tck/pom.xml @@ -0,0 +1,85 @@ + + + + 4.0.0 + + + org.eclipse.ee4j + project + 1.0.6 + + + jakarta.json + jakarta.json-tck + 2.0.0-SNAPSHOT + pom + + + tck-common + tck-tests + tck-tests-plugability + + + JSON-P TCK + Jakarta JSON-P TCK + + + + Eclipse Public License 2.0 + https://projects.eclipse.org/license/epl-2.0 + repo + + + GNU General Public License, version 2 with the GNU Classpath Exception + https://projects.eclipse.org/license/secondary-gpl-2.0-cp + repo + + + + + UTF-8 + 1.8 + 1.8 + + + + + jakarta.json + jakarta.json-api + 2.0.0-RC1 + provided + + + jakarta.inject + jakarta.inject-api + 1.0 + provided + + + org.jboss.arquillian.junit + arquillian-junit-container + 1.6.0.Final + + + junit + junit + 4.12 + + + diff --git a/tck/tck-common/pom.xml b/tck/tck-common/pom.xml new file mode 100644 index 00000000..50d6c679 --- /dev/null +++ b/tck/tck-common/pom.xml @@ -0,0 +1,31 @@ + + + + 4.0.0 + + + jakarta.json + jakarta.json-tck + 2.0.0-SNAPSHOT + + + jakarta.json-tck-common + jar + + diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/JSONP_Data.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/JSONP_Data.java new file mode 100644 index 00000000..e7da0b18 --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/JSONP_Data.java @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.common; + + +import java.util.*; + +public final class JSONP_Data { + + public static final String unicodeControlCharsEscaped = "\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\u0008\\u0009" + + "\\u000a\\u000b\\u000c\\u000d\\u000e\\u000f" + + "\\u000A\\u000B\\u000C\\u000D\\u000E\\u000F" + + "\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019" + + "\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\\u007f" + + "\\u001A\\u001B\\u001C\\u001D\\u001E\\u001F\\u007F" + + "\\u0080\\u0081\\u0082\\u0083\\u0084\\u0085\\u0086\\u0087\\u0088\\u0089" + + "\\u008a\\u008b\\u008c\\u008d\\u008e\\u008f" + + "\\u008A\\u008B\\u008C\\u008D\\u008E\\u008F" + + "\\u0090\\u0091\\u0092\\u0093\\u0094\\u0095\\u0096\\u0097\\u0098\\u0099" + + "\\u009a\\u009b\\u009c\\u009d\\u009e\\u009f" + + "\\u009A\\u009B\\u009C\\u009D\\u009E\\u009F"; + + // NOTE: For the unicode values u000a and u000d we need to use the Java + // escape for both NL and CR as \n and \r respectively + public static final String unicodeControlCharsNonEscaped = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009" + + "\n\u000b\u000c\r\u000e\u000f" + "\n\u000B\u000C\r\u000E\u000F" + + "\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019" + + "\u001a\u001b\u001c\u001d\u001e\u001f\u007f" + + "\u001A\u001B\u001C\u001D\u001E\u001F\u007F" + + "\u0080\u0081\u0082\u0083\u0084\u0085\u0086\u0087\u0088\u0089" + + "\u008a\u008b\u008c\u008d\u008e\u008f" + + "\u008A\u008B\u008C\u008D\u008E\u008F" + + "\u0090\u0091\u0092\u0093\u0094\u0095\u0096\u0097\u0098\u0099" + + "\u009a\u009b\u009c\u009d\u009e\u009f" + + "\u009A\u009B\u009C\u009D\u009E\u009F"; + + // Standard backslash escape characters + public static final String escapeCharsAsString = "\"\\/\b\f\n\r\t"; + + public static final String asciiCharacters = "!@#$%^&*()_+|~1234567890-=;',./<>? " + + "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"; + + public static final String jsonArrayTestData = "[ \"\", \"string\", 100, true, false, null, {}, { \"name\" : \"value\" }, [], [ \"one\", \"two\" ] ]"; + + public static final String jsonObjectTestData = "{" + + "\"emptyString\" : \"\"," + "\"emptyArray\" : []," + + "\"emptyObject\" : {}," + "\"string\" : \"string\"," + + "\"number\" : 100," + "\"true\" : true," + "\"false\" : false," + + "\"null\" : null," + "\"object\" : { \"name\" : \"value\" }," + + "\"array\" : [ \"one\", \"two\" ]," + "}"; + + public static final String jsonArrayTestData2 = "[" + "\"\"," + "[]," + "{}," + + "\"string\"," + "100," + "true," + "false," + "null," + + "{ \"name\" : \"value\" }," + "[ \"one\", \"two\" ]," + "]"; + + public static final String jsonObjectWithAllTypesOfData = "{" + + "\"emptyString\" : \"\"," + "\"emptyArray\" : []," + + "\"emptyObject\" : {}," + "\"string\" : \"string\"," + + "\"number\" : 100," + "\"true\" : true," + "\"false\" : false," + + "\"null\" : null," + "\"object\" : {" + "\"emptyString\" : \"\"," + + "\"emptyArray\" : []," + "\"emptyObject\" : {}," + + "\"string\" : \"string\"," + "\"number\" : 100," + "\"true\" : true," + + "\"false\" : false," + "\"null\" : null," + + "\"object\" : { \"name\" : \"value\" }," + + "\"array\" : [ \"one\", \"two\" ]" + "}," + + "\"array\" : [ \"string\", 100, true, false, null, { \"name\" : \"value\" }" + + ", [ \"one\", \"two\" ] " + "]," + "\"intPositive\" : 100," + + "\"intNegative\" : -100," + "\"longMax\" : 9223372036854775807," + + "\"longMin\" : -9223372036854775808," + "\"fracPositive\" : 0.5," + + "\"fracNegative\" : -0.5," + "\"expPositive1\" : 7e3," + + "\"expPositive2\" : 7e+3," + "\"expPositive3\" : 9E3," + + "\"expPositive4\" : 9E+3," + "\"expNegative1\" : 7e-3," + + "\"expNegative2\" : 7E-3," + "\"asciiChars\" : \"" + asciiCharacters + + "\"" + "}"; + + public static final String jsonArrayWithAllTypesOfData = "[" + "\"\"," + "[]," + + "{}," + "\"string\"," + "100," + "true," + "false," + "null," + "{" + + "\"emptyString\" : \"\"," + "\"emptyArray\" : []," + + "\"emptyObject\" : {}," + "\"string\" : \"string\"," + + "\"number\" : 100," + "\"true\" : true," + "\"false\" : false," + + "\"null\" : null," + "\"object\" : { \"name\" : \"value\" }," + + "\"array\" : [ \"one\", \"two\" ]" + "}," + + "[ \"string\", 100, true, false, null, { \"name\" : \"value\" }" + + ", [ \"one\", \"two\" ] " + "]," + "100," + "-100," + + "9223372036854775807," + "-9223372036854775808," + "0.5," + "-0.5," + + "7e3," + "7e+3," + "9E3," + "9E+3," + "7e-3," + "7E-3," + "\"" + + asciiCharacters + "\"" + "]"; + + public static final String jsonObjectWithLotsOfNestedObjectsData = "{" + + "\"nested1\" : {" + "\"name1\" : \"value1\"," + "\"nested2\" : {" + + "\"name2\" : \"value2\"," + "\"nested3\" : {" + + "\"name3\" : \"value3\"," + "\"nested4\" : {" + + "\"name4\" : \"value4\"," + "\"nested5\" : {" + + "\"name5\" : \"value5\"," + "\"nested6\" : {" + + "\"name6\" : \"value6\"," + "\"nested7\" : {" + + "\"name7\" : \"value7\"," + "\"nested8\" : {" + + "\"name8\" : \"value8\"," + "\"nested9\" : {" + + "\"name9\" : \"value9\"," + "\"nested10\" : {" + + "\"name10\" : \"value10\"," + "\"nested11\" : {" + + "\"name11\" : \"value11\"," + "\"nested12\" : {" + + "\"name12\" : \"value12\"," + "\"nested13\" : {" + + "\"name13\" : \"value13\"," + "\"nested14\" : {" + + "\"name14\" : \"value14\"," + "\"nested15\" : {" + + "\"name15\" : \"value15\"," + "\"nested16\" : {" + + "\"name16\" : \"value16\"," + "\"nested17\" : {" + + "\"name17\" : \"value17\"," + "\"nested18\" : {" + + "\"name18\" : \"value18\"," + "\"nested19\" : {" + + "\"name19\" : \"value19\"," + "\"nested20\" : {" + + "\"name20\" : \"value20\"," + "\"nested21\" : {" + + "\"name21\" : \"value21\"," + "\"nested22\" : {" + + "\"name22\" : \"value22\"," + "\"nested23\" : {" + + "\"name23\" : \"value23\"," + "\"nested24\" : {" + + "\"name24\" : \"value24\"," + "\"nested25\" : {" + + "\"name25\" : \"value25\"," + "\"nested26\" : {" + + "\"name26\" : \"value26\"," + "\"nested27\" : {" + + "\"name27\" : \"value27\"," + "\"nested28\" : {" + + "\"name28\" : \"value28\"," + "\"nested29\" : {" + + "\"name29\" : \"value29\"," + "\"nested30\" : {" + + "\"name30\" : \"value30\"" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}"; + + public static final String jsonArrayWithLotsOfNestedObjectsData = "[" + "{" + + "\"name1\" : \"value1\"," + "\"nested2\" : {" + + "\"name2\" : \"value2\"," + "\"nested3\" : {" + + "\"name3\" : \"value3\"," + "\"nested4\" : {" + + "\"name4\" : \"value4\"," + "\"nested5\" : {" + + "\"name5\" : \"value5\"," + "\"nested6\" : {" + + "\"name6\" : \"value6\"," + "\"nested7\" : {" + + "\"name7\" : \"value7\"," + "\"nested8\" : {" + + "\"name8\" : \"value8\"," + "\"nested9\" : {" + + "\"name9\" : \"value9\"," + "\"nested10\" : {" + + "\"name10\" : \"value10\"," + "\"nested11\" : {" + + "\"name11\" : \"value11\"," + "\"nested12\" : {" + + "\"name12\" : \"value12\"," + "\"nested13\" : {" + + "\"name13\" : \"value13\"," + "\"nested14\" : {" + + "\"name14\" : \"value14\"," + "\"nested15\" : {" + + "\"name15\" : \"value15\"," + "\"nested16\" : {" + + "\"name16\" : \"value16\"," + "\"nested17\" : {" + + "\"name17\" : \"value17\"," + "\"nested18\" : {" + + "\"name18\" : \"value18\"," + "\"nested19\" : {" + + "\"name19\" : \"value19\"," + "\"nested20\" : {" + + "\"name20\" : \"value20\"," + "\"nested21\" : {" + + "\"name21\" : \"value21\"," + "\"nested22\" : {" + + "\"name22\" : \"value22\"," + "\"nested23\" : {" + + "\"name23\" : \"value23\"," + "\"nested24\" : {" + + "\"name24\" : \"value24\"," + "\"nested25\" : {" + + "\"name25\" : \"value25\"," + "\"nested26\" : {" + + "\"name26\" : \"value26\"," + "\"nested27\" : {" + + "\"name27\" : \"value27\"," + "\"nested28\" : {" + + "\"name28\" : \"value28\"," + "\"nested29\" : {" + + "\"name29\" : \"value29\"," + "\"nested30\" : {" + + "\"name30\" : \"value30\"" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "}" + "]"; + + public static final String jsonArrayWithMultipleArraysData = "[ \"string\", 100, true, false, null, { \"object\" : \"object\" }, [ \"one\"," + + "\"two\" ], [ 100, 7e7, true, false, null, { \"object2\" : \"object2\" } ] ]"; +} diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/JSONP_Util.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/JSONP_Util.java new file mode 100644 index 00000000..94145de5 --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/JSONP_Util.java @@ -0,0 +1,2613 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.common; + + +import java.util.*; +import java.io.*; +import java.net.*; +import java.lang.reflect.*; +import java.nio.charset.Charset; + +import java.math.BigInteger; +import java.math.BigDecimal; + +import jakarta.json.*; +import jakarta.json.stream.*; +import jakarta.json.stream.JsonParser.Event.*; +import jakarta.json.JsonValue.ValueType.*; + +public final class JSONP_Util { + + // Charset CONSTANTS for all the supported UTF encodings + public static final Charset UTF_8 = Charset.forName("UTF-8"); + + public static final Charset UTF_16 = Charset.forName("UTF-16"); + + public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); + + public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); + + public static final Charset UTF_32BE = Charset.forName("UTF-32BE"); + + public static final Charset UTF_32LE = Charset.forName("UTF-32LE"); + + // Test Config properties + public static final String FOO_CONFIG = "jakarta.jsonp.tck.common.FOO_CONFIG"; + + // Number of parser errors encountered + private static int parseErrs = 0; + + // A JsonNumber NumberType is now INTEGRAL or NON_INTEGRAL based on + // JsonNumber.isIntegral(). + // The following 2 constant definitions represent these NumberType boolean + // values. + public static final boolean INTEGRAL = true; + + public static final boolean NON_INTEGRAL = false; + + /********************************************************************************* + * void dumpContentsOfResource(String resource) + *********************************************************************************/ + public static void dumpContentsOfResource(String resource) { + System.out.println("Dumping contents of Resource file: " + resource); + BufferedReader reader = null; + try { + InputStream iStream = JSONP_Util.class + .getResourceAsStream("/" + resource); + if (iStream == null) { + System.err.println( + "dumpContentsOfResource: no resource found in classpath or archive named " + + resource); + return; + } + reader = new BufferedReader(new InputStreamReader(iStream)); + String thisLine; + while ((thisLine = reader.readLine()) != null) { + System.out.println(thisLine); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (Exception e) { + System.err.println("exception closing stream: " + e); + } + } + } + + /********************************************************************************* + * void dumpFile(String file) + *********************************************************************************/ + public static void dumpFile(String file) { + System.out.println("Dumping contents of file: " + file); + BufferedReader reader = null; + try { + FileInputStream fis = new FileInputStream(file); + if (fis == null) { + System.err.println("dumpFile: no file found named " + file); + return; + } + reader = new BufferedReader(new InputStreamReader(fis)); + String thisLine; + while ((thisLine = reader.readLine()) != null) { + System.out.println(thisLine); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (Exception e) { + System.err.println("exception closing stream: " + e); + } + } + } + + /********************************************************************************* + * String getContentsOfResourceAsString(String resource) + *********************************************************************************/ + public static String getContentsOfResourceAsString(String resource) { + StringBuilder sb = new StringBuilder(); + BufferedReader reader = null; + try { + InputStream iStream = JSONP_Util.class + .getResourceAsStream("/" + resource); + if (iStream == null) { + System.err.println( + "dumpContentsOfResource: no resource found in classpath or archive named " + + resource); + return null; + } + reader = new BufferedReader(new InputStreamReader(iStream)); + String thisLine; + while ((thisLine = reader.readLine()) != null) { + sb.append(thisLine); + } + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (Exception e) { + System.err.println("exception closing stream: " + e); + } + } + return sb.toString(); + } + + /********************************************************************************* + * Reader getReaderFromResource(String resource) + *********************************************************************************/ + public static Reader getReaderFromResource(String resource) { + InputStreamReader reader = null; + try { + InputStream iStream = JSONP_Util.class + .getResourceAsStream("/" + resource); + if (iStream == null) + System.err.println( + "getReaderFromResource: no resource found in classpath or archive named " + + resource); + else + reader = new InputStreamReader(iStream); + } catch (Exception e) { + e.printStackTrace(); + } + return reader; + } + + /********************************************************************************* + * Reader getReaderFromString(String contents) + *********************************************************************************/ + public static Reader getReaderFromString(String contents) { + InputStreamReader reader = null; + try { + InputStream iStream = new ByteArrayInputStream(contents.getBytes(UTF_8)); + if (iStream == null) + System.err.println("getReaderFromString: no input stream"); + else + reader = new InputStreamReader(iStream); + } catch (Exception e) { + e.printStackTrace(); + } + return reader; + } + + /********************************************************************************* + * InputStream getInputStreamFromResource(String resource) + *********************************************************************************/ + public static InputStream getInputStreamFromResource(String resource) { + InputStream iStream = null; + try { + iStream = JSONP_Util.class.getResourceAsStream("/" + resource); + if (iStream == null) + System.err.println( + "getInputStreamFromResource: no resource found in classpath or archive named " + + resource); + } catch (Exception e) { + e.printStackTrace(); + } + return iStream; + } + + /********************************************************************************* + * InputStream getInputStreamFromString(String contents) + *********************************************************************************/ + public static InputStream getInputStreamFromString(String contents) { + InputStream iStream = null; + try { + iStream = new ByteArrayInputStream(contents.getBytes(UTF_8)); + if (iStream == null) + System.err.println("getInputStreamFromString: no input stream"); + } catch (Exception e) { + e.printStackTrace(); + } + return iStream; + } + + /********************************************************************************* + * InputStream getInputStreamFromOutputStream(ByteArrayOutputStream baos) + *********************************************************************************/ + public static InputStream getInputStreamFromOutputStream( + ByteArrayOutputStream baos) { + InputStream iStream = null; + try { + iStream = new ByteArrayInputStream(baos.toByteArray()); + if (iStream == null) + System.err.println("getInputStreamFromOutputStream: no input stream"); + } catch (Exception e) { + e.printStackTrace(); + } + return iStream; + } + + /********************************************************************************* + * String removeWhitespace(String text) + * + * NOTE: This does not remove whitespace of Json text if a quoted string which + * can include whitespace. + *********************************************************************************/ + public static String removeWhitespace(String text) { + StringReader reader = new StringReader(text); + StringWriter writer = new StringWriter(); + try { + boolean quotedString = false; + boolean backslash = false; + int c; + while ((c = reader.read()) != -1) { + // Skip white space if not quoted string + if (!quotedString) { + if (Character.isWhitespace(c)) + continue; + } + writer.write(c); + if (c == '"') { + if (!backslash) + quotedString = !quotedString; + backslash = false; + } else if (c == '\\') + backslash = true; + } + } catch (IOException e) { + e.printStackTrace(); + } + return writer.toString(); + } + + /********************************************************************************* + * JsonNumber createJsonNumber + * + * The following method signatures are available: + * + * o JsonNumber createJsonNumber(double) o JsonNumber createJsonNumber(long) o + * JsonNumber createJsonNumber(int) o JsonNumber createJsonNumber(BigDecimal) + * o JsonNumber createJsonNumber(BigInteger) + *********************************************************************************/ + public static JsonNumber createJsonNumber(double val) { + JsonArray array = Json.createArrayBuilder().add(val).build(); + return array.getJsonNumber(0); + } + + public static JsonNumber createJsonNumber(long val) { + JsonArray array = Json.createArrayBuilder().add(val).build(); + return array.getJsonNumber(0); + } + + public static JsonNumber createJsonNumber(int val) { + JsonArray array = Json.createArrayBuilder().add(val).build(); + return array.getJsonNumber(0); + } + + public static JsonNumber createJsonNumber(BigDecimal val) { + JsonArray array = Json.createArrayBuilder().add(val).build(); + return array.getJsonNumber(0); + } + + public static JsonNumber createJsonNumber(BigInteger val) { + JsonArray array = Json.createArrayBuilder().add(val).build(); + return array.getJsonNumber(0); + } + + /********************************************************************************* + * JsonString createJsonString(String val) + *********************************************************************************/ + public static JsonString createJsonString(String val) { + JsonArray array = Json.createArrayBuilder().add(val).build(); + return array.getJsonString(0); + } + + /********************************************************************************* + * void dumpJsonString(JsonString val) + *********************************************************************************/ + public static void dumpJsonString(JsonString value) { + System.out.println("dumpJsonString->" + toStringJsonString(value)); + } + + /********************************************************************************* + * void dumpJsonArray(JsonArray value) + *********************************************************************************/ + public static void dumpJsonArray(JsonArray value) { + System.out.println("dumpJsonArray->" + toStringJsonArray(value)); + } + + /********************************************************************************* + * void dumpJsonObject(JsonObject value) + *********************************************************************************/ + public static void dumpJsonObject(JsonObject value) { + System.out.println("dumpJsonObject->" + toStringJsonObject(value)); + } + + /********************************************************************************* + * void dumpJsonConstant(JsonValue value) + *********************************************************************************/ + public static void dumpJsonConstant(JsonValue value) { + System.out.println("dumpJsonConstant->" + toStringJsonConstant(value)); + } + + /********************************************************************************* + * void dumpJsonNumber(JsonNumber value) + *********************************************************************************/ + public static void dumpJsonNumber(JsonNumber value) { + System.out.println("dumpJsonNumber->" + toStringJsonNumber(value)); + } + + /********************************************************************************* + * void dumpJsonValue(JsonValue value) + *********************************************************************************/ + public static void dumpJsonValue(JsonValue value) { + if (value instanceof JsonNumber) { + dumpJsonNumber((JsonNumber) value); + } else if (value instanceof JsonString) { + dumpJsonString((JsonString) value); + } else if (value instanceof JsonArray) { + dumpJsonArray((JsonArray) value); + } else if (value instanceof JsonObject) { + dumpJsonObject((JsonObject) value); + } else + dumpJsonConstant(value); + } + + /********************************************************************************* + * String toStringJsonString(JsonString value) + *********************************************************************************/ + public static String toStringJsonString(JsonString value) { + if (value == null) + return ("JsonString is null"); + return ("\"" + value.getString() + "\""); + } + + /********************************************************************************* + * String toStringJsonArray(JsonArray value) + *********************************************************************************/ + public static String toStringJsonArray(JsonArray value) { + if (value == null) + return ("JsonArray is null"); + StringBuilder sb = new StringBuilder(); + sb.append("["); + Iterator iter = value.iterator(); + String comma = ""; + while (iter.hasNext()) { + sb.append(comma + toStringJsonValue(iter.next())); + if (comma.equals("")) + comma = ","; + } + sb.append("]"); + return (sb.toString()); + } + + /********************************************************************************* + * String toStringJsonObject(JsonObject value) + *********************************************************************************/ + public static String toStringJsonObject(JsonObject value) { + if (value == null) + return ("JsonObject is null"); + StringBuilder sb = new StringBuilder(); + sb.append("{"); + String comma = ""; + for (Map.Entry entry : value.entrySet()) { + sb.append(comma + "\"" + entry.getKey() + "\":" + + toStringJsonValue(entry.getValue())); + if (comma.equals("")) + comma = ","; + } + sb.append("}"); + return (sb.toString()); + } + + /********************************************************************************* + * String toStringJsonConstant(JsonValue value) + *********************************************************************************/ + public static String toStringJsonConstant(JsonValue value) { + if (value == null) + return ("JsonValue is null"); + if (value == JsonValue.FALSE) + return "false"; + else if (value == JsonValue.TRUE) + return "true"; + else if (value == JsonValue.NULL) + return "null"; + else + return "UNKNOWN"; + } + + /********************************************************************************* + * String toStringJsonNumber(JsonNumber value) + *********************************************************************************/ + public static String toStringJsonNumber(JsonNumber value) { + if (value == null) + return ("JsonNumber is null"); + if (value.isIntegral() == INTEGRAL) + return ("" + value.longValue()); + else + return ("" + value.bigDecimalValue()); + } + + /********************************************************************************* + * String toStringJsonValue(JsonValue value) + *********************************************************************************/ + public static String toStringJsonValue(JsonValue value) { + if (value instanceof JsonNumber) { + return toStringJsonNumber((JsonNumber) value); + } else if (value instanceof JsonString) { + return toStringJsonString((JsonString) value); + } else if (value instanceof JsonArray) { + return toStringJsonArray((JsonArray) value); + } else if (value instanceof JsonObject) { + return toStringJsonObject((JsonObject) value); + } else + return toStringJsonConstant(value); + } + + /********************************************************************************* + * void dumpSet(Set set, String msg) + *********************************************************************************/ + public static void dumpSet(Set set, String msg) { + System.out.println("*** Beg: Dumping List contents ***"); + if (msg != null) + System.out.println("*** Message: " + msg); + Iterator iterator = set.iterator(); + System.out.println("Set: ("); + while (iterator.hasNext()) { + System.out.println((String) iterator.next()); + } + System.out.println(")"); + System.out.println("*** End: Dumping Set contents ***"); + } + + /********************************************************************************* + * void dumpSet(Set set) + *********************************************************************************/ + public static void dumpSet(Set set) { + dumpSet(set, null); + } + + /********************************************************************************* + * String toStringSet(Set set) + *********************************************************************************/ + public static String toStringSet(Set set) { + Iterator iter = set.iterator(); + StringBuilder sb = new StringBuilder(); + sb.append("Set: ("); + while (iter.hasNext()) { + sb.append(iter.next()); + if (iter.hasNext()) + sb.append(","); + } + sb.append(")"); + return sb.toString(); + } + + /********************************************************************************* + * boolean assertEqualsSet(SetexpSet, SetactSet) + *********************************************************************************/ + public static boolean assertEqualsSet(Set expSet, + Set actSet) { + if (actSet.equals(expSet)) { + System.out.println("Sets are equal - match (Success)"); + System.out.println("Expected: " + toStringSet(expSet)); + System.out.println("Actual: " + toStringSet(actSet)); + return true; + } else { + System.out.println("Sets are not equal - mismatch (Failure)"); + System.err.println("Expected: " + toStringSet(expSet)); + System.err.println("Actual: " + toStringSet(actSet)); + return false; + } + } + + /********************************************************************************* + * void dumpMap(Map map, String msg) + *********************************************************************************/ + public static void dumpMap(Map map, String msg) { + System.out.println("*** Beg: Dumping Map contents ***"); + if (msg != null) + System.out.println("*** Message: " + msg); + System.out.println("Map: {"); + for (Map.Entry entry : map.entrySet()) { + System.out.println( + "\"" + entry.getKey() + "\":" + toStringJsonValue(entry.getValue())); + } + System.out.println("}"); + System.out.println("*** End: Dumping Map contents ***"); + } + + /********************************************************************************* + * void dumpMap(Map map) + *********************************************************************************/ + public static void dumpMap(Map map) { + dumpMap(map, null); + } + + /********************************************************************************* + * String toStringMap(Map map) + *********************************************************************************/ + public static String toStringMap(Map map) { + StringBuilder sb = new StringBuilder(); + sb.append("Map: {"); + String comma = ""; + for (Map.Entry entry : map.entrySet()) { + sb.append(comma + "\"" + entry.getKey() + "\":" + + toStringJsonValue(entry.getValue())); + if (comma.equals("")) + comma = ","; + } + sb.append("}"); + return sb.toString(); + } + + /********************************************************************************* + * boolean assertEqualsMap(MapexpMap, + * MapactMap) + *********************************************************************************/ + public static boolean assertEqualsMap(Map expMap, + Map actMap) { + if (actMap.equals(expMap)) { + System.out.println("Maps are equal - match (Success)"); + System.out.println("Expected: " + toStringMap(expMap)); + System.out.println("Actual: " + toStringMap(actMap)); + return true; + } else { + System.out.println("Maps are not equal - mismatch (Failure)"); + System.err.println("Expected: " + toStringMap(expMap)); + System.err.println("Actual: " + toStringMap(actMap)); + return false; + } + } + + /********************************************************************************* + * assertEqualsMap2 + *********************************************************************************/ + public static boolean assertEqualsMap2(Map expMap, + Map actMap) { + System.out.println("*** Comparing Map expMap and Map actMap for equality ***"); + System.out.println("Expected: " + toStringMap(expMap)); + System.out.println("Actual: " + toStringMap(actMap)); + System.out.println("Map expMap size should equal Map actMap size"); + if (expMap.size() != actMap.size()) { + System.err.println("Map sizes are not equal: expMap size " + expMap.size() + + ", actMap size " + actMap.size()); + return false; + } else { + System.out.println("Map sizes are equal with size of " + expMap.size()); + } + for (Map.Entry entry : expMap.entrySet()) { + String key = entry.getKey(); + if (actMap.containsKey(key)) { + if (expMap.get(key) != null && actMap.get(key) != null) { + if (!expMap.get(key).equals(actMap.get(key))) { + System.err.println("key=" + key + ", expMap value " + expMap.get(key) + + " does not equal actMap value " + actMap.get(key)); + return false; + } + } + } else { + System.err.println("actMap does not contain key " + key); + return false; + } + } + System.out.println("Maps expMap and actMap are equal."); + return true; + } + + /********************************************************************************* + * void dumpList(List list, String msg) + *********************************************************************************/ + public static void dumpList(List list, String msg) { + System.out.println("*** Beg: Dumping List contents ***"); + if (msg != null) + System.out.println("*** Message: " + msg); + Iterator iter = list.iterator(); + System.out.println("List: ["); + while (iter.hasNext()) { + System.out.println("" + toStringJsonValue(iter.next())); + } + System.out.println("]"); + System.out.println("*** End: Dumping List contents ***"); + } + + /********************************************************************************* + * void dumpList(List list) + *********************************************************************************/ + public static void dumpList(List list) { + dumpList(list, null); + } + + /********************************************************************************* + * String toStringList(List list) + *********************************************************************************/ + public static String toStringList(List list) { + Iterator iter = list.iterator(); + StringBuilder sb = new StringBuilder(); + sb.append("List: ["); + String comma = ""; + while (iter.hasNext()) { + sb.append(comma + toStringJsonValue(iter.next())); + if (comma.equals("")) + comma = ","; + } + sb.append("]"); + return sb.toString(); + } + + /********************************************************************************* + * boolean assertEqualsList(ListexpList, ListactList) + *********************************************************************************/ + public static boolean assertEqualsList(List expList, + List actList) { + if (actList.equals(expList)) { + System.out.println("Lists are equal - match (Success)"); + System.out.println("Expected: " + toStringList(expList)); + System.out.println("Actual: " + toStringList(actList)); + return true; + } else { + System.out.println("Lists are not equal - mismatch (Failure)"); + System.err.println("Expected: " + toStringList(expList)); + System.err.println("Actual: " + toStringList(actList)); + return false; + } + } + + /********************************************************************************* + * assertEqualsList2 + *********************************************************************************/ + public static boolean assertEqualsList2(List expList, + List actList) { + System.out.println( + "*** Comparing contents of List expList and List actList for equality ***"); + System.out.println("Expected: " + toStringList(expList)); + System.out.println("Actual: " + toStringList(actList)); + System.out.println("List expList size should equal List actList size"); + if (expList.size() != actList.size()) { + System.err.println("List sizes are not equal: expList size " + expList.size() + + ", actList size " + actList.size()); + return false; + } + System.out.println("Compare Lists (all elements should MATCH)"); + for (int i = 0; i < expList.size(); i++) { + if (expList.get(i).equals(actList.get(i))) { + System.out.println("expList element " + i + " matches actList element " + i); + } else { + System.err.println( + "expList element " + i + " does not match actList element " + i); + System.err.println("expList[" + i + "]=" + expList.get(i)); + System.err.println("actList[" + i + "]=" + actList.get(i)); + return false; + } + } + System.out.println("Lists are equal (Success)"); + return true; + } + + /********************************************************************************* + * void dumpIterator(Iterator iterator, String msg) + *********************************************************************************/ + public static void dumpIterator(Iterator iterator, String msg) { + System.out.println("*** Beg: Dumping Iterator contents ***"); + if (msg != null) + System.out.println("*** Message: " + msg); + System.out.println("Iter: ["); + while (iterator.hasNext()) { + System.out.println("" + toStringJsonValue(iterator.next())); + } + System.out.println("]"); + System.out.println("*** End: Dumping Iterator contents ***"); + } + + /********************************************************************************* + * void dumpIterator(Iterator iterator) + *********************************************************************************/ + public static void dumpIterator(Iterator iterator) { + dumpIterator(iterator, null); + } + + /********************************************************************************* + * String toStringIterator(Iterator iterator) + *********************************************************************************/ + public static String toStringIterator(Iterator iter) { + StringBuilder sb = new StringBuilder(); + sb.append("Iterator: ["); + while (iter.hasNext()) { + sb.append(toStringJsonValue(iter.next())); + if (iter.hasNext()) + sb.append(","); + } + sb.append("]"); + return sb.toString(); + } + + /********************************************************************************* + * boolean assertEqualsIterator(IteratorexpIt, + * IteratoractIt) + *********************************************************************************/ + public static boolean assertEqualsIterator(Iterator expIt, + Iterator actIt) { + boolean pass = true; + + System.out.println( + "*** Comparing contents of Iterator expIt and Iterator actIt for equality ***"); + int i = 0; + while (expIt.hasNext()) { + if (!actIt.hasNext()) { + System.err.println( + "Iterator expIt contains more elements than Iterator actIt"); + return false; + } + ++i; + JsonValue value1 = expIt.next(); + JsonValue value2 = actIt.next(); + if (assertEqualsJsonValues(value1, value2)) { + System.out.println("Iterator expIt element " + i + + " matches Iterator actIt element " + i); + } else { + System.err.println("Iterator expIt element " + i + + " does not match Iterator actIt element " + i); + pass = false; + } + } + if (actIt.hasNext()) { + System.err.println("Iterator actIt contains more elements than Iterator expIt"); + return false; + } + if (pass) + System.out.println("Iterators are equal (Success)"); + else + System.out.println("Iterators are not equal (Failure)"); + return pass; + } + + /********************************************************************************* + * boolean assertEqualsEmptyArrayList(List actual) + *********************************************************************************/ + public static boolean assertEqualsEmptyArrayList(List actual) { + if (actual.isEmpty()) { + System.out.println("Array List is empty - expected"); + return true; + } else { + System.err.println("Array List is not empty - unexpected"); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsEmptyObjectMap(Map actual) + *********************************************************************************/ + public static boolean assertEqualsEmptyObjectMap( + Map actual) { + if (actual.isEmpty()) { + System.out.println("Object Map is empty - expected"); + return true; + } else { + System.err.println("Object Map is not empty - unexpected"); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsEmptyIterator(Map actual) + *********************************************************************************/ + public static boolean assertEqualsEmptyIterator(Iterator actual) { + if (!actual.hasNext()) { + System.out.println("Iterator is empty - expected"); + return true; + } else { + System.err.println("Iterator is not empty - unexpected"); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsJsonText(String expected, String actual) + *********************************************************************************/ + public static boolean assertEqualsJsonText(String expected, String actual) { + if (actual.equals(expected)) { + System.out.println("JSON text match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("JSON text mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsJsonArrays(JsonArray expected, JsonArray actual) + *********************************************************************************/ + public static boolean assertEqualsJsonArrays(JsonArray expected, + JsonArray actual) { + if (actual.equals(expected)) { + System.out.println("JsonArray match"); + System.out.println("Expected: " + toStringJsonArray(expected)); + System.out.println("Actual: " + toStringJsonArray(actual)); + return true; + } else { + System.err.println("JsonArray mismatch"); + System.err.println("Expected: " + toStringJsonArray(expected)); + System.err.println("Actual: " + toStringJsonArray(actual)); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsJsonObjects(JsonObject expected, JsonObject actual) + *********************************************************************************/ + public static boolean assertEqualsJsonObjects(JsonObject expected, + JsonObject actual) { + if (actual.equals(expected)) { + System.out.println("JsonObject match"); + System.out.println("Expected: " + toStringJsonObject(expected)); + System.out.println("Actual: " + toStringJsonObject(actual)); + return true; + } else { + System.err.println("JsonObject mismatch"); + System.err.println("Expected: " + toStringJsonObject(expected)); + System.err.println("Actual: " + toStringJsonObject(actual)); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsJsonNumbers(JsonNumber expected, JsonNumber actual) + *********************************************************************************/ + public static boolean assertEqualsJsonNumbers(JsonNumber expected, + JsonNumber actual) { + boolean pass = true; + + if (actual.equals(expected)) { + System.out.println("JsonNumber match"); + System.out.println("Expected: " + toStringJsonNumber(expected)); + System.out.println("Actual: " + toStringJsonNumber(actual)); + return true; + } else { + System.err.println("JsonNumber mismatch"); + System.err.println("Expected: " + toStringJsonNumber(expected)); + System.err.println("Actual: " + toStringJsonNumber(actual)); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsJsonStrings(JsonString expected, JsonString actual) + *********************************************************************************/ + public static boolean assertEqualsJsonStrings(JsonString expected, + JsonString actual) { + boolean pass = true; + + if (actual.equals(expected)) { + System.out.println("JsonString match"); + System.out.println("Expected: " + toStringJsonString(expected)); + System.out.println("Actual: " + toStringJsonString(actual)); + return true; + } else { + System.err.println("JsonString mismatch"); + System.err.println("Expected: " + toStringJsonString(expected)); + System.err.println("Actual: " + toStringJsonString(actual)); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsJsonValues(JsonValue expected, JsonValue actual) + *********************************************************************************/ + public static boolean assertEqualsJsonValues(JsonValue expected, + JsonValue actual) { + boolean pass = true; + + // Comparing JsonNumbers + if (expected instanceof JsonNumber) { + if (!(actual instanceof JsonNumber)) { + System.err.println("expected type does not match actual type"); + System.err.println("expected=" + toStringJsonValue(expected)); + System.err.println("actual= " + toStringJsonValue(actual)); + pass = false; + } else { + pass = assertEqualsJsonNumbers((JsonNumber) expected, + (JsonNumber) actual); + } + // Comparing JsonStrings + } else if (expected instanceof JsonString) { + if (!(actual instanceof JsonString)) { + System.err.println("expected type does not match actual type"); + System.err.println("expected=" + toStringJsonValue(expected)); + System.err.println("actual= " + toStringJsonValue(actual)); + pass = false; + } else { + pass = assertEqualsJsonStrings((JsonString) expected, + (JsonString) actual); + } + // Comparing JsonArrays + } else if (expected instanceof JsonArray) { + if (!(actual instanceof JsonArray)) { + System.err.println("expected type does not match actual type"); + System.err.println("expected=" + toStringJsonValue(expected)); + System.err.println("actual= " + toStringJsonValue(actual)); + pass = false; + } else { + pass = assertEqualsJsonArrays((JsonArray) expected, (JsonArray) actual); + } + // Comparing JsonObjects + } else if (expected instanceof JsonObject) { + if (!(actual instanceof JsonObject)) { + System.err.println("expected type does not match actual type"); + System.err.println("expected=" + toStringJsonValue(expected)); + System.err.println("actual= " + toStringJsonValue(actual)); + pass = false; + } else { + pass = assertEqualsJsonObjects((JsonObject) expected, + (JsonObject) actual); + } + // Comparing JsonValues + } else if (expected.equals(actual)) { + System.out.println("expected matches actual"); + System.out.println("expected=" + toStringJsonValue(expected)); + System.out.println("actual= " + toStringJsonValue(actual)); + } else { + System.err.println("expected does not match actual"); + System.err.println("expected=" + toStringJsonValue(expected)); + System.err.println("actual= " + toStringJsonValue(actual)); + pass = false; + } + return pass; + } + + /********************************************************************************* + * boolean assertEqualsJsonValueType(JsonValue.ValueType + * expected,JsonValue.ValueType actual) + *********************************************************************************/ + public static boolean assertEqualsJsonValueType(JsonValue.ValueType expected, + JsonValue.ValueType actual) { + if (actual == expected) { + System.out.println("JsonValue.ValueType match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("JsonValue.ValueType mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsJsonNumberType(boolean expected,boolean actual) + *********************************************************************************/ + public static boolean assertEqualsJsonNumberType(boolean expected, + boolean actual) { + if (actual == expected) { + System.out.println("Json NumberType match"); + System.out.println("Expected: " + toStringJsonNumberType(expected)); + System.out.println("Actual: " + toStringJsonNumberType(actual)); + return true; + } else { + System.err.println("Json NumberType mismatch"); + System.err.println("Expected: " + toStringJsonNumberType(expected)); + System.err.println("Actual: " + toStringJsonNumberType(actual)); + return false; + } + } + + /********************************************************************************* + * boolean assertEqualsJsonNumberTypes(boolean expected[],boolean actual) + *********************************************************************************/ + public static boolean assertEqualsJsonNumberTypes(boolean expected[], + boolean actual) { + for (int i = 0; i < expected.length; i++) { + if (actual == expected[i]) { + System.out.println("Json NumberType match"); + System.out.println("Expected: " + toStringJsonNumberType(expected[i])); + System.out.println("Actual: " + toStringJsonNumberType(actual)); + return true; + } + } + System.err.println("Json NumberType mismatch"); + System.err.println("Expected: " + toStringJsonNumberTypes(expected)); + System.err.println("Actual: " + toStringJsonNumberType(actual)); + return false; + } + + /********************************************************************************* + * String toStringJsonNumberType(boolean numberType) + *********************************************************************************/ + public static String toStringJsonNumberType(boolean numberType) { + if (numberType == INTEGRAL) + return "INTEGRAL"; + else + return "NON_INTEGRAL"; + } + + /********************************************************************************* + * String toStringJsonNumberTypes(boolean expected[]) + *********************************************************************************/ + public static String toStringJsonNumberTypes(boolean expected[]) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < expected.length; i++) { + sb.append("" + toStringJsonNumberType(expected[i])); + if (i + 1 < expected.length) + sb.append("|"); + } + return sb.toString(); + } + + /********************************************************************************* + * boolean assertEquals(Object, Object) + *********************************************************************************/ + public static boolean assertEquals(Object expected, Object actual) { + if (actual.equals(expected)) { + System.out.println("Object match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("Object mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(boolean, boolean) + *********************************************************************************/ + public static boolean assertEquals(boolean expected, boolean actual) { + if (actual == expected) { + System.out.println("boolean match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("boolean mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(short, short) + *********************************************************************************/ + public static boolean assertEquals(short expected, short actual) { + if (actual == expected) { + System.out.println("short match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("short mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(int, int) + *********************************************************************************/ + public static boolean assertEquals(int expected, int actual) { + if (actual == expected) { + System.out.println("int match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("int mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(long, long) + *********************************************************************************/ + public static boolean assertEquals(long expected, long actual) { + if (actual == expected) { + System.out.println("long match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("long mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(float, float) + *********************************************************************************/ + public static boolean assertEquals(float expected, float actual) { + if (actual == expected) { + System.out.println("float match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("float mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(double, double) + *********************************************************************************/ + public static boolean assertEquals(double expected, double actual) { + if (actual == expected) { + System.out.println("double match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("double mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(BigDecimal, BigDecimal) + *********************************************************************************/ + public static boolean assertEquals(BigDecimal expected, BigDecimal actual) { + if (actual.equals(expected)) { + System.out.println("BigDecimal match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("BigDecimal mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(BigInteger, BigInteger) + *********************************************************************************/ + public static boolean assertEquals(BigInteger expected, BigInteger actual) { + if (actual.equals(expected)) { + System.out.println("BigInteger match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("BigInteger mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(String, String) + *********************************************************************************/ + public static boolean assertEquals(String expected, String actual) { + if (actual.equals(expected)) { + System.out.println("String match"); + System.out.println("Expected: " + expected); + System.out.println("Actual: " + actual); + return true; + } else { + System.err.println("String mismatch"); + System.err.println("Expected: " + expected); + System.err.println("Actual: " + actual); + return false; + } + } + + /********************************************************************************* + * boolean assertEquals(JsonValue, JsonValue) + *********************************************************************************/ + public static boolean assertEquals(JsonValue expected, JsonValue actual) { + if (actual.equals(expected)) { + System.out.println("JsonValue match"); + System.out.println("Expected: " + toStringJsonValue(expected)); + System.out.println("Actual: " + toStringJsonValue(actual)); + return true; + } else { + System.err.println("JsonValue mismatch"); + System.err.println("Expected: " + toStringJsonValue(expected)); + System.err.println("Actual: " + toStringJsonValue(actual)); + return false; + } + } + + /********************************************************************************* + * String getNumberTypeString(boolean numberType) + *********************************************************************************/ + public static String getNumberTypeString(boolean numberType) { + if (numberType == INTEGRAL) + return "INTEGRAL"; + else + return "NON_INTEGRAL"; + } + + /********************************************************************************* + * boolean getNumberType(String numberType) + *********************************************************************************/ + public static boolean getNumberType(String numberType) { + if (numberType.equals("INTEGRAL")) + return INTEGRAL; + else + return NON_INTEGRAL; + } + + /********************************************************************************* + * String getValueTypeString(JsonValue.ValueType valueType) + *********************************************************************************/ + public static String getValueTypeString(JsonValue.ValueType valueType) { + switch (valueType) { + case ARRAY: + return "ARRAY"; + case FALSE: + return "FALSE"; + case NULL: + return "NULL"; + case NUMBER: + return "NUMBER"; + case OBJECT: + return "OBJECT"; + case STRING: + return "STRING"; + case TRUE: + return "TRUE"; + default: + return null; + } + } + + /********************************************************************************* + * JsonValue.ValueType getValueType(String valueType) + *********************************************************************************/ + public static JsonValue.ValueType getValueType(String valueType) { + if (valueType.equals("ARRAY")) + return JsonValue.ValueType.ARRAY; + if (valueType.equals("FALSE")) + return JsonValue.ValueType.FALSE; + if (valueType.equals("NULL")) + return JsonValue.ValueType.NULL; + if (valueType.equals("NUMBER")) + return JsonValue.ValueType.NUMBER; + if (valueType.equals("OBJECT")) + return JsonValue.ValueType.OBJECT; + if (valueType.equals("STRING")) + return JsonValue.ValueType.STRING; + if (valueType.equals("TRUE")) + return JsonValue.ValueType.TRUE; + else + return null; + } + + /********************************************************************************* + * void dumpEventType(JsonParser.Event eventType) + *********************************************************************************/ + public static void dumpEventType(JsonParser.Event eventType) { + System.out.println("JsonParser.Event=" + eventType); + } + + /********************************************************************************* + * getEventTypeString(JsonParser.Event eventType) + *********************************************************************************/ + public static String getEventTypeString(JsonParser.Event eventType) { + switch (eventType) { + case START_ARRAY: + return "START_ARRAY"; + case START_OBJECT: + return "START_OBJECT"; + case KEY_NAME: + return "KEY_NAME"; + case VALUE_STRING: + return "VALUE_STRING"; + case VALUE_NUMBER: + return "VALUE_NUMBER"; + case VALUE_TRUE: + return "VALUE_TRUE"; + case VALUE_FALSE: + return "VALUE_FALSE"; + case VALUE_NULL: + return "VALUE_NULL"; + case END_OBJECT: + return "END_OBJECT"; + case END_ARRAY: + return "END_ARRAY"; + default: + return null; + } + } + + /********************************************************************************* + * JsonParser.Event getEventType(String eventType) + *********************************************************************************/ + public static JsonParser.Event getEventType(String eventType) { + if (eventType.equals("START_ARRAY")) + return JsonParser.Event.START_ARRAY; + if (eventType.equals("START_OBJECT")) + return JsonParser.Event.START_OBJECT; + if (eventType.equals("KEY_NAME")) + return JsonParser.Event.KEY_NAME; + if (eventType.equals("VALUE_STRING")) + return JsonParser.Event.VALUE_STRING; + if (eventType.equals("VALUE_NUMBER")) + return JsonParser.Event.VALUE_NUMBER; + if (eventType.equals("VALUE_TRUE")) + return JsonParser.Event.VALUE_TRUE; + if (eventType.equals("VALUE_FALSE")) + return JsonParser.Event.VALUE_FALSE; + if (eventType.equals("VALUE_NULL")) + return JsonParser.Event.VALUE_NULL; + if (eventType.equals("END_OBJECT")) + return JsonParser.Event.END_OBJECT; + if (eventType.equals("END_ARRAY")) + return JsonParser.Event.END_ARRAY; + else + return null; + } + + /********************************************************************************* + * String getConfigName(String configValue) + *********************************************************************************/ + public static String getConfigName(String configValue) { + if (configValue.equals(JsonGenerator.PRETTY_PRINTING)) + return "JsonGenerator.PRETTY_PRINTING"; + else if (configValue.equals(JSONP_Util.FOO_CONFIG)) + return "JSONP_Util.FOO_CONFIG"; + else + return null; + } + + /********************************************************************************* + * String getConfigValue(String configProp) + *********************************************************************************/ + public static String getConfigValue(String configProp) { + if (configProp.equals("JsonGenerator.PRETTY_PRINING")) + return JsonGenerator.PRETTY_PRINTING; + else if (configProp.equals("JSONP_Util.FOO_CONFIG")) + return JSONP_Util.FOO_CONFIG; + else + return null; + } + + /********************************************************************************* + * void dumpConfigMap(Map map, String msg) + *********************************************************************************/ + public static void dumpConfigMap(Map map, String msg) { + System.out.println("*** Beg: Dumping Config Map contents ***"); + if (msg != null) + System.out.println("*** Message: " + msg); + for (Map.Entry entry : map.entrySet()) { + System.out.println("\"" + entry.getKey() + "\":" + entry.getValue()); + } + System.out.println("*** End: Dumping Config Map contents ***"); + } + + /********************************************************************************* + * void dumpConfigMap(Map map) + *********************************************************************************/ + public static void dumpConfigMap(Map map) { + dumpConfigMap(map, null); + } + + /********************************************************************************* + * boolean doConfigCheck(Map config, int expectedSize) + *********************************************************************************/ + public static boolean doConfigCheck(Map config, int expectedSize) { + return doConfigCheck(config, expectedSize, null); + } + + public static boolean doConfigCheck(Map config, int expectedSize, + String[] expectedProps) { + boolean pass = true; + dumpConfigMap(config); + System.out.println("Checking factory configuration property size"); + if (config.size() != expectedSize) { + System.err.println("Expecting no of properties=" + expectedSize + ", got=" + + config.size()); + pass = false; + } else { + System.out.println("Expecting no of properties=" + expectedSize + ", got=" + + config.size()); + } + if (expectedSize != 0 && expectedProps != null) { + System.out.println("Checking factory configuration property name and value"); + for (int i = 0; i < expectedProps.length; i++) { + if (config.containsKey(expectedProps[i])) { + System.out.println("Does contain key: " + expectedProps[i] + " - expected."); + if (!JSONP_Util.assertEquals(true, config.get(expectedProps[i]))) { + pass = false; + } + } else { + System.err.println( + "Does not contain key: " + expectedProps[i] + " - unexpected."); + pass = false; + } + } + } + return pass; + } + + /********************************************************************************* + * boolean isEmptyConfig(Map config) + *********************************************************************************/ + public boolean isEmptyConfig(Map config) { + System.out.println("isEmptyConfig"); + return config.isEmpty(); + } + + /********************************************************************************* + * Map getEmptyConfig() + *********************************************************************************/ + public static Map getEmptyConfig() { + System.out.println("getEmptyConfig"); + Map config = new HashMap(); + return config; + } + + /********************************************************************************* + * Map getPrettyPrintingConfig() + *********************************************************************************/ + public static Map getPrettyPrintingConfig() { + System.out.println("getPrettyPrintConfig"); + Map config = new HashMap(); + System.out.println("Added property: JsonGenerator.PRETTY_PRINTING"); + config.put(JsonGenerator.PRETTY_PRINTING, true); + return config; + } + + /********************************************************************************* + * Map getFooConfig() + *********************************************************************************/ + public static Map getFooConfig() { + System.out.println("getFooConfig"); + Map config = new HashMap(); + System.out.println("Added property: JSONP_Util.FOO_CONFIG"); + config.put(JSONP_Util.FOO_CONFIG, true); + return config; + } + + /********************************************************************************* + * Map getAllConfig() + *********************************************************************************/ + public static Map getAllConfig() { + System.out.println("getAllConfig"); + Map config = new HashMap(); + System.out.println("Added property: JsonGenerator.PRETTY_PRINTING"); + config.put(JsonGenerator.PRETTY_PRINTING, true); + System.out.println("Added property: JSONP_Util.FOO_CONFIG"); + config.put(JSONP_Util.FOO_CONFIG, true); + return config; + } + + /********************************************************************************* + * JsonObject createJsonObjectFromString(String jsonObjData) + *********************************************************************************/ + public static JsonObject createJsonObjectFromString(String jsonObjData) { + JsonReader reader = null; + JsonObject object = null; + try { + reader = Json.createReader(new StringReader(jsonObjData)); + object = reader.readObject(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (reader != null) + reader.close(); + } + return object; + } + + /********************************************************************************* + * JsonArray createJsonArrayFromString(String jsonArrData) + *********************************************************************************/ + public static JsonArray createJsonArrayFromString(String jsonArrData) { + JsonReader reader = null; + JsonArray array = null; + try { + reader = Json.createReader(new StringReader(jsonArrData)); + array = reader.readArray(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (reader != null) + reader.close(); + } + return array; + } + + /********************************************************************************* + * void writeJsonObjectFromString(JsonWriter writer, String jsonObjData) + *********************************************************************************/ + public static void writeJsonObjectFromString(JsonWriter writer, + String jsonObjData) { + try { + JsonObject jsonObject = createJsonObjectFromString(jsonObjData); + writer.writeObject(jsonObject); + writer.close(); + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + } + } + + /********************************************************************************* + * void writeJsonArrayFromString(JsonWriter writer, String jsonArrData) + *********************************************************************************/ + public static void writeJsonArrayFromString(JsonWriter writer, + String jsonArrData) { + try { + JsonArray jsonArray = createJsonArrayFromString(jsonArrData); + writer.writeArray(jsonArray); + writer.close(); + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + } + } + + /********************************************************************************* + * void testKeyStringValue(JsonParser parser, String name, String value) + *********************************************************************************/ + public static void testKeyStringValue(JsonParser parser, String name, + String value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.VALUE_STRING) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_STRING) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } + String keyvalue = parser.getString(); + if (!keyvalue.equals(value)) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testKeyIntegerValue(JsonParser parser, String name, int value) + *********************************************************************************/ + public static void testKeyIntegerValue(JsonParser parser, String name, + int value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.VALUE_NUMBER) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + int keyvalue = parser.getInt(); + if (keyvalue != value) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testKeyDoubleValue(JsonParser parser, String name, double value) + *********************************************************************************/ + public static void testKeyDoubleValue(JsonParser parser, String name, + double value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.VALUE_NUMBER) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + double keyvalue = parser.getBigDecimal().doubleValue(); + if (keyvalue != value) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testKeyLongValue(JsonParser parser, String name, long value) + *********************************************************************************/ + public static void testKeyLongValue(JsonParser parser, String name, + long value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.VALUE_NUMBER) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + long keyvalue = parser.getLong(); + if (keyvalue != value) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testKeyBigDecimalValue(JsonParser parser, String name, BigDecimal + * value) + *********************************************************************************/ + public static void testKeyBigDecimalValue(JsonParser parser, String name, + BigDecimal value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.VALUE_NUMBER) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + BigDecimal keyvalue = parser.getBigDecimal(); + if (keyvalue != value) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testKeyTrueValue(JsonParser parser, String name) + *********************************************************************************/ + public static void testKeyTrueValue(JsonParser parser, String name) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.VALUE_TRUE) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_TRUE) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + } + + /********************************************************************************* + * void testKeyFalseValue(JsonParser parser, String name) + *********************************************************************************/ + public static void testKeyFalseValue(JsonParser parser, String name) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.VALUE_FALSE) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_FALSE) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + } + + /********************************************************************************* + * void testKeyNullValue(JsonParser parser, String name) + *********************************************************************************/ + public static void testKeyNullValue(JsonParser parser, String name) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.VALUE_NULL) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NULL) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + } + + /********************************************************************************* + * void testKeyStartObjectValue(JsonParser parser, String name) + *********************************************************************************/ + public static void testKeyStartObjectValue(JsonParser parser, String name) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.START_OBJECT) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.START_OBJECT) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + } + + /********************************************************************************* + * void testKeyStartArrayValue(JsonParser parser, String name) + *********************************************************************************/ + public static void testKeyStartArrayValue(JsonParser parser, String name) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + + if (e != JsonParser.Event.KEY_NAME) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.KEY_NAME) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyname = parser.getString(); + if (!name.equals(keyname)) { + System.err.println("Expected keyname: " + name + ", got keyname: " + keyname); + parseErrs++; + } else { + System.out.println("Got expected keyname: " + keyname); + } + + if (!checkNextParserEvent(parser)) + return; + e = parser.next(); + if (e != JsonParser.Event.START_ARRAY) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.START_ARRAY) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + } + + /********************************************************************************* + * boolean checkNextParserEvent(JsonParser parser) + *********************************************************************************/ + public static boolean checkNextParserEvent(JsonParser parser) { + if (!parser.hasNext()) { + System.err.println("no next parser event found - unexpected"); + parseErrs++; + return false; + } else + return true; + } + + /********************************************************************************* + * JsonParser.Event getNextParserEvent(JsonParser parser) + *********************************************************************************/ + public static JsonParser.Event getNextParserEvent(JsonParser parser) { + if (parser.hasNext()) + return parser.next(); + else + return null; + } + + /********************************************************************************* + * JsonParser.Event getNextSpecificParserEvent(JsonParser parser, + * JsonParser.Event thisEvent) + *********************************************************************************/ + public static JsonParser.Event getNextSpecificParserEvent(JsonParser parser, + JsonParser.Event thisEvent) { + while (parser.hasNext()) { + JsonParser.Event event = parser.next(); + if (event == thisEvent) + return event; + } + return null; + } + + /********************************************************************************* + * void testEventType(JsonParser parser, JsonParser.Event expEvent) + *********************************************************************************/ + public static void testEventType(JsonParser parser, + JsonParser.Event expEvent) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + if (e != expEvent) { + System.err.println("Expected event: " + getEventTypeString(expEvent) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + } + + /********************************************************************************* + * void testStringValue(JsonParser parser, String value) + *********************************************************************************/ + public static void testStringValue(JsonParser parser, String value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + if (e != JsonParser.Event.VALUE_STRING) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_STRING) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + String keyvalue = parser.getString(); + if (!keyvalue.equals(value)) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testIntegerValue(JsonParser parser, int value) + *********************************************************************************/ + public static void testIntegerValue(JsonParser parser, int value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + if (e != JsonParser.Event.VALUE_NUMBER) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + int keyvalue = parser.getInt(); + if (keyvalue != value) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testDoubleValue(JsonParser parser, double value) + *********************************************************************************/ + public static void testDoubleValue(JsonParser parser, double value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + if (e != JsonParser.Event.VALUE_NUMBER) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + double keyvalue = parser.getBigDecimal().doubleValue(); + if (keyvalue != value) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testLongValue(JsonParser parser, long value) + *********************************************************************************/ + public static void testLongValue(JsonParser parser, long value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + if (e != JsonParser.Event.VALUE_NUMBER) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + long keyvalue = parser.getLong(); + if (keyvalue != value) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testBigDecimalValue(JsonParser parser, BigDecimal value) + *********************************************************************************/ + public static void testBigDecimalValue(JsonParser parser, BigDecimal value) { + if (!checkNextParserEvent(parser)) + return; + JsonParser.Event e = parser.next(); + if (e != JsonParser.Event.VALUE_NUMBER) { + System.err.println( + "Expected event: " + getEventTypeString(JsonParser.Event.VALUE_NUMBER) + + ", got event: " + getEventTypeString(e)); + parseErrs++; + } else { + System.out.println("Got expected event: " + getEventTypeString(e)); + } + BigDecimal keyvalue = parser.getBigDecimal(); + if (keyvalue != value) { + System.err.println( + "Expected keyvalue: " + value + ", got keyvalue: " + keyvalue); + parseErrs++; + } else { + System.out.println("Got expected keyvalue: " + keyvalue); + } + } + + /********************************************************************************* + * void testTrueValue(JsonParser parser, JsonParser.Event expEvent) + *********************************************************************************/ + public static void testTrueValue(JsonParser parser, + JsonParser.Event expEvent) { + testEventType(parser, expEvent); + } + + /********************************************************************************* + * void testFalseValue(JsonParser parser, JsonParser.Event expEvent) + *********************************************************************************/ + public static void testFalseValue(JsonParser parser, + JsonParser.Event expEvent) { + testEventType(parser, expEvent); + } + + /********************************************************************************* + * void testNullValue(JsonParser parser, JsonParser.Event expEvent) + *********************************************************************************/ + public static void testNullValue(JsonParser parser, + JsonParser.Event expEvent) { + testEventType(parser, expEvent); + } + + /********************************************************************************* + * resetParseErrs() + *********************************************************************************/ + public static void resetParseErrs() { + parseErrs = 0; + } + + /********************************************************************************* + * int getParseErrs() + *********************************************************************************/ + public static int getParseErrs() { + return parseErrs; + } + + /********************************************************************************* + * String convertUnicodeCharToString(Char c) + * + * Convert unicode to string value of form U+NNNN where NNNN are 4 hex digits + * + * Use a binary or with hex value '0x10000' when converting unicode char to + * hex string and remove 1st char to get the 4 hex digits we need. + *********************************************************************************/ + public static String convertUnicodeCharToString(char c) { + return "\\u" + Integer.toHexString((int) c | 0x10000).substring(1); + } + + /********************************************************************************* + * boolean isUnicodeControlChar(Char c) + * + * The following unicode control chars: + * + * U+0000 - U+001F and U+007F U+0080 - U+009F + *********************************************************************************/ + public static boolean isUnicodeControlChar(char c) { + + if ((c >= '\u0000' && c <= '\u001F') || (c == '\u007F') + || (c >= '\u0080' && c <= '\u009F')) + return true; + else + return false; + } + + /********************************************************************************* + * void writeStringToFile(String string, String file, String encoding) + *********************************************************************************/ + public static void writeStringToFile(String string, String file, + String encoding) { + try { + FileOutputStream fos = new FileOutputStream(file); + Writer out = new OutputStreamWriter(fos, encoding); + out.write(string); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /********************************************************************************* + * String readStringFromFile(String file, String encoding) + *********************************************************************************/ + public static String readStringFromFile(String file, String encoding) { + StringBuffer buffer = new StringBuffer(); + try { + FileInputStream fis = new FileInputStream(file); + InputStreamReader isr = new InputStreamReader(fis, encoding); + Reader in = new BufferedReader(isr); + int ch; + while ((ch = in.read()) > -1) { + buffer.append((char) ch); + } + in.close(); + return buffer.toString(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + /********************************************************************************* + * void writeStringToStream(String string, OutputStream os, String encoding) + *********************************************************************************/ + public static void writeStringToStream(String string, OutputStream os, + String encoding) { + try { + Writer out = new OutputStreamWriter(os, encoding); + out.write(string); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /********************************************************************************* + * String readStringFromStream(InputStream is, String encoding) + *********************************************************************************/ + public static String readStringFromStream(InputStream is, String encoding) { + StringBuffer buffer = new StringBuffer(); + try { + InputStreamReader isr = new InputStreamReader(is, encoding); + Reader in = new BufferedReader(isr); + int ch; + while ((ch = in.read()) > -1) { + buffer.append((char) ch); + } + in.close(); + return buffer.toString(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + /********************************************************************************* + * void writeStringToFile(String string, String file, Charset charset) + *********************************************************************************/ + public static void writeStringToFile(String string, String file, + Charset charset) { + try { + FileOutputStream fos = new FileOutputStream(file); + Writer out = new OutputStreamWriter(fos, charset); + out.write(string); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /********************************************************************************* + * String readStringFromFile(String file, Charset charset) + *********************************************************************************/ + public static String readStringFromFile(String file, Charset charset) { + StringBuffer buffer = new StringBuffer(); + try { + FileInputStream fis = new FileInputStream(file); + InputStreamReader isr = new InputStreamReader(fis, charset); + Reader in = new BufferedReader(isr); + int ch; + while ((ch = in.read()) > -1) { + buffer.append((char) ch); + } + in.close(); + return buffer.toString(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + /********************************************************************************* + * void writeStringToStream(String string, OutputStream os, Charset charset) + *********************************************************************************/ + public static void writeStringToStream(String string, OutputStream os, + Charset charset) { + try { + Writer out = new OutputStreamWriter(os, charset); + out.write(string); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /********************************************************************************* + * String readStringFromStream(InputStream is, Charset charset) + *********************************************************************************/ + public static String readStringFromStream(InputStream is, Charset charset) { + StringBuffer buffer = new StringBuffer(); + try { + InputStreamReader isr = new InputStreamReader(is, charset); + Reader in = new BufferedReader(isr); + int ch; + while ((ch = in.read()) > -1) { + buffer.append((char) ch); + } + in.close(); + return buffer.toString(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + /********************************************************************************* + * Charset getCharset(String encoding) + *********************************************************************************/ + public static Charset getCharset(String encoding) { + Charset cs = null; + + try { + cs = Charset.forName(encoding); + } catch (Exception e) { + e.printStackTrace(); + } + return cs; + } + + /********************************************************************************* + * void dumpLocation(JsonLocation location) + *********************************************************************************/ + public static void dumpLocation(JsonLocation location) { + if (location != null) { + System.out.println("JsonLocation info: lineNumber=" + location.getLineNumber() + + ", columnNumber=" + location.getColumnNumber() + + ", streamOffset=" + location.getStreamOffset()); + } else { + System.out.println("JsonLocation is null - no location info"); + } + } + + /********************************************************************************* + * void dumpLocation(JsonParser parser) + *********************************************************************************/ + public static void dumpLocation(JsonParser parser) { + dumpLocation(parser.getLocation()); + } + + /********************************************************************************* + * boolean assertEquals(JsonLocation, JsonLocation) + *********************************************************************************/ + public static boolean assertEquals(JsonLocation expLoc, JsonLocation actLoc) { + if (expLoc.getLineNumber() == actLoc.getLineNumber() + && expLoc.getColumnNumber() == actLoc.getColumnNumber() + && expLoc.getStreamOffset() == actLoc.getStreamOffset()) { + System.out.println("JsonLocations equal - match (Success)"); + System.out.println( + "Expected: JsonLocation info: lineNumber=" + expLoc.getLineNumber() + + ", columnNumber=" + expLoc.getColumnNumber() + ", streamOffset=" + + expLoc.getStreamOffset()); + System.out.println( + "Actual: JsonLocation info: lineNumber=" + actLoc.getLineNumber() + + ", columnNumber=" + actLoc.getColumnNumber() + ", streamOffset=" + + actLoc.getStreamOffset()); + return true; + } else { + System.err.println("JsonLocations not equal - mismatch (Failure)"); + System.err.println( + "Expected: JsonLocation info: lineNumber=" + expLoc.getLineNumber() + + ", columnNumber=" + expLoc.getColumnNumber() + ", streamOffset=" + + expLoc.getStreamOffset()); + System.err.println( + "Actual: JsonLocation info: lineNumber=" + actLoc.getLineNumber() + + ", columnNumber=" + actLoc.getColumnNumber() + ", streamOffset=" + + actLoc.getStreamOffset()); + return false; + } + } + + /********************************************************************************* + * void addFileToClassPath(String s) + *********************************************************************************/ + public static void addFileToClassPath(String s) throws Exception { + addFileToClassPath(new File(s)); + } + + /********************************************************************************* + * void addFileToClassPath(File f) + *********************************************************************************/ + public static void addFileToClassPath(File f) throws Exception { + addURLToClassPath((f.toURI()).toURL()); + } + + /********************************************************************************* + * void addURLToClassPath(URL url) + *********************************************************************************/ + public static void addURLToClassPath(URL url) throws Exception { + System.out.println("addURLToClassPath-> " + url.toString()); + URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader + .getSystemClassLoader(); + try { + Class urlClassLoaderClass = URLClassLoader.class; + Method method = urlClassLoaderClass.getDeclaredMethod("addURL", + new Class[] { URL.class }); + method.setAccessible(true); + method.invoke(urlClassLoader, new Object[] { url }); + } catch (Throwable t) { + t.printStackTrace(); + throw new IOException("Error, could not add URL to system classloader"); + } + } + + /********************************************************************************* + * JsonArray buildJsonArrayFooBar + *********************************************************************************/ + public static JsonArray buildJsonArrayFooBar() { + try { + JsonArray jsonArray = Json.createArrayBuilder().add("foo").add("bar") + .build(); + return jsonArray; + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + return null; + } + } + + public static final String JSONARRAYFOOBAR = "[\"foo\",\"bar\"]"; + + /********************************************************************************* + * JsonObject buildJsonObjectFooBar() + *********************************************************************************/ + public static JsonObject buildJsonObjectFooBar() { + try { + JsonObject jsonObject = Json.createObjectBuilder().add("foo", "bar") + .build(); + return jsonObject; + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + return null; + } + } + + public static final String JSONOBJECTFOOBAR = "{\"foo\":\"bar\"}"; + + /********************************************************************************* + * JsonObject createSampleJsonObject() + * + * Assertion ids covered: 400/401/403/404/406/408/409 + *********************************************************************************/ + public static JsonObject createSampleJsonObject() throws Exception { + JsonObject object = Json.createObjectBuilder().add("firstName", "John") + .add("lastName", "Smith").add("age", 25).add("elderly", JsonValue.FALSE) + .add("patriot", JsonValue.TRUE) + .add("address", + Json.createObjectBuilder().add("streetAddress", "21 2nd Street") + .add("city", "New York").add("state", "NY") + .add("postalCode", "10021")) + .add("phoneNumber", + Json.createArrayBuilder() + .add(Json.createObjectBuilder().add("type", "home") + .add("number", "212 555-1234")) + .add(Json.createObjectBuilder().add("type", "cell") + .add("number", "646 555-4567"))) + .add("objectOfFooBar", + Json.createObjectBuilder() + .add("objectFooBar", buildJsonObjectFooBar()) + .add("arrayFooBar", buildJsonArrayFooBar())) + .add("arrayOfFooBar", Json.createArrayBuilder() + .add(buildJsonObjectFooBar()).add(buildJsonArrayFooBar())) + .build(); + return object; + } + + /********************************************************************************* + * EXPECTED_SAMPLEJSONOBJECT_TEXT Constant defining expected Json text output + * of above sample JsonObject + *********************************************************************************/ + public final static String EXPECTED_SAMPLEJSONOBJECT_TEXT = "{\"firstName\":\"John\",\"lastName\":\"Smith\",\"age\":25,\"elderly\":false,\"patriot\":true," + + "\"address\":{\"streetAddress\":\"21 2nd Street\",\"city\":\"New York\",\"state\":\"NY\"," + + "\"postalCode\":\"10021\"},\"phoneNumber\":[{\"type\":\"home\",\"number\":\"212 555-1234\"}," + + "{\"type\":\"cell\",\"number\":\"646 555-4567\"}],\"objectOfFooBar\":{\"objectFooBar\":" + + "{\"foo\":\"bar\"},\"arrayFooBar\":[\"foo\",\"bar\"]},\"arrayOfFooBar\":[{\"foo\":\"bar\"}," + + "[\"foo\",\"bar\"]]}"; + + /********************************************************************************* + * JsonObject createSampleJsonObject2() + *********************************************************************************/ + public static JsonObject createSampleJsonObject2() throws Exception { + JsonObject object = Json.createObjectBuilder().add("firstName", "John") + .add("lastName", "Smith").add("age", 25).add("elderly", JsonValue.FALSE) + .add("patriot", JsonValue.TRUE) + .add("address", + Json.createObjectBuilder().add("streetAddress", "21 2nd Street") + .add("city", "New York").add("state", "NY") + .add("postalCode", "10021")) + .add("phoneNumber", + Json.createArrayBuilder() + .add(Json.createObjectBuilder().add("type", "home") + .add("number", "212 555-1234")) + .add(Json.createObjectBuilder().add("type", "cell") + .add("number", "535 444-1234"))) + .build(); + return object; + } + + /********************************************************************************* + * JsonArray createSampleJsonArray() + * + * Assertion ids covered: 400/401/402/403/404/406/409 + *********************************************************************************/ + public static JsonArray createSampleJsonArray() throws Exception { // Indices + JsonArray array = Json.createArrayBuilder().add(Json.createObjectBuilder() // 0 + .add("name1", "value1").add("name2", "value2")).add(JsonValue.TRUE) + .add(JsonValue.FALSE).add(JsonValue.NULL) // 1,2,3 + .add(100).add(200L).add("string") // 4,5,6 + .add(BigDecimal.valueOf(123456789)).add(new BigInteger("123456789"))// 7,8 + .add(Json.createObjectBuilder() // 9 + .add("name3", "value3").add("name4", "value4")) + .add(true).add(false).addNull() // 10,11,12 + .add(Json.createArrayBuilder() // 13 + .add(2).add(4)) + .add(Json.createObjectBuilder() // 14 + .add("objectFooBar", buildJsonObjectFooBar()) + .add("arrayFooBar", buildJsonArrayFooBar())) + .add(Json.createArrayBuilder() // 15 + .add(buildJsonObjectFooBar()).add(buildJsonArrayFooBar())) + .build(); + return array; + } + + /********************************************************************************* + * EXPECTED_SAMPLEJSONARRAY_TEXT Constant defining expected Json text output + * of above sample JsonArray + *********************************************************************************/ + public final static String EXPECTED_SAMPLEJSONARRAY_TEXT = "[{\"name1\":\"value1\",\"name2\":\"value2\"},true,false,null,100,200,\"string\",123456789,123456789," + + "{\"name3\":\"value3\",\"name4\":\"value4\"},true,false,null,[2,4],{\"objectFooBar\":" + + "{\"foo\":\"bar\"},\"arrayFooBar\":[\"foo\",\"bar\"]},[{\"foo\":\"bar\"},[\"foo\",\"bar\"]]]"; + + /********************************************************************************* + * JsonArray createSampleJsonArray2() + *********************************************************************************/ + public static JsonArray createSampleJsonArray2() throws Exception { // Indices + JsonArray array = Json.createArrayBuilder().add(Json.createObjectBuilder() // 0 + .add("name1", "value1").add("name2", "value2")).add(JsonValue.TRUE) + .add(JsonValue.FALSE).add(JsonValue.NULL) // 1,2,3 + .add(Integer.MAX_VALUE).add(Long.MAX_VALUE).add("string") // 4,5,6 + .add(Json.createObjectBuilder() // 7 + .add("name3", "value3").add("name4", "value4")) + .add(true).add(false).addNull() // 8,9,10 + .add(Json.createArrayBuilder() // 11 + .add(1).add(3)) + .build(); + return array; + } +} diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyBufferedInputStream.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyBufferedInputStream.java new file mode 100644 index 00000000..7e59aaf5 --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyBufferedInputStream.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.common; + + +import java.io.*; + +// A wrapper class to BufferedInputStream class used to inject IOException errors +// when the throwIOException instance variable is set. All methods delegate +// to the parent super class and check whether or not to throw an IOException +// before delegation. + +public class MyBufferedInputStream extends BufferedInputStream { + + private boolean throwIOException = false; + + public MyBufferedInputStream(InputStream in) { + super(in); + } + + public MyBufferedInputStream(InputStream in, int sz) { + super(in, sz); + } + + public MyBufferedInputStream(InputStream in, boolean throwIOException) { + super(in); + this.throwIOException = throwIOException; + } + + private void checkToTripIOException() throws IOException { + if (throwIOException) { + System.out.println( + "MyBufferedInputStream->checkToTripIOException: *** tripping an IOException ***"); + throw new IOException("tripping an IOException"); + } + } + + public void setThrowIOException(boolean throwIOException) { + this.throwIOException = throwIOException; + } + + public int read() throws IOException { + checkToTripIOException(); + int c = super.read(); + return c; + } + + public int read(byte[] b, int off, int len) throws IOException { + checkToTripIOException(); + int c = super.read(b, off, len); + return c; + } + + public void close() throws IOException { + checkToTripIOException(); + super.close(); + } +} diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyBufferedReader.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyBufferedReader.java new file mode 100644 index 00000000..00c5145f --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyBufferedReader.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.common; + + +import java.io.*; + +// A wrapper class to BufferedReader class used to inject IOException errors +// when the throwIOException instance variable is set. All methods delegate +// to the parent super class and check whether or not to throw an IOException +// before delegation. + +public class MyBufferedReader extends BufferedReader { + + private boolean throwIOException; + + public MyBufferedReader(Reader in) { + super(in); + } + + public MyBufferedReader(Reader in, int sz) { + super(in, sz); + } + + public MyBufferedReader(Reader in, int sz, boolean throwIOException) { + super(in, sz); + this.throwIOException = throwIOException; + } + + private void checkToTripIOException() throws IOException { + if (throwIOException) { + System.out.println("*** tripping an IOException ***"); + throw new IOException("tripping an IOException"); + } + } + + public void setThrowIOException(boolean throwIOException) { + this.throwIOException = throwIOException; + } + + public int read() throws IOException { + checkToTripIOException(); + return super.read(); + } + + public int read(char[] cbuf, int off, int len) throws IOException { + checkToTripIOException(); + return super.read(cbuf, off, len); + } + + public String readLine() throws IOException { + checkToTripIOException(); + return super.readLine(); + } + + public boolean ready() throws IOException { + checkToTripIOException(); + return super.ready(); + } + + public void reset() throws IOException { + checkToTripIOException(); + super.reset(); + } + + public void close() throws IOException { + checkToTripIOException(); + super.close(); + } +} diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyBufferedWriter.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyBufferedWriter.java new file mode 100644 index 00000000..a06c99a9 --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyBufferedWriter.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.common; + + +import java.io.*; + +// A wrapper class to BufferedWriter class used to inject IOException errors +// when the throwIOException instance variable is set. All methods delegate +// to the parent super class and check whether or not to throw an IOException +// before delegation. + +public class MyBufferedWriter extends BufferedWriter { + + private boolean throwIOException; + + public MyBufferedWriter(Writer out) { + super(out); + } + + public MyBufferedWriter(Writer out, int sz) { + super(out, sz); + } + + public MyBufferedWriter(Writer out, int sz, boolean throwIOException) { + super(out, sz); + this.throwIOException = throwIOException; + } + + private void checkToTripIOException() throws IOException { + if (throwIOException) { + System.out.println("*** tripping an IOException ***"); + throw new IOException("tripping an IOException"); + } + } + + public void setThrowIOException(boolean throwIOException) { + this.throwIOException = throwIOException; + } + + public void write(int c) throws IOException { + checkToTripIOException(); + super.write(c); + } + + public void write(char[] cbuf) throws IOException { + checkToTripIOException(); + super.write(cbuf); + } + + public void write(char[] cbuf, int offset, int length) throws IOException { + checkToTripIOException(); + super.write(cbuf, offset, length); + } + + public void write(String str) throws IOException { + checkToTripIOException(); + super.write(str); + } + + public void write(String str, int offset, int length) throws IOException { + checkToTripIOException(); + super.write(str, offset, length); + } + + public void close() throws IOException { + checkToTripIOException(); + super.close(); + } + + public void flush() throws IOException { + checkToTripIOException(); + super.flush(); + } +} diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyJsonLocation.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyJsonLocation.java new file mode 100644 index 00000000..4882ac77 --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/common/MyJsonLocation.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.common; + + +import jakarta.json.stream.JsonLocation; + +public class MyJsonLocation implements JsonLocation { + + private long lineNumber = -1; + + private long columnNumber = -1; + + private long streamOffset = -1; + + public MyJsonLocation() { + } + + public MyJsonLocation(long lineNumber, long columnNumber, long streamOffset) { + this.lineNumber = lineNumber; + this.columnNumber = columnNumber; + this.streamOffset = streamOffset; + } + + public void setLineNumber(long lineNumber) { + this.lineNumber = lineNumber; + } + + public long getLineNumber() { + return lineNumber; + } + + public void setColumnNumber(long columnNumber) { + this.columnNumber = columnNumber; + } + + public long getColumnNumber() { + return columnNumber; + } + + public void setStreamOffset(long streamOffset) { + this.streamOffset = streamOffset; + } + + public long getStreamOffset() { + return streamOffset; + } +} diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/lib/harness/Fault.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/lib/harness/Fault.java new file mode 100644 index 00000000..b7a83e09 --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/lib/harness/Fault.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.lib.harness; + +import junit.framework.AssertionFailedError; + +public class Fault extends AssertionFailedError { + + private static final long serialVersionUID = 1L; + + public Fault() { + super(); + } + + public Fault(String message) { + super(message); + } + + public Fault(String message, Throwable cause) { + super(message + cause); + } + +} diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/util/FileUTFConverter.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/util/FileUTFConverter.java new file mode 100644 index 00000000..fe03252d --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/util/FileUTFConverter.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +/* + * Usage: java FileUTFConverter [-toUTF|-fromUTF] encoding infile outfile + * + * Utility program for converting a UTF-8 file to various UTF + * encoded files and vice-versa. + * + * Example(s): + * + * java FileUTFConverter -toUTF UTF-16 jsonObjectUTF8.json jsonObjectUTF16.json + * + * The above takes a UTF-8 encoded input file (jsonObjectUTF8.json) and converts + * it to a UTF-16 encoded output file (jsonObjectUTF16.json). + * + * java FileUTFConverter -fromUTF UTF-16 jsonObjectUTF16.json jsonObjectUTF8.json + * + * The above takes a UTF-16 encoded input file (jsonObjectUTF16.json) and + * converts it to a UTF-8 encoded output file (jsonObjectUTF8.json). + * + * All UTF encodings can be used: + * + * UTF-8 + * UTF-16 + * UTF-16BE + * UTF-16LE + * UTF-32BE + * UTF-32LE + */ + +package jakarta.jsonp.tck.util; + +import java.io.*; + +public class FileUTFConverter { + + private static final String USAGE = "Usage : java FileUTFConverter [-toUTF|-fromUTF] encoding infile outfile"; + + public static void main(String args[]) { + try { + if (args.length != 4) { + System.err.println(USAGE); + System.exit(1); + } + + // Convert UTF-8 input file to specified UTF encoded output file + if (args[0].equals("-toUTF")) { + System.out + .println("FileUTFConverter-> convert UTF-8 encoded input file (" + + args[2] + "), to encoding (" + args[1] + + ") and write to output file (" + args[3] + ")"); + FileInputStream fis = new FileInputStream(args[2]); + BufferedReader br = new BufferedReader( + new InputStreamReader(fis, "UTF-8")); + FileOutputStream fos = new FileOutputStream(args[3]); + BufferedWriter bw = new BufferedWriter( + new OutputStreamWriter(fos, args[1])); + for (String s = ""; (s = br.readLine()) != null;) { + bw.write(s + System.getProperty("line.separator")); + bw.flush(); + } + bw.close(); + br.close(); + // Convert specified UTF encoded input file to UTF-8 encoded output file + } else if (args[0].equals("-fromUTF")) { + System.out.println("FileUTFConverter-> convert UTF encoded input file (" + + args[2] + "), from encoding (" + args[1] + + ") and write to UTF-8 encoded output file (" + args[3] + ")"); + FileInputStream fis = new FileInputStream(args[2]); + BufferedReader br = new BufferedReader( + new InputStreamReader(fis, args[1])); + FileOutputStream fos = new FileOutputStream(args[3]); + BufferedWriter bw = new BufferedWriter( + new OutputStreamWriter(fos, "UTF-8")); + for (String s = ""; (s = br.readLine()) != null;) { + bw.write(s + System.getProperty("line.separator")); + bw.flush(); + } + bw.close(); + br.close(); + } else { + System.err.println(USAGE); + System.exit(1); + } + + System.exit(0); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } +} diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/util/MyEncoder.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/util/MyEncoder.java new file mode 100644 index 00000000..4ab64832 --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/util/MyEncoder.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.util; + +import java.io.*; + +/* + * Used to generate an encoded file preceded by N null characters. + * + * This utility takes a valid Json text file as input and generates + * an encoded version as output file with N null characters preceded by + * each character. For empty files it will just output the N null chars. + * + */ +public class MyEncoder { + + private static final int NULL = '\0'; + + private static final String USAGE = "Usage : java MyEncoder #nulls infile outfile"; + + public static void main(String args[]) { + if (args.length != 3) { + System.err.println(USAGE); + System.exit(1); + } + + FileReader inputStream = null; + FileWriter outputStream = null; + + try { + int n = Integer.parseInt(args[0]); + inputStream = new FileReader(args[1]); + outputStream = new FileWriter(args[2]); + + System.out.println("Null chars: " + args[0]); + System.out.println("Input file: " + args[1]); + System.out.println("Output file: " + args[2]); + + System.out + .println("\nCreating an encoded file with each char preceded by " + n + + " null chars.\n"); + + int c; + int nchars = 0; + while ((c = inputStream.read()) != -1) { + nchars++; + for (int i = 0; i < n; i++) + outputStream.write(NULL); + outputStream.write(c); + } + if (nchars == 0) { + for (int i = 0; i < n; i++) + outputStream.write(NULL); // if empty file at least write the nulls + // out + } + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (Exception e) { + } + } + if (outputStream != null) { + try { + outputStream.close(); + } catch (Exception e) { + } + } + } + System.exit(0); + } +} diff --git a/tck/tck-common/src/main/java/jakarta/jsonp/tck/util/StringUTFConverter.java b/tck/tck-common/src/main/java/jakarta/jsonp/tck/util/StringUTFConverter.java new file mode 100644 index 00000000..cefd268c --- /dev/null +++ b/tck/tck-common/src/main/java/jakarta/jsonp/tck/util/StringUTFConverter.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +/* + * Usage: java StringUTFConverter inputstring encoding outputfile + * + * Utility program to convert an input string to a UTF encoded output file. + * + * Example(s): + * + * java StringUTFConverter "foo" UTF-16LE fooUTF16LE + * + * The above converts an input string "foo" and outputs to UTF-16LE encoded + * output file (fooUTF16LE). + */ + +package jakarta.jsonp.tck.util; + +import java.io.*; + +public class StringUTFConverter { + + private static final String USAGE = "Usage : java StringUTFConverter inputstring encoding outputfile"; + + public static void main(String args[]) { + try { + if (args.length != 3) { + System.err.println(USAGE); + System.exit(1); + } + + // Convert string to specified UTF encoded output file + System.out.println( + "StringtoUTF-> convert string (" + args[0] + "), to encoding (" + + args[1] + ") and write to output file (" + args[2] + ")"); + FileOutputStream fos = new FileOutputStream(args[2]); + BufferedWriter bw = new BufferedWriter( + new OutputStreamWriter(fos, args[1])); + bw.write(args[0]); + bw.flush(); + bw.close(); + + System.exit(0); + + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + } +} diff --git a/tck/tck-tests-plugability/pom.xml b/tck/tck-tests-plugability/pom.xml new file mode 100644 index 00000000..9ffbf882 --- /dev/null +++ b/tck/tck-tests-plugability/pom.xml @@ -0,0 +1,40 @@ + + + + 4.0.0 + + + jakarta.json + jakarta.json-tck + 2.0.0-SNAPSHOT + + + jakarta.json-tck-tests-plugability + jar + + + + jakarta.json + jakarta.json-tck-common + 2.0.0-SNAPSHOT + provided + + + + diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/pluggability/jsonprovidertests/ClientTests.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/pluggability/jsonprovidertests/ClientTests.java new file mode 100644 index 00000000..58310ed4 --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/pluggability/jsonprovidertests/ClientTests.java @@ -0,0 +1,554 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.pluggability.jsonprovidertests; + +import jakarta.json.*; +import jakarta.json.spi.JsonProvider; +import jakarta.json.stream.*; + +import java.io.*; +import java.nio.charset.Charset; + +import java.util.Properties; +import java.util.ServiceLoader; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.List; +import java.util.Iterator; +import java.util.ArrayList; +import java.util.Map; +import java.util.HashMap; + +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; +import jakarta.jsonp.tck.provider.MyJsonProvider; +import jakarta.jsonp.tck.provider.MyJsonGenerator; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + + private static final String MY_JSONPROVIDER_CLASS = "jakarta.jsonp.tck.provider.MyJsonProvider"; + + private String providerPath = null; + + @After + public void after() { + MyJsonProvider.clearCalls(); + MyJsonGenerator.clearCalls(); + } + + /* Tests */ + + /* + * @testName: jsonProviderTest1 + * + * @assertion_ids: JSONP:JAVADOC:152; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * static JsonProvider provider() + */ + @Test + public void jsonProviderTest1() throws Fault { + boolean pass = true; + try { + // Load my provider + JsonProvider provider = JsonProvider.provider(); + String providerClass = provider.getClass().getName(); + System.out.println("provider class=" + providerClass); + if (providerClass.equals(MY_JSONPROVIDER_CLASS)) + System.out.println("Current provider is my provider - expected."); + else { + System.err.println("Current provider is not my provider - unexpected."); + pass = false; + ServiceLoader loader = ServiceLoader.load(JsonProvider.class); + Iterator it = loader.iterator(); + List providers = new ArrayList<>(); + while(it.hasNext()) { + providers.add(it.next()); + } + System.out.println("Providers: "+providers); + } + } catch (Exception e) { + throw new Fault("jsonProviderTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest1 Failed"); + } + + /* + * @testName: jsonProviderTest2 + * + * @assertion_ids: JSONP:JAVADOC:144; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonGenerator createGenerator(Writer) + */ + @Test + public void jsonProviderTest2() throws Fault { + boolean pass = true; + String expString = "public JsonGenerator createGenerator(Writer)"; + String expString2 = "public JsonGenerator writeStartArray()"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonGenerator generator = Json.createGenerator(new StringWriter()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + generator.writeStartArray(); + String actString2 = MyJsonGenerator.getCalls(); + System.out.println("Verify SPI generator method was called: " + expString2); + pass = JSONP_Util.assertEquals(expString2, actString2); + } catch (Exception e) { + throw new Fault("jsonProviderTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest2 Failed"); + } + + /* + * @testName: jsonProviderTest3 + * + * @assertion_ids: JSONP:JAVADOC:192; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonGenerator createGenerator(OutputStream) + */ + @Test + public void jsonProviderTest3() throws Fault { + boolean pass = true; + String expString = "public JsonGenerator createGenerator(OutputStream)"; + String expString2 = "public JsonGenerator writeStartObject()"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonGenerator generator = Json + .createGenerator(new ByteArrayOutputStream()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + generator.writeStartObject(); + String actString2 = MyJsonGenerator.getCalls(); + System.out.println("Verify SPI generator method was called: " + expString2); + pass = JSONP_Util.assertEquals(expString2, actString2); + } catch (Exception e) { + throw new Fault("jsonProviderTest3 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest3 Failed"); + } + + /* + * @testName: jsonProviderTest4 + * + * @assertion_ids: JSONP:JAVADOC:146; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonParser createParser(Reader) + */ + @Test + public void jsonProviderTest4() throws Fault { + boolean pass = true; + String expString = "public JsonParser createParser(Reader)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonParser parser = Json.createParser(new StringReader("{}")); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest4 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest4 Failed"); + } + + /* + * @testName: jsonProviderTest5 + * + * @assertion_ids: JSONP:JAVADOC:196; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonParser createParser(InputStream) + */ + @Test + public void jsonProviderTest5() throws Fault { + boolean pass = true; + String expString = "public JsonParser createParser(InputStream)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonParser parser = Json + .createParser(JSONP_Util.getInputStreamFromString("{}")); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest5 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest5 Failed"); + } + + /* + * @testName: jsonProviderTest6 + * + * @assertion_ids: JSONP:JAVADOC:465; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonParserFactory createParserFactory(Map) + */ + @Test + public void jsonProviderTest6() throws Fault { + boolean pass = true; + String expString = "public JsonParserFactory createParserFactory(Map)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonParserFactory parserFactory = Json + .createParserFactory(JSONP_Util.getEmptyConfig()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest6 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest6 Failed"); + } + + /* + * @testName: jsonProviderTest7 + * + * @assertion_ids: JSONP:JAVADOC:426; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonParserFactory createParserFactory(Map) + */ + @Test + public void jsonProviderTest7() throws Fault { + boolean pass = true; + String expString = "public JsonParserFactory createParserFactory(Map)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonParserFactory parserFactory = Json + .createParserFactory(new HashMap()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest7 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest7 Failed"); + } + + /* + * @testName: jsonProviderTest8 + * + * @assertion_ids: JSONP:JAVADOC:425; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonGeneratorFactory createGeneratorFactory(Map) + */ + @Test + public void jsonProviderTest8() throws Fault { + boolean pass = true; + String expString = "public JsonGeneratorFactory createGeneratorFactory(Map)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonGeneratorFactory generatorFactory = Json + .createGeneratorFactory(new HashMap()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest8 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest8 Failed"); + } + + /* + * @testName: jsonProviderTest9 + * + * @assertion_ids: JSONP:JAVADOC:472; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonWriterFactory createWriterFactory(Map) + */ + @Test + public void jsonProviderTest9() throws Fault { + boolean pass = true; + String expString = "public JsonWriterFactory createWriterFactory(Map)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonWriterFactory factory = Json + .createWriterFactory(JSONP_Util.getEmptyConfig()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest9 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest9 Failed"); + } + + /* + * @testName: jsonProviderTest10 + * + * @assertion_ids: JSONP:JAVADOC:223; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonParser createParser(InputStream) Tests the case where a JsonException + * can be thrown. An InputStream of null will cause MyJsonProvider to throw + * JsonException. + */ + @Test + public void jsonProviderTest10() throws Fault { + boolean pass = true; + String expString = "public JsonParser createParser(InputStream)"; + try { + System.out.println("Calling SPI provider method: " + expString); + InputStream in = null; + JsonParser parser = Json.createParser(in); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException: " + e); + } catch (Exception e) { + throw new Fault("jsonProviderTest10 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest10 Failed"); + } + + /* + * @testName: jsonProviderTest11 + * + * @assertion_ids: JSONP:JAVADOC:464; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonArrayBuilder createArrayBuilder() + */ + @Test + public void jsonProviderTest11() throws Fault { + boolean pass = true; + String expString = "public JsonArrayBuilder createArrayBuilder()"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest11 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest11 Failed"); + } + + /* + * @testName: jsonProviderTest12 + * + * @assertion_ids: JSONP:JAVADOC:466; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonObjectBuilder createObjectBuilder() + */ + @Test + public void jsonProviderTest12() throws Fault { + boolean pass = true; + String expString = "public JsonObjectBuilder createObjectBuilder()"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonObjectBuilder objectBuilder = Json.createObjectBuilder(); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest12 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest12 Failed"); + } + + /* + * @testName: jsonProviderTest13 + * + * @assertion_ids: JSONP:JAVADOC:465; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonBuilderFactory createBuilderFactory(Map) + */ + @Test + public void jsonProviderTest13() throws Fault { + boolean pass = true; + String expString = "public JsonBuilderFactory createBuilderFactory(Map)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonBuilderFactory objectBuilder = Json + .createBuilderFactory(JSONP_Util.getEmptyConfig()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest13 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest13 Failed"); + } + + /* + * @testName: jsonProviderTest14 + * + * @assertion_ids: JSONP:JAVADOC:467; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonReader createReader(Reader) + */ + @Test + public void jsonProviderTest14() throws Fault { + boolean pass = true; + String expString = "public JsonReader createReader(Reader)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonReader reader = Json.createReader(new StringReader("{}")); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest14 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest14 Failed"); + } + + /* + * @testName: jsonProviderTest15 + * + * @assertion_ids: JSONP:JAVADOC:468; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonReader createReader(InputStream) + */ + @Test + public void jsonProviderTest15() throws Fault { + boolean pass = true; + String expString = "public JsonReader createReader(InputStream)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonReader reader = Json + .createReader(JSONP_Util.getInputStreamFromString("{}")); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest15 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest15 Failed"); + } + + /* + * @testName: jsonProviderTest16 + * + * @assertion_ids: JSONP:JAVADOC:470; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonWriter createWriter(Writer) + */ + @Test + public void jsonProviderTest16() throws Fault { + boolean pass = true; + String expString = "public JsonWriter createWriter(Writer)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonWriter writer = Json.createWriter(new StringWriter()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest16 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest16 Failed"); + } + + /* + * @testName: jsonProviderTest17 + * + * @assertion_ids: JSONP:JAVADOC:471; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonWriter createWriter(OutputStream) + */ + @Test + public void jsonProviderTest17() throws Fault { + boolean pass = true; + String expString = "public JsonWriter createWriter(OutputStream)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonWriter writer = Json.createWriter(new ByteArrayOutputStream()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest17 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest17 Failed"); + } + + /* + * @testName: jsonProviderTest18 + * + * @assertion_ids: JSONP:JAVADOC:469; + * + * @test_Strategy: Test call of SPI provider method with signature: o public + * JsonReaderFactory createReaderFactory(Map) + */ + @Test + public void jsonProviderTest18() throws Fault { + boolean pass = true; + String expString = "public JsonReaderFactory createReaderFactory(Map)"; + try { + System.out.println("Calling SPI provider method: " + expString); + JsonReaderFactory factory = Json + .createReaderFactory(JSONP_Util.getEmptyConfig()); + String actString = MyJsonProvider.getCalls(); + System.out.println("Verify SPI provider method was called: " + expString); + pass = JSONP_Util.assertEquals(expString, actString); + } catch (Exception e) { + throw new Fault("jsonProviderTest18 Failed: ", e); + } + if (!pass) + throw new Fault("jsonProviderTest18 Failed"); + } +} diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonGenerator.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonGenerator.java new file mode 100644 index 00000000..93400703 --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonGenerator.java @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.provider; + +import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.Charset; +import jakarta.json.*; +import jakarta.json.stream.*; + +/* + * MyJsonGenerator is a Json Test Generator used by the pluggability tests + * to test the Json SPI layer. This generator tracks that the proper callback + * methods are invoked within the generator when Json API methods are called. + */ + +public class MyJsonGenerator implements JsonGenerator { + private Writer writer = null; + + private OutputStream out = null; + + private final Charset charset = Charset.forName("UTF-8"); + + private void dumpInstanceVars() { + System.out.println("writer=" + writer); + System.out.println("out=" + out); + System.out.println("charset=" + charset); + } + + // call methods + private static StringBuilder calls = new StringBuilder(); + + public static String getCalls() { + return calls.toString(); + } + + public static void clearCalls() { + calls.delete(0, calls.length()); + } + + private static void addCalls(String s) { + calls.append(s); + } + + public MyJsonGenerator(Writer writer) { + this.writer = writer; + } + + public MyJsonGenerator(OutputStream out) { + this.out = out; + } + + @Override + public void flush() { + System.out.println("public void flush()"); + addCalls("public void flush()"); + } + + @Override + public JsonGenerator writeStartObject() { + System.out.println("public JsonGenerator writeStartObject()"); + addCalls("public JsonGenerator writeStartObject()"); + return null; + } + + @Override + public JsonGenerator writeStartObject(String name) { + System.out.println("public JsonGenerator writeStartObject(String)"); + addCalls("public JsonGenerator writeStartObject(String)"); + return null; + } + + @Override + public JsonGenerator write(String name, String value) { + System.out.println("public JsonGenerator write(String,String)"); + addCalls("public JsonGenerator write(String,String)"); + return null; + } + + @Override + public JsonGenerator write(String name, int value) { + System.out.println("public JsonGenerator write(String,int)"); + addCalls("public JsonGenerator write(String,int)"); + return null; + } + + @Override + public JsonGenerator write(String name, long value) { + System.out.println("public JsonGenerator write(String,long)"); + addCalls("public JsonGenerator write(String,long)"); + return null; + } + + @Override + public JsonGenerator write(String name, double value) { + System.out.println("public JsonGenerator write(String,double)"); + addCalls("public JsonGenerator write(String,double)"); + return null; + } + + @Override + public JsonGenerator write(String name, BigInteger value) { + System.out.println("public JsonGenerator write(String,BigInteger)"); + addCalls("public JsonGenerator write(String,BigInteger)"); + return null; + } + + @Override + public JsonGenerator write(String name, BigDecimal value) { + System.out.println("public JsonGenerator write(String,BigDecimal)"); + addCalls("public JsonGenerator write(String,BigDecimal)"); + return null; + } + + @Override + public JsonGenerator write(String name, boolean value) { + System.out.println("public JsonGenerator write(String,boolean)"); + addCalls("public JsonGenerator write(String,boolean)"); + return null; + } + + @Override + public JsonGenerator write(String name, JsonValue value) { + System.out.println("public JsonGenerator write(String,JsonValue)"); + addCalls("public JsonGenerator write(String,JsonValue)"); + return null; + } + + @Override + public JsonGenerator writeNull(String name) { + System.out.println("public JsonGenerator writeNull(String)"); + addCalls("public JsonGenerator writeNull(String)"); + return null; + } + + @Override + public JsonGenerator writeStartArray() { + System.out.println("public JsonGenerator writeStartArray()"); + addCalls("public JsonGenerator writeStartArray()"); + return null; + } + + @Override + public JsonGenerator writeStartArray(String name) { + System.out.println("public JsonGenerator writeStartArray(String)"); + addCalls("public JsonGenerator writeStartArray(String)"); + return null; + } + + @Override + public JsonGenerator write(String value) { + System.out.println("public JsonGenerator write(String)"); + addCalls("public JsonGenerator write(String)"); + return null; + } + + @Override + public JsonGenerator write(int value) { + System.out.println("public JsonGenerator write(int)"); + addCalls("public JsonGenerator write(int)"); + return null; + } + + @Override + public JsonGenerator write(long value) { + System.out.println("public JsonGenerator write(long)"); + addCalls("public JsonGenerator write(long)"); + return null; + } + + @Override + public JsonGenerator write(double value) { + System.out.println("public JsonGenerator write(double)"); + addCalls("public JsonGenerator write(double)"); + return null; + } + + @Override + public JsonGenerator write(BigInteger value) { + System.out.println("public JsonGenerator write(BigInteger)"); + addCalls("public JsonGenerator write(BigInteger)"); + return null; + } + + @Override + public JsonGenerator write(BigDecimal value) { + System.out.println("public JsonGenerator write(BigDecimal)"); + addCalls("public JsonGenerator write(BigDecimal)"); + return null; + } + + @Override + public JsonGenerator write(boolean value) { + System.out.println("public JsonGenerator write(boolean)"); + addCalls("public JsonGenerator write(boolean)"); + return null; + } + + @Override + public JsonGenerator write(JsonValue value) { + System.out.println("public JsonGenerator write(JsonValue)"); + addCalls("public JsonGenerator write(JsonValue)"); + return null; + } + + @Override + public JsonGenerator writeNull() { + System.out.println("public JsonGenerator writeNull()"); + addCalls("public JsonGenerator writeNull()"); + return null; + } + + @Override + public JsonGenerator writeEnd() { + System.out.println("public JsonGenerator writeEnd()"); + addCalls("public JsonGenerator writeEnd()"); + return null; + } + + @Override + public JsonGenerator writeKey(String name) { + System.out.println("public JsonGenerator writeKey()"); + addCalls("public JsonGenerator writeKey()"); + return null; + } + + @Override + public void close() { + System.out.println("public void close()"); + addCalls("public void close()"); + } + +} diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonGeneratorFactory.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonGeneratorFactory.java new file mode 100644 index 00000000..d5ae3dd0 --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonGeneratorFactory.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.provider; + +import jakarta.json.*; +import jakarta.json.stream.*; +import java.io.*; +import java.nio.charset.Charset; +import java.util.*; + +/* + * MyJsonGeneratorFactory is a Json Test GeneratorFactory used by the pluggability tests + * to test the Json SPI layer. This parser tracks that the proper callback + * methods are invoked within the parser when Json API methods are called. + */ + +public class MyJsonGeneratorFactory implements JsonGeneratorFactory { + private OutputStream out = null; + + private Writer writer = null; + + private Charset charset = Charset.forName("UTF-8"); + + private Map config = null; + + private void dumpInstanceVars() { + System.out.println("writer=" + writer); + System.out.println("out=" + out); + System.out.println("charset=" + charset); + System.out.println("config=" + config); + } + + // call methods + private static StringBuilder calls = new StringBuilder(); + + public static String getCalls() { + return calls.toString(); + } + + public static void clearCalls() { + calls.delete(0, calls.length()); + } + + private static void addCalls(String s) { + calls.append(s); + } + + public MyJsonGeneratorFactory(Map config) { + this.config = config; + } + + public Map getConfigInUse() { + System.out.println("public Map getConfigInUse()"); + addCalls("public Map getConfigInUse()"); + return config; + } + + public JsonGenerator createGenerator(OutputStream out) { + System.out.println("public JsonGenerator createGenerator(OutputStream)"); + addCalls("public JsonGenerator createGenerator(OutputStream)"); + this.out = out; + return null; + } + + public JsonGenerator createGenerator(OutputStream out, Charset charset) { + System.out.println( + "public JsonGenerator createGenerator(OutputStream, Charset)"); + addCalls("public JsonGenerator createGenerator(OutputStream, Charset)"); + this.out = out; + this.charset = charset; + return null; + } + + public JsonGenerator createGenerator(Writer writer) { + System.out.println("public JsonGenerator createGenerator(Writer)"); + addCalls("public JsonGenerator createGenerator(Writer)"); + this.writer = writer; + return null; + } +} diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonParser.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonParser.java new file mode 100644 index 00000000..5df3fc51 --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonParser.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.provider; + + +import jakarta.json.*; +import jakarta.json.stream.*; +import jakarta.json.spi.JsonProvider; +import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.Charset; +import java.util.*; + +/* + * MyJsonParser is a Json Test Parser used by the pluggability tests + * to test the Json SPI layer. This parser tracks that the proper callback + * methods are invoked within the parser when Json API methods are called. + */ + +public class MyJsonParser implements JsonParser { + private InputStream in = null; + + private Reader reader = null; + + private void dumpInstanceVars() { + System.out.println("reader=" + reader); + System.out.println("in=" + in); + } + + // call methods + private static StringBuilder calls = new StringBuilder(); + + public static String getCalls() { + return calls.toString(); + } + + public static void clearCalls() { + calls.delete(0, calls.length()); + } + + private static void addCalls(String s) { + calls.append(s); + } + + public MyJsonParser(InputStream in) { + this.in = in; + } + + public MyJsonParser(Reader reader) { + this.reader = reader; + } + + public void close() { + System.out.println("public void close()"); + addCalls("public void close()"); + } + + public BigDecimal getBigDecimal() { + System.out.println("public BigDecimal getBigDecimal()"); + addCalls("public BigDecimal getBigDecimal()"); + return null; + } + + public int getInt() { + System.out.println("public int getInt()"); + addCalls("public int getInt()"); + return -1; + } + + public JsonLocation getLocation() { + System.out.println("public JsonLocation getLocation()"); + addCalls("public JsonLocation getLocation()"); + return null; + } + + public long getLong() { + System.out.println("public long getLong()"); + addCalls("public long getLong()"); + return -1; + } + + public boolean isIntegralNumber() { + System.out.println("public boolean isIntegralNumber()"); + addCalls("public boolean isIntegralNumber()"); + return false; + } + + public String getString() { + System.out.println("public String getString()"); + addCalls("public String getString()"); + return null; + } + + public boolean hasNext() { + System.out.println("public boolean hasNext()"); + addCalls("public boolean hasNext()"); + return false; + } + + public JsonParser.Event next() { + System.out.println("public JsonParser.Event next()"); + addCalls("public JsonParser.Event next()"); + return null; + } +} diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonParserFactory.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonParserFactory.java new file mode 100644 index 00000000..0d06523c --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonParserFactory.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.provider; + +import jakarta.json.*; +import jakarta.json.stream.*; +import java.io.*; +import java.nio.charset.Charset; +import java.util.*; + +/* + * MyJsonParserFactory is a Json Test ParserFactory used by the pluggability tests + * to test the Json SPI layer. This parser tracks that the proper callback + * methods are invoked within the parser when Json API methods are called. + */ + +public class MyJsonParserFactory implements JsonParserFactory { + private InputStream in = null; + + private Charset charset = null; + + private Reader reader = null; + + private Map config = null; + + private void dumpInstanceVars() { + System.out.println("reader=" + reader); + System.out.println("in=" + in); + System.out.println("charset=" + charset); + System.out.println("config=" + config); + } + + // call methods + private static StringBuilder calls = new StringBuilder(); + + public static String getCalls() { + return calls.toString(); + } + + public static void clearCalls() { + calls.delete(0, calls.length()); + } + + private static void addCalls(String s) { + calls.append(s); + } + + public MyJsonParserFactory(Map config) { + this.config = config; + } + + public Map getConfigInUse() { + System.out.println("public Map getConfigInUse()"); + addCalls("public Map getConfigInUse()"); + return config; + } + + public JsonParser createParser(InputStream in) { + System.out.println("public JsonParser createParser(InputStream)"); + addCalls("public JsonParser createParser(InputStream)"); + this.in = in; + return null; + } + + public JsonParser createParser(InputStream in, Charset charset) { + System.out.println("public JsonParser createParser(InputStream, Charset)"); + addCalls("public JsonParser createParser(InputStream, Charset)"); + this.in = in; + this.charset = charset; + return null; + } + + public JsonParser createParser(Reader reader) { + System.out.println("public JsonParser createParser(Reader)"); + addCalls("public JsonParser createParser(Reader)"); + this.reader = reader; + return null; + } + + public JsonParser createParser(JsonArray jsonArray) { + System.out.println("public JsonParser createParser(JsonArray)"); + addCalls("public JsonParser createParser(JsonArray)"); + return null; + } + + public JsonParser createParser(JsonObject jsonObject) { + System.out.println("public JsonParser createParser(JsonObject)"); + addCalls("public JsonParser createParser(JsonObject)"); + return null; + } +} diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonProvider.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonProvider.java new file mode 100644 index 00000000..c7d16807 --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonProvider.java @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.provider; + +import java.io.*; +import java.util.*; +import jakarta.json.*; +import jakarta.json.spi.JsonProvider; +import jakarta.json.stream.*; + +// $Id$ +/* + * MyJsonProvider is a Json Test Provider used by the pluggability tests + * to test the Json SPI layer. This provider tracks that the proper callback + * methods are invoked within the provider when Json API methods are called. + */ +public class MyJsonProvider extends JsonProvider { + + // Exception thrown when encoding or i/o error + private final JsonException exception = new JsonException( + "encoding or i/o error"); + + // call methods + private static final StringBuilder CALLS = new StringBuilder(); + + public static String getCalls() { + return CALLS.toString(); + } + + public static void clearCalls() { + CALLS.delete(0, CALLS.length()); + } + + private static void addCalls(String s) { + CALLS.append(s); + } + + @Override + public JsonArrayBuilder createArrayBuilder() { + System.out.println("public JsonArrayBuilder createArrayBuilder()"); + addCalls("public JsonArrayBuilder createArrayBuilder()"); + return null; + } + + @Override + public JsonBuilderFactory createBuilderFactory(Map config) { + System.out.println( + "public JsonBuilderFactory createBuilderFactory(Map)"); + addCalls("public JsonBuilderFactory createBuilderFactory(Map)"); + return null; + } + + @Override + public JsonObjectBuilder createObjectBuilder() { + System.out.println("public JsonObjectBuilder createObjectBuilder()"); + addCalls("public JsonObjectBuilder createObjectBuilder()"); + return null; + } + + @Override + public JsonReader createReader(Reader reader) { + System.out.println("public JsonReader createReader(Reader)"); + addCalls("public JsonReader createReader(Reader)"); + return new MyJsonReader(reader); + } + + @Override + public JsonReader createReader(InputStream in) { + System.out.println("public JsonReader createReader(InputStream)"); + addCalls("public JsonReader createReader(InputStream)"); + return new MyJsonReader(in); + } + + @Override + public JsonReaderFactory createReaderFactory(Map config) { + System.out.println( + "public JsonReaderFactory createReaderFactory(Map)"); + addCalls("public JsonReaderFactory createReaderFactory(Map)"); + return null; + } + + @Override + public JsonWriter createWriter(Writer writer) { + System.out.println("public JsonWriter createWriter(Writer)"); + addCalls("public JsonWriter createWriter(Writer)"); + return new MyJsonWriter(writer); + } + + @Override + public JsonWriter createWriter(OutputStream out) { + System.out.println("public JsonWriter createWriter(OutputStream)"); + addCalls("public JsonWriter createWriter(OutputStream)"); + return new MyJsonWriter(out); + } + + @Override + public JsonWriterFactory createWriterFactory(Map config) { + System.out.println( + "public JsonWriterFactory createWriterFactory(Map)"); + addCalls("public JsonWriterFactory createWriterFactory(Map)"); + return null; + } + + @Override + public JsonGenerator createGenerator(Writer writer) { + System.out.println("public JsonGenerator createGenerator(Writer)"); + addCalls("public JsonGenerator createGenerator(Writer)"); + return new MyJsonGenerator(writer); + } + + @Override + public JsonGenerator createGenerator(OutputStream out) { + System.out.println("public JsonGenerator createGenerator(OutputStream)"); + addCalls("public JsonGenerator createGenerator(OutputStream)"); + return new MyJsonGenerator(out); + } + + @Override + public JsonParser createParser(Reader reader) { + System.out.println("public JsonParser createParser(Reader)"); + addCalls("public JsonParser createParser(Reader)"); + return new MyJsonParser(reader); + } + + @Override + public JsonParser createParser(InputStream in) { + System.out.println("public JsonParser createParser(InputStream)"); + addCalls("public JsonParser createParser(InputStream)"); + if (in == null) + throw exception; + else + return new MyJsonParser(in); + } + + @Override + public JsonParserFactory createParserFactory(Map config) { + System.out.println( + "public JsonParserFactory createParserFactory(Map)"); + addCalls("public JsonParserFactory createParserFactory(Map)"); + return null; + } + + @Override + public JsonGeneratorFactory createGeneratorFactory(Map config) { + System.out.println( + "public JsonGeneratorFactory createGeneratorFactory(Map)"); + addCalls( + "public JsonGeneratorFactory createGeneratorFactory(Map)"); + return null; + } + + @Override + public JsonPatchBuilder createPatchBuilder() { + throw new UnsupportedOperationException("Not supported yet."); // To change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonPatchBuilder createPatchBuilder(JsonArray ja) { + throw new UnsupportedOperationException("Not supported yet."); // To change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + +} diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonReader.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonReader.java new file mode 100644 index 00000000..a74c203f --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonReader.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.provider; + +import jakarta.json.*; +import jakarta.json.stream.*; +import jakarta.json.spi.JsonProvider; +import java.io.*; +import java.nio.charset.Charset; +import java.util.*; + +/* + * MyJsonReader is a Json Test Reader used by the pluggability tests + * to test the Json SPI layer. This parser tracks that the proper callback + * methods are invoked within the parser when Json API methods are called. + */ + +public class MyJsonReader implements JsonReader { + private InputStream in = null; + + private Reader reader = null; + + private void dumpInstanceVars() { + System.out.println("reader=" + reader); + System.out.println("in=" + in); + } + + // call methods + private static StringBuilder calls = new StringBuilder(); + + public static String getCalls() { + return calls.toString(); + } + + public static void clearCalls() { + calls.delete(0, calls.length()); + } + + private static void addCalls(String s) { + calls.append(s); + } + + public MyJsonReader() { + } + + public MyJsonReader(InputStream in) { + this.in = in; + } + + public MyJsonReader(Reader reader) { + this.reader = reader; + } + + public void close() { + System.out.println("public void close()"); + addCalls("public void close()"); + } + + public JsonStructure read() { + System.out.println("public void read()"); + addCalls("public void read()"); + return null; + } + + public JsonArray readArray() { + System.out.println("public void readArray()"); + addCalls("public void readArray()"); + return null; + } + + public JsonObject readObject() { + System.out.println("public void readObject()"); + addCalls("public void readObject()"); + return null; + } +} diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonReaderFactory.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonReaderFactory.java new file mode 100644 index 00000000..d58b9a2b --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonReaderFactory.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.provider; + +import jakarta.json.*; +import java.io.*; +import java.nio.charset.Charset; +import java.util.*; + +/* + * MyJsonReaderFactory is a Json Test ReaderFactory used by the pluggability tests + * to test the Json SPI layer. This parser tracks that the proper callback + * methods are invoked within the parser when Json API methods are called. + */ +public class MyJsonReaderFactory implements JsonReaderFactory { + private InputStream in = null; + + private Charset charset = null; + + private Reader reader = null; + + private Map config = null; + + private void dumpInstanceVars() { + System.out.println("reader=" + reader); + System.out.println("in=" + in); + System.out.println("charset=" + charset); + System.out.println("config=" + config); + } + + // call methods + private static StringBuilder calls = new StringBuilder(); + + public static String getCalls() { + return calls.toString(); + } + + public static void clearCalls() { + calls.delete(0, calls.length()); + } + + private static void addCalls(String s) { + calls.append(s); + } + + public MyJsonReaderFactory(Map config) { + this.config = config; + } + + public Map getConfigInUse() { + System.out.println("public Map getConfigInUse()"); + addCalls("public Map getConfigInUse()"); + return config; + } + + public JsonReader createReader(InputStream in) { + System.out.println("public JsonReader createReader(InputStream)"); + addCalls("public JsonReader createReader(InputStream)"); + this.in = in; + return null; + } + + public JsonReader createReader(InputStream in, Charset charset) { + System.out.println("public JsonReader createReader(InputStream, Charset)"); + addCalls("public JsonReader createReader(InputStream, Charset)"); + this.in = in; + this.charset = charset; + return null; + } + + public JsonReader createReader(Reader reader) { + System.out.println("public JsonReader createReader(Reader)"); + addCalls("public JsonReader createReader(Reader)"); + this.reader = reader; + return null; + } +} diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonWriter.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonWriter.java new file mode 100644 index 00000000..a3321f04 --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonWriter.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.provider; + +import jakarta.json.*; +import jakarta.json.stream.*; +import jakarta.json.spi.JsonProvider; +import java.io.*; +import java.nio.charset.Charset; +import java.util.*; + +/* + * MyJsonWriter is a Json Test Writer used by the pluggability tests + * to test the Json SPI layer. This parser tracks that the proper callback + * methods are invoked within the parser when Json API methods are called. + */ +public class MyJsonWriter implements JsonWriter { + private OutputStream out = null; + + private Writer writer = null; + + private Charset charset = Charset.forName("UTF-8"); + + private void dumpInstanceVars() { + System.out.println("writer=" + writer); + System.out.println("out=" + out); + System.out.println("charset=" + charset); + } + + // call methods + private static StringBuilder calls = new StringBuilder(); + + public static String getCalls() { + return calls.toString(); + } + + public static void clearCalls() { + calls.delete(0, calls.length()); + } + + private static void addCalls(String s) { + calls.append(s); + } + + public MyJsonWriter() { + } + + public MyJsonWriter(OutputStream out) { + this.out = out; + } + + public MyJsonWriter(Writer writer) { + this.writer = writer; + } + + public void close() { + System.out.println("public void close()"); + addCalls("public void close()"); + } + + public void write(JsonStructure value) { + System.out.println("public void write(JsonStructure)"); + addCalls("public void write(JsonStructure)"); + } + + public void writeArray(JsonArray array) { + System.out.println("public void writeArray(JsonArray)"); + addCalls("public void writeArray(JsonArray)"); + } + + public void writeObject(JsonObject object) { + System.out.println("public void writeObject(JsonObject)"); + addCalls("public void writeObject(JsonObject)"); + } +} diff --git a/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonWriterFactory.java b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonWriterFactory.java new file mode 100644 index 00000000..f15cfbd1 --- /dev/null +++ b/tck/tck-tests-plugability/src/main/java/jakarta/jsonp/tck/provider/MyJsonWriterFactory.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ + +package jakarta.jsonp.tck.provider; + + +import jakarta.json.*; +import java.io.*; +import java.nio.charset.Charset; +import java.util.*; + +/* + * MyJsonWriterFactory is a Json Test WriterFactory used by the pluggability tests + * to test the Json SPI layer. This parser tracks that the proper callback + * methods are invoked within the parser when Json API methods are called. + */ +public class MyJsonWriterFactory implements JsonWriterFactory { + private OutputStream out = null; + + private Writer writer = null; + + private Charset charset = null; + + private Map config = null; + + private void dumpInstanceVars() { + System.out.println("writer=" + writer); + System.out.println("out=" + out); + System.out.println("charset=" + charset); + System.out.println("config=" + config); + } + + // call methods + private static StringBuilder calls = new StringBuilder(); + + public static String getCalls() { + return calls.toString(); + } + + public static void clearCalls() { + calls.delete(0, calls.length()); + } + + private static void addCalls(String s) { + calls.append(s); + } + + public MyJsonWriterFactory(Map config) { + this.config = config; + } + + public Map getConfigInUse() { + System.out.println("public Map getConfigInUse()"); + addCalls("public Map getConfigInUse()"); + return config; + } + + public JsonWriter createWriter(OutputStream out) { + System.out.println("public JsonWriter createWriter(OutputStream)"); + addCalls("public JsonWriter createWriter(OutputStream)"); + this.out = out; + return null; + } + + public JsonWriter createWriter(OutputStream out, Charset charset) { + System.out.println("public JsonWriter createWriter(OutputStream, Charset)"); + addCalls("public JsonWriter createWriter(OutputStream, Charset)"); + this.out = out; + this.charset = charset; + return null; + } + + public JsonWriter createWriter(Writer writer) { + System.out.println("public JsonWriter createWriter(Writer)"); + addCalls("public JsonWriter createWriter(Writer)"); + this.writer = writer; + return null; + } +} diff --git a/tck/tck-tests-plugability/src/main/resources/META-INF/services/jakarta.json.spi.JsonProvider b/tck/tck-tests-plugability/src/main/resources/META-INF/services/jakarta.json.spi.JsonProvider new file mode 100644 index 00000000..997ae9ad --- /dev/null +++ b/tck/tck-tests-plugability/src/main/resources/META-INF/services/jakarta.json.spi.JsonProvider @@ -0,0 +1 @@ +jakarta.jsonp.tck.provider.MyJsonProvider diff --git a/tck/tck-tests/pom.xml b/tck/tck-tests/pom.xml new file mode 100644 index 00000000..af1c6d06 --- /dev/null +++ b/tck/tck-tests/pom.xml @@ -0,0 +1,40 @@ + + + + 4.0.0 + + + jakarta.json + jakarta.json-tck + 2.0.0-SNAPSHOT + + + jakarta.json-tck-tests + jar + + + + jakarta.json + jakarta.json-tck-common + 2.0.0-SNAPSHOT + provided + + + + diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/collectortests/CollectorTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/collectortests/CollectorTests.java new file mode 100644 index 00000000..a15bc5ed --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/collectortests/CollectorTests.java @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.collectortests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.lib.harness.Fault; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +// $Id$ +/** + * JavaScript Object Notation (JSON) Pointer compatibility tests.
+ * Test {@link jakarta.json.stream.JsonCollectors} class implementation. + */ +@RunWith(Arquillian.class) +public class CollectorTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, CollectorTests.class.getPackage().getName()); + } + + /** + * Test JSON-P {@link jakarta.json.stream.JsonCollectors} class implementation. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonCollectorTest + * @assertion_ids: JSONP:JAVADOC:668; JSONP:JAVADOC:669; JSONP:JAVADOC:670; + * JSONP:JAVADOC:671; + * @test_Strategy: Test all collectors returned by API. + */ + @Test + public void jsonCollectorTest() throws Fault { + Collectors collectorTest = new Collectors(); + final TestResult result = collectorTest.test(); + result.eval(); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/collectortests/Collectors.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/collectortests/Collectors.java new file mode 100644 index 00000000..bffc4454 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/collectortests/Collectors.java @@ -0,0 +1,517 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.collectortests; + +import jakarta.jsonp.tck.api.common.TestResult; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Map; +import java.util.TreeSet; +import java.util.function.Function; +import java.util.stream.Collector; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonValue; +import jakarta.json.stream.JsonCollectors; +import jakarta.json.stream.JsonParser; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) Pointer compatibility tests.
+ * Test {@link jakarta.json.stream.JsonCollectors} class implementation. This + * class was added to resolve + * {@see RFE: + * Support JSON queries using JDK's stream operations}. + */ +public class Collectors { + + /** Tests input data with JsonArray instances. */ + private static final JsonArray[] ARRAY_VALUES = new JsonArray[] { + createSimpleStringArray5(), // JsonArray with String + createSimpleIntArray5(), // JsonArray with int + createSimpleBoolArray5(), // JsonArray with boolean + createSimpleObjectArray5() // JsonArray with JsonObject + }; + + /** Tests input data with JsonArray instances. */ + private static final JsonObject[] OBJ_VALUES = new JsonObject[] { + createSimpleObjectWithStr(), // JsonObject with String + createSimpleObjectWithInt(), // JsonObject with int + createSimpleObjectWithBool(), // JsonObject with boolean + createCompoundObject() // JsonObject with JsonObject + }; + + /** Test input data for {@code groupingBy} methods. */ + private static final JsonArray OBJ_ARRAY_GROUP = Json.createArrayBuilder() + .add(Json.createObjectBuilder().add("name", "Peter").add("office", + "Green")) + .add(Json.createObjectBuilder().add("name", "John").add("office", "Red")) + .add(Json.createObjectBuilder().add("name", "Bob").add("office", "Blue")) + .add(Json.createObjectBuilder().add("name", "Sarah").add("office", "Red")) + .add(Json.createObjectBuilder().add("name", "Tom").add("office", "Blue")) + .add(Json.createObjectBuilder().add("name", "Jane").add("office", "Blue")) + .add(Json.createObjectBuilder().add("name", "Peggy").add("office", + "Green")) + .add(Json.createObjectBuilder().add("name", "Rick").add("office", "Red")) + .build(); + + /** + * Creates an instance of {@link jakarta.json.stream.JsonCollectors} class + * implementation tests. + */ + Collectors() { + super(); + } + + /** + * Test {@link jakarta.json.stream.JsonCollectors} class implementation. Suite + * entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonCollectors class implementation"); + System.out.println("JsonCollectors class implementation"); + testToJsonArrayCollector(result); + // testSimpleToJsonObjectCollector(result); + testToJsonObjectCollector(result); + testSimpleGroupingByCollector(result); + testSortingGroupingByCollector(result); + return result; + } + + /** + * Test collector returned by {@code toJsonArray()} method. This collector + * packs {@code Stream} contend into a single JsonArray instance + * which contains stream values in the same order at they were read. It can be + * considered as {@link JsonParser#getArrayStream()} counterpart. + * + * @param result + * Tests result record. + */ + private void testToJsonArrayCollector(final TestResult result) { + System.out.println(" - Collector returned by toJsonArray()"); + for (final JsonArray in : ARRAY_VALUES) { + System.out.println(" - Input: " + valueToString(in)); + final Collector col = JsonCollectors + .toJsonArray(); + final JsonArray out = in.getValuesAs(JsonObject.class).stream() + .collect(col); + if (operationFailed(in, out)) { + result.fail("toJsonArray()", "Output Stream value " + valueToString(out) + + " shall be " + valueToString(in)); + } + } + } + + // TCK test for https://java.net/jira/browse/JSON_PROCESSING_SPEC-82 in case + // it will be checked in. + // /** + // * Test collector returned by {@code toJsonObject()} method. + // * This collector packs {@code Stream} contend into a single + // JsonArray instance which contains + // * stream values in the same order at they were read. It can be considered + // as {@link JsonParser#getArrayStream()} + // * counterpart. + // * @param result Tests result record. + // */ + // private void testSimpleToJsonObjectCollector(final TestResult result) { + // System.out.println(" - Collector returned by toJsonObject()"); + // for (final JsonObject in : OBJ_VALUES) { + // System.out.println(" - Input: " + valueToString(in)); + // final Collector, JsonObjectBuilder, JsonObject> + // col = JsonCollectors.toJsonObject(); + // final JsonObject out = (in.entrySet()).stream().collect(col); + // if (operationFailed(in, out)) { + // result.fail("toJsonObject()", + // "Output Stream value " + valueToString(out) + " shall be " + + // valueToString(in)); + // } + // } + // } + + /** + * Test collector returned by + * {@code toJsonObject(Function, Function)} + * method. This collector does not pack content of + * {@code Stream>} stream of + * {@link JsonParser#getObjectStream()} output. So it's not counterpart of + * this method. It works with {@code Stream}, which is + * {@link JsonParser#getArrayStream()} output and uses two {@link Function} + * implementations to build target object keys and values from + * {@code JsonValue} in the {@code Stream}. + * + * @param result + * Tests result record. + */ + private void testToJsonObjectCollector(final TestResult result) { + System.out.println(" - Collector returned by toJsonObject(Function,Function)"); + final JsonArray in = Json.createArrayBuilder() + .add(Json.createObjectBuilder().add("key", STR_NAME).add("value", + STR_VALUE)) + .add(Json.createObjectBuilder().add("key", INT_NAME).add("value", + INT_VALUE)) + .add(Json.createObjectBuilder().add("key", BOOL_NAME).add("value", + BOOL_VALUE)) + .add(Json.createObjectBuilder().add("key", OBJ_NAME).add("value", + OBJ_VALUE)) + .build(); + final JsonObject check = Json.createObjectBuilder().add(STR_NAME, STR_VALUE) + .add(INT_NAME, INT_VALUE).add(BOOL_NAME, BOOL_VALUE) + .add(OBJ_NAME, OBJ_VALUE).build(); + System.out.println(" Input: " + valueToString(in)); + final Collector col = JsonCollectors + .toJsonObject( + // Build key from stream value. + (JsonValue v) -> { + if (v.getValueType() == JsonValue.ValueType.OBJECT) + return v.asJsonObject().getString("key"); + throw new IllegalStateException("Value must be JsonObject"); + }, + // Build value from stream value. + (JsonValue v) -> { + if (v.getValueType() == JsonValue.ValueType.OBJECT) + return v.asJsonObject().get("value"); + throw new IllegalStateException("Value must be JsonObject"); + }); + final JsonObject out = in.getValuesAs(JsonObject.class).stream() + .collect(col); + if (operationFailed(out, check)) { + result.fail("toJsonObject(Function,Function)", "Output Stream value " + + valueToString(out) + " shall be " + valueToString(check)); + } + } + + /** + * Test collector returned by {@code groupingBy(Function)} + * method. This collector allows grouping of {@code Stream} using + * provided {@code Function)} function to define group + * identifiers based on {@code JsonValue} content. Test just groups JSON + * objects in the stream by {@code "office"} attribute. Default + * {@code toJsonArray()} collector is used so output is unsorted. + * + * @param result + * Tests result record. + */ + private void testSimpleGroupingByCollector(final TestResult result) { + System.out.println(" - Collector returned by groupingBy(Function)"); + final JsonObject check = Json.createObjectBuilder().add("Red", Json + .createArrayBuilder() + .add( + Json.createObjectBuilder().add("name", "John").add("office", "Red")) + .add(Json.createObjectBuilder().add("name", "Sarah").add("office", + "Red")) + .add( + Json.createObjectBuilder().add("name", "Rick").add("office", "Red")) + .build()) + .add("Blue", + Json.createArrayBuilder() + .add(Json.createObjectBuilder().add("name", "Bob").add("office", + "Blue")) + .add(Json.createObjectBuilder().add("name", "Tom").add("office", + "Blue")) + .add(Json.createObjectBuilder().add("name", "Jane") + .add("office", "Blue")) + .build()) + .add("Green", + Json.createArrayBuilder() + .add(Json.createObjectBuilder().add("name", "Peter") + .add("office", "Green")) + .add(Json.createObjectBuilder().add("name", "Peggy") + .add("office", "Green")) + .build()) + .build(); + System.out.println(" Input: " + valueToString(OBJ_ARRAY_GROUP)); + final Collector, JsonObject> col = JsonCollectors + .groupingBy((JsonValue v) -> { + if (v.getValueType() == JsonValue.ValueType.OBJECT) + return v.asJsonObject().getString("office"); + throw new IllegalStateException("Value must be JsonObject"); + }); + final JsonObject out = OBJ_ARRAY_GROUP.getValuesAs(JsonObject.class) + .stream().collect(col); + if (operationFailed(out, check)) { + result.fail("groupingBy(Function)", "Output Stream value " + + valueToString(out) + " shall be " + valueToString(check)); + } + } + + /** + * Builder to create sorted JsonArray with ordering by {@code "name"} + * attribute of {@code JsonObject}. + */ + private class ValueBuilder implements JsonArrayBuilder { + + /** Sorted collection of values. */ + private final TreeSet values; + + private ValueBuilder() { + values = new TreeSet<>((JsonValue v1, JsonValue v2) -> { + if (v1.getValueType() == JsonValue.ValueType.OBJECT + && v1.getValueType() == JsonValue.ValueType.OBJECT) { + return v1.asJsonObject().getString("name") + .compareTo(v2.asJsonObject().getString("name")); + } + throw new IllegalStateException("Values must be JsonObject"); + }); + } + + /** + * Builder accumulator method. + * + * @param value + * Value to be added to {@code JsonArray}. + * @return This builder instance. + */ + @Override + public JsonArrayBuilder add(JsonValue value) { + values.add(value); + return this; + } + + /** + * Builder combiner method. + * + * @param builder + * Builder containing values to be added to {@code JsonArray}. + * @return This builder instance. + */ + public ValueBuilder addAll(ValueBuilder builder) { + values.addAll(builder.values); + return this; + } + + /** + * Builder finisher method. + * + * @return {@code JsonArray} from current builder content. + */ + @Override + public JsonArray build() { + JsonArrayBuilder builder = Json.createArrayBuilder(); + for (JsonValue value : values) { + builder.add(value); + } + return builder.build(); + } + + @Override + public JsonArrayBuilder add(String value) { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonArrayBuilder add(BigDecimal value) { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonArrayBuilder add(BigInteger value) { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonArrayBuilder add(int value) { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonArrayBuilder add(long value) { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonArrayBuilder add(double value) { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonArrayBuilder add(boolean value) { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonArrayBuilder addNull() { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonArrayBuilder add(JsonObjectBuilder builder) { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + @Override + public JsonArrayBuilder add(JsonArrayBuilder builder) { + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body of + // generated + // methods, + // choose + // Tools | + // Templates. + } + + } + + /** + * Test collector returned by + * {@code groupingBy(Function,Collector)} + * method. This collector allows grouping of {@code Stream} using + * provided {@code Function)} function to define group + * identifiers based on {@code JsonValue} content and + * {@code Collector)}. Test groups JSON + * objects in the stream by {@code "office"} attribute. External collector is + * building sorted {@code JsonArray} so arrays for each office group are + * sorted. + * + * @param result + * Tests result record. + */ + private void testSortingGroupingByCollector(final TestResult result) { + System.out.println(" - Collector returned by groupingBy(Function,Collector)"); + final JsonObject check = Json.createObjectBuilder().add("Red", Json + .createArrayBuilder() + .add( + Json.createObjectBuilder().add("name", "John").add("office", "Red")) + .add( + Json.createObjectBuilder().add("name", "Rick").add("office", "Red")) + .add(Json.createObjectBuilder().add("name", "Sarah").add("office", + "Red")) + .build()) + .add("Blue", + Json.createArrayBuilder() + .add(Json.createObjectBuilder().add("name", "Bob").add("office", + "Blue")) + .add(Json.createObjectBuilder().add("name", "Jane") + .add("office", "Blue")) + .add(Json.createObjectBuilder().add("name", "Tom").add("office", + "Blue")) + .build()) + .add("Green", + Json.createArrayBuilder() + .add(Json.createObjectBuilder().add("name", "Peggy") + .add("office", "Green")) + .add(Json.createObjectBuilder().add("name", "Peter") + .add("office", "Green")) + .build()) + .build(); + Collector toArray = Collector.of( + ValueBuilder::new, JsonArrayBuilder::add, JsonArrayBuilder::addAll, + JsonArrayBuilder::build); + System.out.println(" Input: " + valueToString(OBJ_ARRAY_GROUP)); + final Collector, JsonObject> col = JsonCollectors + .groupingBy((JsonValue v) -> { + if (v.getValueType() == JsonValue.ValueType.OBJECT) + return v.asJsonObject().getString("office"); + throw new IllegalStateException("Value must be JsonObject"); + }, toArray); + final JsonObject out = OBJ_ARRAY_GROUP.getValuesAs(JsonObject.class) + .stream().collect(col); + if (operationFailed(out, check)) { + result.fail("groupingBy(Function,Collector)", "Output Stream value " + + valueToString(out) + " shall be " + valueToString(check)); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + System.out.println(" Checking " + valueToString(out)); + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/ArrayBuilder.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/ArrayBuilder.java new file mode 100644 index 00000000..63abcfe5 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/ArrayBuilder.java @@ -0,0 +1,290 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +import java.math.BigDecimal; +import java.math.BigInteger; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonValue; + +// $Id$ +/** + * {@link JsonArrayBuilder} manipulation helper. + */ +public class ArrayBuilder { + + /** + * Add {@code value} to provided JSON array builder. + * + * @param builder + * Target JSON array builder. + * @param value + * Value to be added at the end of the array. + * @return JSON array builder containing new {@code value}. + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonArrayBuilder add(final JsonArrayBuilder builder, + final Object value) { + switch (JsonValueType.getType(value)) { + case String: + return builder.add((String) value); + case Integer: + return builder.add(((Integer) value).intValue()); + case Long: + return builder.add(((Long) value).intValue()); + case BigInteger: + return builder.add(((BigInteger) value)); + case Double: + return builder.add(((Double) value).doubleValue()); + case BigDecimal: + return builder.add(((BigDecimal) value)); + case Boolean: + return builder.add(((Boolean) value).booleanValue()); + case JsonValue: + return builder.add((JsonValue) value); + case Null: + return builder.addNull(); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + + /** + * Add {@code value} at specified index to provided JSON array builder. + * + * @param builder + * Target JSON array builder. + * @param index + * Array index of value to be added. + * @param value + * Value to be added at the end of the array. + * @return JSON array builder containing new {@code value}. + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonArrayBuilder add(final JsonArrayBuilder builder, + final int index, final Object value) { + switch (JsonValueType.getType(value)) { + case String: + return builder.add(index, (String) value); + case Integer: + return builder.add(index, ((Integer) value).intValue()); + case Long: + return builder.add(index, ((Long) value).longValue()); + case BigInteger: + return builder.add(index, ((BigInteger) value)); + case Double: + return builder.add(index, ((Double) value).doubleValue()); + case BigDecimal: + return builder.add(index, ((BigDecimal) value)); + case Boolean: + return builder.add(index, ((Boolean) value).booleanValue()); + case JsonValue: + return builder.add(index, (JsonValue) value); + case Null: + return builder.addNull(index); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + + /** + * Add {@code null} to provided JSON array builder. Every call shall throw an + * exception which depends on selected type. + * + * @param builder + * Target JSON array builder. + * @param type + * Type of method argument to use.. + * @return JSON array builder containing new {@code value}. + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonArrayBuilder add(final JsonArrayBuilder builder, + final JsonValueType type) { + switch (type) { + case String: + return builder.add((String) null); + case Integer: + throw new UnsupportedOperationException( + "Value null is not supported for int"); + case Long: + throw new UnsupportedOperationException( + "Value null is not supported for long"); + case BigInteger: + return builder.add((BigInteger) null); + case Double: + throw new UnsupportedOperationException( + "Value null is not supported for double"); + case BigDecimal: + return builder.add((BigDecimal) null); + case Boolean: + return builder.add((Boolean) null); + case JsonValue: + return builder.add((JsonValue) null); + case Null: + throw new UnsupportedOperationException( + "Value null is not supported for addNull()"); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + + /** + * Add {@code null} to provided JSON array builder. Every call shall throw an + * exception which depends on selected type. + * + * @param builder + * Target JSON array builder. + * @param index + * Array index of value to be added. + * @param type + * Type of method argument to use.. + * @return JSON array builder containing new {@code value}. + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonArrayBuilder add(final JsonArrayBuilder builder, + final int index, final JsonValueType type) { + switch (type) { + case String: + return builder.add(index, (String) null); + case Integer: + throw new UnsupportedOperationException( + "Value null is not supported for int"); + case Long: + throw new UnsupportedOperationException( + "Value null is not supported for long"); + case BigInteger: + return builder.add(index, (BigInteger) null); + case Double: + throw new UnsupportedOperationException( + "Value null is not supported for double"); + case BigDecimal: + return builder.add(index, (BigDecimal) null); + case Boolean: + return builder.add(index, (Boolean) null); + case JsonValue: + return builder.add(index, (JsonValue) null); + case Null: + throw new UnsupportedOperationException( + "Value null is not supported for addNull()"); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + + /** + * Set {@code value} at specified index to provided JSON array builder. + * + * @param builder + * Target JSON array builder. + * @param index + * Array index of value to be added. + * @param value + * Value to be set at the end of the array. + * @return JSON array builder containing new {@code value}. + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonArrayBuilder set(final JsonArrayBuilder builder, + final int index, final Object value) { + switch (JsonValueType.getType(value)) { + case String: + return builder.set(index, (String) value); + case Integer: + return builder.set(index, ((Integer) value).intValue()); + case Long: + return builder.set(index, ((Long) value).longValue()); + case BigInteger: + return builder.set(index, ((BigInteger) value)); + case Double: + return builder.set(index, ((Double) value).doubleValue()); + case BigDecimal: + return builder.set(index, ((BigDecimal) value)); + case Boolean: + return builder.set(index, ((Boolean) value).booleanValue()); + case JsonValue: + return builder.set(index, (JsonValue) value); + case Null: + return builder.setNull(index); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + + /** + * Set {@code null} to provided JSON array builder. Every call shall throw an + * exception which depends on selected type. + * + * @param builder + * Target JSON array builder. + * @param index + * Array index of value to be added. + * @param type + * Type of method argument to use.. + * @return JSON array builder containing new {@code value}. + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonArrayBuilder set(final JsonArrayBuilder builder, + final int index, final JsonValueType type) { + switch (type) { + case String: + return builder.set(index, (String) null); + case Integer: + throw new UnsupportedOperationException( + "Value null is not supported for int"); + case Long: + throw new UnsupportedOperationException( + "Value null is not supported for long"); + case BigInteger: + return builder.set(index, (BigInteger) null); + case Double: + throw new UnsupportedOperationException( + "Value null is not supported for double"); + case BigDecimal: + return builder.set(index, (BigDecimal) null); + case Boolean: + return builder.set(index, (Boolean) null); + case JsonValue: + return builder.set(index, (JsonValue) null); + case Null: + throw new UnsupportedOperationException( + "Value null is not supported for addNull()"); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + + /** + * Remove {@code value} at specified index from provided JSON array builder. + * + * @param builder + * Target JSON array builder. + * @param index + * Array index of value to be added. + * @return JSON array builder containing new {@code value}. + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonArrayBuilder remove(final JsonArrayBuilder builder, + final int index) { + return builder.remove(index); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/JsonAssert.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/JsonAssert.java new file mode 100644 index 00000000..6afd3910 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/JsonAssert.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +import java.io.StringReader; +import java.math.BigDecimal; +import java.math.BigInteger; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonNumber; +import jakarta.json.JsonObject; +import jakarta.json.JsonReader; +import jakarta.json.JsonString; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.common.JSONP_Util.toStringJsonArray; +import static jakarta.jsonp.tck.common.JSONP_Util.toStringJsonObject; + +// $Id$ +/** + * JSON values assertions. + */ +public class JsonAssert { + + private static boolean assertEquals(final JsonObject expected, + final JsonObject actual, final String message) { + if (actual.equals(expected)) { + return true; + } else { + System.out.println(" " + message); + System.out.println(" Expected: " + toStringJsonObject(expected)); + System.out.println(" Actual: " + toStringJsonObject(actual)); + return false; + } + } + + private static boolean assertEquals(final JsonArray expected, + final JsonArray actual, final String message) { + if (actual.equals(expected)) { + return true; + } else { + System.out.println(" " + message); + System.out.println(" Expected: " + toStringJsonArray(expected)); + System.out.println(" Actual: " + toStringJsonArray(actual)); + return false; + } + } + + private static boolean assertEquals(final JsonString expected, + final JsonString actual, final String message) { + if (actual.equals(expected)) { + return true; + } else { + System.out.println(" " + message); + System.out.println(" Expected: " + expected.getString()); + System.out.println(" Actual: " + actual.getString()); + return false; + } + } + + private static boolean assertEquals(final JsonNumber expected, + final JsonNumber actual, final String message) { + if (actual.equals(expected)) { + return true; + } else { + System.out.println(" " + message); + System.out.println(" Expected: " + expected.toString()); + System.out.println(" Actual: " + actual.toString()); + return false; + } + } + + public static boolean assertEquals(final JsonValue expected, + final JsonValue actual, final String message) { + switch (expected.getValueType()) { + case OBJECT: + return assertEquals((JsonObject) expected, (JsonObject) actual, message); + case ARRAY: + return assertEquals((JsonArray) expected, (JsonArray) actual, message); + case STRING: + return assertEquals((JsonString) expected, (JsonString) actual, message); + case NUMBER: + return assertEquals((JsonNumber) expected, (JsonNumber) actual, message); + case TRUE: + case FALSE: + if (expected == actual) { + return true; + } else { + System.out.println(" " + message); + System.out.println(" Expected: " + expected.toString()); + System.out.println(" Actual: " + actual.toString()); + return false; + } + default: + if (actual.equals(expected)) { + return true; + } else { + System.out.println(" " + message); + System.out.println(" Expected: " + expected.toString()); + System.out.println(" Actual: " + actual.toString()); + return false; + } + } + } + + public static boolean assertEquals(final JsonValue expected, + final JsonValue actual) { + return assertEquals(expected, actual, "JSON mismatch"); + } + + /** + * Operation result expected. + * + * @param expected + * Expected modified JSON value. + * @param actual + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + public static boolean assertEquals(final Object expected, + final String actual) { + if (actual == null) { + return true; + } + try { + switch (JsonValueType.getType(expected)) { + case String: + String exp = '\"' + (String) expected + '\"'; + return exp.equals(actual); + case Integer: + return Integer.parseInt(actual) == (Integer) expected; + case Long: + return Long.parseLong(actual) == (Long) expected; + case BigInteger: + return (new BigInteger(actual)).equals(expected); + case Double: + return Double.parseDouble(actual) == (Double) expected; + case BigDecimal: + return (new BigDecimal(actual)).equals(expected); + case Boolean: + return Boolean.parseBoolean(actual) == (Boolean) expected; + case JsonValue: + try (final JsonReader reader = Json + .createReader(new StringReader(actual))) { + final JsonValue actVal = reader.readValue(); + return assertEquals((JsonValue) expected, actVal); + } + case Null: + try (final JsonReader reader = Json + .createReader(new StringReader(actual))) { + final JsonValue actVal = reader.readValue(); + return assertEquals(JsonValue.NULL, actVal); + } + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } catch (NumberFormatException ex) { + return true; + } + } + + /** + * Convert provided JSON value to human readable String. + * + * @param value + * Value to be converted. + * @return JSON value as human readable String. + */ + public static String valueToString(final JsonValue value) { + switch (value.getValueType()) { + case OBJECT: + return toStringJsonObject((JsonObject) value); + case ARRAY: + return toStringJsonArray((JsonArray) value); + case STRING: + return ((JsonString) value).getString(); + case NUMBER: + return ((JsonNumber) value).toString(); + case TRUE: + return Boolean.toString(true); + case FALSE: + return Boolean.toString(false); + case NULL: + return "null"; + default: + throw new IllegalArgumentException("Unknown value type"); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/JsonIO.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/JsonIO.java new file mode 100644 index 00000000..1261a5e6 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/JsonIO.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +import java.io.StringReader; +import jakarta.json.Json; +import jakarta.json.JsonValue; + +// $Id$ +/** + * Read and write JSON values. + */ +public class JsonIO { + /** + * Reads JSON value from {@code String}. + * + * @param json + * JSON value to be read. + * @return JSON value from provided {@code String}. + */ + public static JsonValue read(final String json) { + return Json.createReader(new StringReader(json)).readValue(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/JsonValueType.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/JsonValueType.java new file mode 100644 index 00000000..f8da9829 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/JsonValueType.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import jakarta.json.JsonValue; + +// $Id$ +/** + * Identifiers of types used as JSON value. + */ +public enum JsonValueType { + /** JsonValue is String. */ + String, + /** JsonValue is Integer. */ + Integer, + /** JsonValue is Long. */ + Long, + /** JsonValue is BigInteger. */ + BigInteger, + /** JsonValue is Double. */ + Double, + /** JsonValue is BigDecimal. */ + BigDecimal, + /** JsonValue is Boolean. */ + Boolean, + /** JsonValue is common JSON value. */ + JsonValue, + /** JsonValue is null. */ + Null; + + /** Size of this enumeration. */ + private static final int SIZE = JsonValueType.values().length; + + /** Name to value {@code Map}. */ + private static final Map VALUES = new HashMap<>(SIZE); + // Name to value Map initialization. + static { + for (int i = 0; i < SIZE; i++) + VALUES.put(JsonValueType.values()[i].name(), JsonValueType.values()[i]); + } + + /** + * Returns JSON value identifier for provided class. + * + * @param c + * JSON value class. + * @return JSON value identifier for provided class. + */ + public static JsonValueType getType(final Class c) { + JsonValueType type = VALUES.get(c.getSimpleName()); + if (type != null) { + return type; + } + // Interface hierarchy is a tree so stack machine is required to go trough + // it. + final LinkedList stack = new LinkedList(); + for (final Class i : c.getInterfaces()) { + stack.push(i); + } + while (!stack.isEmpty()) { + final Class i = stack.pop(); + type = VALUES.get(i.getSimpleName()); + if (type != null) { + return type; + } + for (final Class j : i.getInterfaces()) { + stack.push(j); + } + } + throw new IllegalArgumentException( + "Unsupported JSON value type: " + c.getSimpleName()); + } + + /** + * Returns JSON value identifier for provided value. + * + * @param value + * JSON value. + * @return JSON value identifier for provided class. + */ + public static JsonValueType getType(final Object value) { + return value != null ? getType(value.getClass()) : Null; + } + + /** + * Convert provided value to {@code String} which is part of JSON document. + * + * @param value + * Value be be converted to {@code String}. + * @return Value converted to {@code String}. + */ + public static String toStringValue(final Object value) { + switch (getType(value)) { + case String: + return '"' + ((String) value) + '"'; + case Integer: + return ((Integer) value).toString(); + case Long: + return ((Long) value).toString(); + case BigInteger: + return ((BigInteger) value).toString(); + case Double: + return ((Double) value).toString(); + case BigDecimal: + return ((BigDecimal) value).toString(); + case Boolean: + return ((Boolean) value).toString(); + case JsonValue: + return JsonAssert.valueToString((JsonValue) value); + case Null: + return SimpleValues.NULL; + default: + throw new IllegalArgumentException( + "Unsupported JSON value type: " + value.getClass().getSimpleName()); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/MergeRFCObject.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/MergeRFCObject.java new file mode 100644 index 00000000..54b6279e --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/MergeRFCObject.java @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonValue; + +/* + * $Id$ + */ +/** + * {@see RFC 7396}: JavaScript + * Object Notation (JSON) Merge Patch compatibility sample object.
+ * Object structure is defined in + * {@see RFC 7396: 3. + * Example}. + */ +public class MergeRFCObject { + + // Following values define JSON object keys from RFC 7396: 3. Example + /** RFC 7396 sample JSON object key for {@code /title}. */ + public static final String KEY_TITLE = "title"; + + /** RFC 7396 sample JSON object key for {@code /author/givenName}. */ + public static final String KEY_GIVEN_NAME = "givenName"; + + /** RFC 7396 sample JSON object key for {@code /author/familyName}. */ + public static final String KEY_FAMILY_NAME = "familyName"; + + /** RFC 7396 sample JSON object key for {@code /author}. */ + public static final String KEY_AUTHOR = "author"; + + /** RFC 7396 sample JSON object key for {@code /tags}. */ + public static final String KEY_TAGS = "tags"; + + /** RFC 7396 sample JSON object key for {@code /content}. */ + public static final String KEY_CONTENT = "content"; + + /** RFC 7396 sample JSON object key for {@code /phoneNumber}. */ + public static final String KEY_PHONE_NUMBER = "phoneNumber"; + + // Following values define JSON object source values from RFC 7396: 3. Example + /** RFC 7396 sample JSON object source value for {@code /title}. */ + public static final String VAL_SRC_TITLE = "Goodbye!"; + + /** RFC 7396 sample JSON object source value for {@code /author/givenName}. */ + public static final String VAL_SRC_GIVEN_NAME = "John"; + + /** + * RFC 7396 sample JSON object source value for {@code /author/familyName}. + */ + public static final String VAL_SRC_FAMILY_NAME = "Doe"; + + /** RFC 7396 sample JSON object source value for {@code /author}. */ + public static final JsonObject VAL_SRC_AUTHOR = SimpleValues + .createSimpleObject(new String[] { KEY_GIVEN_NAME, KEY_FAMILY_NAME }, + new Object[] { VAL_SRC_GIVEN_NAME, VAL_SRC_FAMILY_NAME }); + + /** RFC 7396 sample JSON object source value for {@code /tags/0}. */ + public static final String VAL_SRC_TAGS_0 = "example"; + + /** RFC 7396 sample JSON object source value for {@code /tags/1}. */ + public static final String VAL_SRC_TAGS_1 = "sample"; + + /** RFC 7396 sample JSON object source value for {@code /tags}. */ + public static final JsonArray VAL_SRC_TAGS = SimpleValues + .createStringArray(new String[] { VAL_SRC_TAGS_0, VAL_SRC_TAGS_1 }); + + /** RFC 7396 sample JSON object source value for {@code /content}. */ + public static final String VAL_SRC_CONTENT = "This will be unchanged"; + + // Following values define JSON object target values from RFC 7396: 3. Example + /** RFC 7396 sample JSON object target value for {@code /title}. */ + public static final String VAL_TRG_TITLE = "Hello!"; + + /** RFC 7396 sample JSON object target value for {@code /author}. */ + public static final JsonObject VAL_TRG_AUTHOR = SimpleValues + .createSimpleObject(new String[] { KEY_GIVEN_NAME }, + new Object[] { VAL_SRC_GIVEN_NAME }); + + /** RFC 7396 sample JSON object target value for {@code /phoneNumber}. */ + public static final String VAL_TRG_PHONE_NUMBER = "+01-123-456-7890"; + + /** RFC 7396 sample JSON object target value for {@code /tags/0}. */ + public static final String VAL_TRG_TAGS_0 = "example"; + + /** RFC 7396 sample JSON object target value for {@code /tags}. */ + public static final JsonArray VAL_TRG_TAGS = SimpleValues + .createStringArray(new String[] { VAL_TRG_TAGS_0 }); + + // Following values define JSON object patch values from RFC 7396: 3. Example + /** RFC 7396 sample JSON object patch value for {@code /author/familyName}. */ + public static final JsonValue VAL_PATCH_FAMILY_NAME = JsonValue.NULL; + + /** RFC 7396 sample JSON object patch value for {@code /author}. */ + public static final JsonObject VAL_PATCH_AUTHOR = SimpleValues + .createSimpleObject(new String[] { KEY_FAMILY_NAME }, + new Object[] { VAL_PATCH_FAMILY_NAME }); + + /** + * Create {@see RFC + * 7396 example} source JSON object. + * + * @return Source object from example. + */ + public static JsonObject createRFCSourceObject() { + return Json.createObjectBuilder().add(KEY_TITLE, VAL_SRC_TITLE) + .add(KEY_AUTHOR, VAL_SRC_AUTHOR).add(KEY_TAGS, VAL_SRC_TAGS) + .add(KEY_CONTENT, VAL_SRC_CONTENT).build(); + } + + /** + * Create {@see RFC + * 7396 example} target JSON object. + * + * @return Target object from example. + */ + public static JsonObject createRFCTargetObject() { + return Json.createObjectBuilder().add(KEY_TITLE, VAL_TRG_TITLE) + .add(KEY_AUTHOR, VAL_TRG_AUTHOR).add(KEY_TAGS, VAL_TRG_TAGS) + .add(KEY_CONTENT, VAL_SRC_CONTENT) + .add(KEY_PHONE_NUMBER, VAL_TRG_PHONE_NUMBER).build(); + } + + /** + * Create {@see RFC + * 7396 example} patch JSON object. + * + * @return Patch object from example. + */ + public static JsonObject createRFCPatchObject() { + return Json.createObjectBuilder().add(KEY_TITLE, VAL_TRG_TITLE) + .add(KEY_PHONE_NUMBER, VAL_TRG_PHONE_NUMBER) + .add(KEY_AUTHOR, VAL_PATCH_AUTHOR).add(KEY_TAGS, VAL_TRG_TAGS).build(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/ObjectBuilder.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/ObjectBuilder.java new file mode 100644 index 00000000..e31f468a --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/ObjectBuilder.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +import java.math.BigDecimal; +import java.math.BigInteger; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonValue; + +// $Id$ +/** + * {@link JsonObjectBuilder} manipulation helper. + */ +public class ObjectBuilder { + + /** + * Add {@code value} with {@code name} to provided JSON object builder. + * + * @param builder + * Target JSON object builder. + * @param name + * Name of value to be added. + * @param value + * Value to be added. + * @return JSON object builder containing new {@code value}. + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonObjectBuilder add(final JsonObjectBuilder builder, + final String name, final Object value) { + switch (JsonValueType.getType(value)) { + case String: + return builder.add(name, (String) value); + case Integer: + return builder.add(name, ((Integer) value).intValue()); + case Long: + return builder.add(name, ((Long) value).intValue()); + case BigInteger: + return builder.add(name, ((BigInteger) value)); + case Double: + return builder.add(name, ((Double) value).doubleValue()); + case BigDecimal: + return builder.add(name, ((BigDecimal) value)); + case Boolean: + return builder.add(name, ((Boolean) value).booleanValue()); + case JsonValue: + return builder.add(name, (JsonValue) value); + case Null: + return builder.addNull(name); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/PointerRFCObject.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/PointerRFCObject.java new file mode 100644 index 00000000..b648d3c0 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/PointerRFCObject.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; + +/* + * $Id$ + */ +/** + * {@see RFC 6901}: JavaScript + * Object Notation (JSON) Pointer compatibility sample object.
+ * Object structure is defined in + * {@see RFC 6901: 5. + * JSON String Representation}. + */ +public class PointerRFCObject { + + // Following values define JSON object from + // RFC 6901: 5. JSON String Representation + // https://tools.ietf.org/html/rfc6901#section-5 + /** RFC 6901 sample JSON object key for the whole document. */ + public static final String RFC_KEY_WHOLE = ""; + + /** RFC 6901 sample JSON object key for 1st value. */ + public static final String RFC_KEY1 = "foo"; + + /** RFC 6901 sample JSON object pointer for 1st value. */ + public static final String RFC_PTR1 = "/foo"; + + /** RFC 6901 sample JSON object pointer for 1st item of 1st value. */ + public static final String RFC_PTR1_ITEM1 = "/foo/0"; + + /** RFC 6901 sample JSON object pointer for 2nd item of 1st value. */ + public static final String RFC_PTR1_ITEM2 = "/foo/1"; + + /** RFC 6901 sample JSON object 1st value: array 1st item. */ + public static final String RFC_VAL1_ITEM1 = "bar"; + + /** RFC 6901 sample JSON object 1st value: array 2nd item. */ + public static final String RFC_VAL1_ITEM2 = "baz"; + + /** RFC 6901 sample JSON object 1st value. */ + public static final JsonArray RFC_VAL1 = SimpleValues + .createStringArray(RFC_VAL1_ITEM1, RFC_VAL1_ITEM2); + + /** RFC 6901 sample JSON object key for 2nd value. */ + public static final String RFC_KEY2 = ""; + + /** RFC 6901 sample JSON object pointer for 2nd value. */ + public static final String RFC_PTR2 = "/"; + + /** RFC 6901 sample JSON object 2nd value. */ + public static final int RFC_VAL2 = 0; + + /** RFC 6901 sample JSON object key for 3rd value. */ + public static final String RFC_KEY3 = "a/b"; + + /** RFC 6901 sample JSON object pointer for 3rd value. */ + public static final String RFC_PTR3_ENC = "/a~1b"; + + /** RFC 6901 sample JSON object pointer for 3rd value. */ + public static final String RFC_PTR3 = "/a/b"; + + /** RFC 6901 sample JSON object 3rd value. */ + public static final int RFC_VAL3 = 1; + + /** RFC 6901 sample JSON object key for 4th value. */ + public static final String RFC_KEY4 = "c%d"; + + /** RFC 6901 sample JSON object pointer for 4th value. */ + public static final String RFC_PTR4 = "/c%d"; + + /** RFC 6901 sample JSON object 4th value. */ + public static final int RFC_VAL4 = 2; + + /** RFC 6901 sample JSON object key for 5th value. */ + public static final String RFC_KEY5 = "e^f"; + + /** RFC 6901 sample JSON object pointer for 5th value. */ + public static final String RFC_PTR5 = "/e^f"; + + /** RFC 6901 sample JSON object 5th value. */ + public static final int RFC_VAL5 = 3; + + /** RFC 6901 sample JSON object key for 6th value. */ + public static final String RFC_KEY6 = "g|h"; + + /** RFC 6901 sample JSON object pointer for 6th value. */ + public static final String RFC_PTR6 = "/g|h"; + + /** RFC 6901 sample JSON object 6th value. */ + public static final int RFC_VAL6 = 4; + + /** RFC 6901 sample JSON object key for 7th value. */ + public static final String RFC_KEY7 = "i\\j"; + + /** RFC 6901 sample JSON object pointer for 7th value. */ + public static final String RFC_PTR7 = "/i\\j"; + + /** RFC 6901 sample JSON object 7th value. */ + public static final int RFC_VAL7 = 5; + + /** RFC 6901 sample JSON object key for 8th value. */ + public static final String RFC_KEY8 = "k\"l"; + + /** RFC 6901 sample JSON object pointer for 8th value. */ + public static final String RFC_PTR8 = "/k\"l"; + + /** RFC 6901 sample JSON object 8th value. */ + public static final int RFC_VAL8 = 6; + + /** RFC 6901 sample JSON object key for 9th value. */ + public static final String RFC_KEY9 = " "; + + /** RFC 6901 sample JSON object pointer for 9th value. */ + public static final String RFC_PTR9 = "/ "; + + /** RFC 6901 sample JSON object 9th value. */ + public static final int RFC_VAL9 = 7; + + /** RFC 6901 sample JSON object key for 10th value. */ + public static final String RFC_KEY10 = "m~n"; + + /** RFC 6901 sample JSON object encoded pointer for 10th value. */ + public static final String RFC_KEY10_ENC = "/m~0n"; + + /** RFC 6901 sample JSON object pointer for 10th value. */ + public static final String RFC_PTR10 = "/m~n"; + + /** RFC 6901 sample JSON object 10th value. */ + public static final int RFC_VAL10 = 8; + + /** RFC 6901 sample JSON object key for 11th value. */ + public static final String RFC_KEY11 = "o~1p"; + + /** RFC 6901 sample JSON object encoded pointer for 11th value. */ + public static final String RFC_PTR11_ENC = "/o~01p"; + + /** RFC 6901 sample JSON object pointer for 11th value. */ + public static final String RFC_PTR11 = "/o~1p"; + + /** RFC 6901 sample JSON object 11th value. */ + public static final int RFC_VAL11 = 9; + + /** + * Creates RFC 6901 sample JSON object. + * {@see RFC 6901: 5. + * JSON String Representation} + * + * @return RFC 6901 sample JSON object. + */ + public static JsonObject createRFC6901Object() { + return Json.createObjectBuilder().add(RFC_KEY1, RFC_VAL1) + .add(RFC_KEY2, RFC_VAL2).add(RFC_KEY3, RFC_VAL3).add(RFC_KEY4, RFC_VAL4) + .add(RFC_KEY5, RFC_VAL5).add(RFC_KEY6, RFC_VAL6).add(RFC_KEY7, RFC_VAL7) + .add(RFC_KEY8, RFC_VAL8).add(RFC_KEY9, RFC_VAL9) + .add(RFC_KEY10, RFC_VAL10).add(RFC_KEY11, RFC_VAL11).build(); + } + + /** + * Create an instance of RFC 6901 object class is not allowed. + */ + private PointerRFCObject() { + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/SimpleValues.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/SimpleValues.java new file mode 100644 index 00000000..7ebe2b5f --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/SimpleValues.java @@ -0,0 +1,1155 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +import java.io.StringWriter; +import java.math.BigDecimal; +import java.math.BigInteger; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonException; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonPatch; +import jakarta.json.JsonValue; +import jakarta.json.JsonWriter; + +// $Id$ +/** + * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
+ * {@see RFC 6902}. + *

+ * Build various simple values for testing. + */ +public class SimpleValues { + + /** Name of JSON {@code String} value used in tests. */ + public static final String STR_NAME = "address"; + + /** Path of JSON {@code String} value used in tests. */ + public static final String STR_PATH = "/" + STR_NAME; + + /** JSON {@code String} value used in tests. */ + public static final String STR_VALUE = "In a galaxy far far away"; + + /** JSON {@code String} second value used in tests. */ + public static final String STR_VALUE2 = "In a land of myth"; + + /** Name of JSON {@code int} value used in tests. */ + public static final String INT_NAME = "age"; + + /** Path of JSON {@code int} value used in tests. */ + public static final String INT_PATH = "/" + INT_NAME; + + /** JSON {@code int} value used in tests. */ + public static final int INT_VALUE = 42; + + /** JSON {@code int} second value used in tests. */ + public static final int INT_VALUE2 = 32; + + /** Name of JSON {@code boolean} value used in tests. */ + public static final String BOOL_NAME = "married"; + + /** Path of JSON {@code boolean} value used in tests. */ + public static final String BOOL_PATH = "/" + BOOL_NAME; + + /** JSON {@code boolean} value used in tests. */ + public static final boolean BOOL_VALUE = true; + + /** JSON {@code boolean} second value used in tests. */ + public static final boolean BOOL_VALUE2 = false; + + /** Name of JSON {@code JsonObject} value used in tests. */ + public static final String OBJ_NAME = "wife"; + + /** Path of JSON {@code JsonObject} value used in tests. */ + public static final String OBJ_PATH = "/" + OBJ_NAME; + + /** JSON {@code JsonObject} value used in tests. */ + public static final JsonObject OBJ_VALUE = createSimpleObject( + new String[] { "name", "age" }, new Object[] { "Sarah Connor", 32 }); + + /** JSON {@code JsonObject} second value used in tests. */ + public static final JsonObject OBJ_VALUE2 = createSimpleObject( + new String[] { "name", "age" }, new Object[] { "Kyle Reese", 35 }); + + /** Name of JSON default value stored in simple object. */ + public static final String DEF_NAME = "name"; + + /** Name of JSON default value stored in simple object. */ + public static final String DEF_PATH = "/" + DEF_NAME; + + /** JSON default value stored in simple object. */ + public static final String DEF_VALUE = "John Smith"; + + /** Name of JSON object stored in compound object. */ + public static final String DEF_OBJ_NAME = "child"; + + /** Path of JSON object stored in compound object. */ + public static final String DEF_OBJ_PATH = "/child"; + + /** JSON default object stored in simple object. */ + public static final JsonObject DEF_OBJ_VALUE = createSimpleObject( + new String[] { "name", "age" }, new Object[] { "John Connor", 6 }); + + /** JSON default object stored in simple object with name changed. */ + public static final JsonObject DEF_OBJ_VALUE2 = createSimpleObject( + new String[] { "name", "age" }, new Object[] { "John Smith", 6 }); + + /** Value of JSON {@code String} array at index 0. */ + public static final String STR_VALUE_1 = "First value"; + + /** Value of JSON {@code String} array at index 1. */ + public static final String STR_VALUE_2 = "Second value"; + + /** Value of JSON {@code String} array at index 2. */ + public static final String STR_VALUE_3 = "Third value"; + + /** Value of JSON {@code String} array at index 3. */ + public static final String STR_VALUE_4 = "Fourth value"; + + /** Value of JSON {@code String} array at index 4. */ + public static final String STR_VALUE_5 = "Fifth value"; + + /** Value of JSON {@code String} array at index 5. */ + public static final String STR_VALUE_6 = "Sixth value"; + + /** Value of JSON {@code String} array at index 6. */ + public static final String STR_VALUE_7 = "Seventh value"; + + /** Value of JSON {@code int} array at index 0. */ + public static final int INT_VALUE_1 = 1; + + /** Value of JSON {@code int} array at index 1. */ + public static final int INT_VALUE_2 = 2; + + /** Value of JSON {@code int} array at index 2. */ + public static final int INT_VALUE_3 = 3; + + /** Value of JSON {@code int} array at index 3. */ + public static final int INT_VALUE_4 = 4; + + /** Value of JSON {@code int} array at index 4. */ + public static final int INT_VALUE_5 = 5; + + /** Value of JSON {@code JsonObject} array at index 0. */ + public static final JsonObject OBJ_VALUE_1 = createSimpleObject( + new String[] { "first" }, new String[] { STR_VALUE_1 }); + + /** Value of JSON {@code JsonObject} array at index 1. */ + public static final JsonObject OBJ_VALUE_2 = createSimpleObject( + new String[] { "second" }, new String[] { STR_VALUE_2 }); + + /** Value of JSON {@code JsonObject} array at index 2. */ + public static final JsonObject OBJ_VALUE_3 = createSimpleObject( + new String[] { "third" }, new String[] { STR_VALUE_3 }); + + /** Value of JSON {@code JsonObject} array at index 3. */ + public static final JsonObject OBJ_VALUE_4 = createSimpleObject( + new String[] { "fourth" }, new String[] { STR_VALUE_4 }); + + /** Value of JSON {@code JsonObject} array at index 4. */ + public static final JsonObject OBJ_VALUE_5 = createSimpleObject( + new String[] { "fifth" }, new String[] { STR_VALUE_5 }); + + /** JSON {@code boolean} value: {@code true}. */ + public static final boolean BOOL_TRUE = true; + + /** JSON {@code boolean} value: {@code false}. */ + public static final boolean BOOL_FALSE = false; + + /** JSON {@code long} value used in tests. */ + public static final long LNG_VALUE = Long.MAX_VALUE - 42; + + /** JSON {@code BigInteger} value used in tests. */ + public static final BigInteger BIN_VALUE = new BigInteger( + "123456789012345678901234567890"); + + /** JSON {@code double} value used in tests. */ + public static final double DBL_VALUE = 0x1.f5c926b3a0942P+1014; + + /** JSON {@code BigDecimal} value used in tests. */ + public static final BigDecimal BDC_VALUE = new BigDecimal( + new BigInteger("1234567890123456789012345678901234567890"), 10); + + /** Message content: null String. */ + public static final String NULL = "null"; + + /** + * Creates empty JSON object. + * + * @return Empty JSON object. + */ + public static JsonObject createEmptyObject() { + return Json.createObjectBuilder().build(); + } + + /** + * Creates empty JSON object after ADD STR_NAME STR_VALUE operation. + * + * @return Empty JSON object after ADD STR_NAME STR_VALUE operation. + */ + public static JsonObject createSimpleObjectStr() { + return Json.createObjectBuilder().add(STR_NAME, STR_VALUE).build(); + } + + /** + * Creates empty JSON object after ADD INT_NAME INT_VALUE operation. + * + * @return Empty JSON object after ADD INT_NAME INT_VALUE operation. + */ + public static JsonObject createSimpleObjectInt() { + return Json.createObjectBuilder().add(INT_NAME, INT_VALUE).build(); + } + + /** + * Creates empty JSON object after ADD BOOL_NAME BOOL_VALUE operation. + * + * @return Empty JSON object after ADD BOOL_NAME BOOL_VALUE operation. + */ + public static JsonObject createSimpleObjectBool() { + return Json.createObjectBuilder().add(BOOL_NAME, BOOL_VALUE).build(); + } + + /** + * Creates empty JSON object after ADD OBJ_NAME OBJ_VALUE operation. + * + * @return Empty JSON object after ADD OBJ_NAME OBJ_VALUE operation. + */ + public static JsonObject createSimpleObjectObject() { + return Json.createObjectBuilder().add(OBJ_NAME, OBJ_VALUE).build(); + } + + /** + * Creates JSON patch to remove STR_NAME attribute from object. + * + * @return JSON patch + */ + public static JsonObject createPatchRemoveStr() { + return Json.createObjectBuilder().add(STR_NAME, JsonValue.NULL).build(); + } + + /** + * Creates JSON patch to remove INT_NAME attribute from object. + * + * @return JSON patch + */ + public static JsonObject createPatchRemoveInt() { + return Json.createObjectBuilder().add(INT_NAME, JsonValue.NULL).build(); + } + + /** + * Creates JSON patch to remove BOOL_NAME attribute from object. + * + * @return JSON patch + */ + public static JsonObject createPatchRemoveBool() { + return Json.createObjectBuilder().add(BOOL_NAME, JsonValue.NULL).build(); + } + + /** + * Creates JSON patch to remove OBJ_NAME attribute from object. + * + * @return JSON patch + */ + public static JsonObject createPatchRemoveObject() { + return Json.createObjectBuilder().add(OBJ_NAME, JsonValue.NULL).build(); + } + + /** + * Creates empty JSON array. + * + * @return Empty JSON array. + */ + public static JsonArray createEmptyArray() { + return Json.createArrayBuilder().build(); + } + + /** + * Creates empty JSON array after ADD STR_VALUE operation. + * + * @return Empty JSON array after ADD STR_VALUE operation. + */ + public static JsonArray createEmptyArrayWithStr() { + return Json.createArrayBuilder().add(STR_VALUE).build(); + } + + /** + * Creates empty JSON array after ADD INT_VALUE operation. + * + * @return Empty JSON array after ADD INT_VALUE operation. + */ + public static JsonArray createEmptyArrayWithInt() { + return Json.createArrayBuilder().add(INT_VALUE).build(); + } + + /** + * Creates empty JSON array after ADD BOOL_VALUE operation. + * + * @return Empty JSON array after ADD BOOL_VALUE operation. + */ + public static JsonArray createEmptyArrayWithBool() { + return Json.createArrayBuilder().add(BOOL_VALUE).build(); + } + + /** + * Creates empty JSON array after ADD OBJ_VALUE operation. + * + * @return Empty JSON array after ADD OBJ_VALUE operation. + */ + public static JsonArray createEmptyArrayWithObject() { + return Json.createArrayBuilder().add(OBJ_VALUE).build(); + } + + /** + * Creates simple JSON object. + * + * @return Simple JSON object. + */ + public static JsonObject createSimpleObject() { + return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE).build(); + } + + /** + * Creates simple JSON object after ADD STR_NAME STR_VALUE operation. + * + * @return Simple JSON object after ADD STR_NAME STR_VALUE operation. + */ + public static JsonObject createSimpleObjectWithStr() { + return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) + .add(STR_NAME, STR_VALUE).build(); + } + + /** + * Creates simple JSON object after REPLACE STR_NAME STR_VALUE operation. + * + * @return Simple JSON object after REPLACE STR_NAME STR_VALUE operation. + */ + public static JsonObject createSimpleObjectReplaceStr() { + return Json.createObjectBuilder().add(STR_NAME, STR_VALUE2).build(); + } + + /** + * Creates simple JSON object after MOVE STR_NAME DEF_NAME operation. + * + * @return Simple JSON object after MOVE STR_NAME DEF_NAME operation. + */ + public static JsonObject createSimpleObjectMoveStr() { + return Json.createObjectBuilder().add(DEF_NAME, STR_VALUE).build(); + } + + /** + * Creates simple JSON object after COPY STR_NAME DEF_NAME operation. + * + * @return Simple JSON object after COPY STR_NAME DEF_NAME operation. + */ + public static JsonObject createSimpleObjectCopyStr() { + return Json.createObjectBuilder().add(STR_NAME, STR_VALUE) + .add(DEF_NAME, STR_VALUE).build(); + } + + /** + * Creates simple JSON object after ADD INT_NAME INT_VALUE operation. + * + * @return Simple JSON object after ADD INT_NAME INT_VALUE operation. + */ + public static JsonObject createSimpleObjectWithInt() { + return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) + .add(INT_NAME, INT_VALUE).build(); + } + + /** + * Creates simple JSON object after REPLACE INT_NAME INT_VALUE operation. + * + * @return Simple JSON object after REPLACE INT_NAME INT_VALUE operation. + */ + public static JsonObject createSimpleObjectReplaceInt() { + return Json.createObjectBuilder().add(INT_NAME, INT_VALUE2).build(); + } + + /** + * Creates simple JSON object after MOVE INT_NAME DEF_NAME operation. + * + * @return Simple JSON object after MOVE INT_NAME DEF_NAME operation. + */ + public static JsonObject createSimpleObjectMoveInt() { + return Json.createObjectBuilder().add(DEF_NAME, INT_VALUE).build(); + } + + /** + * Creates simple JSON object after COPY INT_NAME DEF_NAME operation. + * + * @return Simple JSON object after COPY INT_NAME DEF_NAME operation. + */ + public static JsonObject createSimpleObjectCopyInt() { + return Json.createObjectBuilder().add(INT_NAME, INT_VALUE) + .add(DEF_NAME, INT_VALUE).build(); + } + + /** + * Creates simple JSON object after ADD BOOL_NAME BOOL_VALUE operation. + * + * @return Simple JSON object after ADD BOOL_NAME BOOL_VALUE operation. + */ + public static JsonObject createSimpleObjectWithBool() { + return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) + .add(BOOL_NAME, BOOL_VALUE).build(); + } + + /** + * Creates simple JSON object after REPLACE BOOL_NAME BOOL_VALUE operation. + * + * @return Simple JSON object after REPLACE BOOL_NAME BOOL_VALUE operation. + */ + public static JsonObject createSimpleObjectReplaceBool() { + return Json.createObjectBuilder().add(BOOL_NAME, BOOL_VALUE2).build(); + } + + /** + * Creates simple JSON object after MOVE BOOL_NAME DEF_NAME operation. + * + * @return Simple JSON object after MOVE BOOL_NAME DEF_NAME operation. + */ + public static JsonObject createSimpleObjectMoveBool() { + return Json.createObjectBuilder().add(DEF_NAME, BOOL_VALUE).build(); + } + + /** + * Creates simple JSON object after COPY BOOL_NAME DEF_NAME operation. + * + * @return Simple JSON object after COPY BOOL_NAME DEF_NAME operation. + */ + public static JsonObject createSimpleObjectCopyBool() { + return Json.createObjectBuilder().add(BOOL_NAME, BOOL_VALUE) + .add(DEF_NAME, BOOL_VALUE).build(); + } + + /** + * Creates simple JSON object. + * + * @return Simple JSON object. + */ + public static JsonObject createCompoundObject() { + return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) + .add(DEF_OBJ_NAME, DEF_OBJ_VALUE).build(); + } + + /** + * Creates simple JSON object after ADD OBJ_NAME OBJ_VALUE operation. + * + * @return Simple JSON object after ADD OBJ_NAME OBJ_VALUE operation. + */ + public static JsonObject createCompoundObjectWithObject() { + return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) + .add(DEF_OBJ_NAME, DEF_OBJ_VALUE).add(OBJ_NAME, OBJ_VALUE).build(); + } + + /** + * Creates simple JSON object after ADD OBJ_NAME OBJ_VALUE operation. + * + * @return Simple JSON object after ADD OBJ_NAME OBJ_VALUE operation. + */ + public static JsonObject createCompoundObjectReplaceObject() { + return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) + .add(DEF_OBJ_NAME, DEF_OBJ_VALUE).add(OBJ_NAME, OBJ_VALUE2).build(); + } + + /** + * Creates simple JSON object after MOVE DEF_PATH DEF_OBJ_PATH+DEF_PATH. + * + * @return Simple JSON object. + */ + public static JsonObject createCompoundObjectMoveValue() { + return Json.createObjectBuilder().add(DEF_OBJ_NAME, DEF_OBJ_VALUE2).build(); + } + + /** + * Creates simple JSON object after COPY DEF_PATH DEF_OBJ_PATH+DEF_PATH. + * + * @return Simple JSON object. + */ + public static JsonObject createCompoundObjectCopyValue() { + return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) + .add(DEF_OBJ_NAME, DEF_OBJ_VALUE2).build(); + } + + /** + * Creates simple JSON object after MOVE OBJ_NAME DEF_NAME operation. + * + * @return Simple JSON object after MOVE OBJ_NAME DEF_NAME operation. + */ + public static JsonObject createSimpleObjectMoveObject() { + return Json.createObjectBuilder().add(DEF_NAME, OBJ_VALUE).build(); + } + + /** + * Creates simple JSON object after COPY OBJ_NAME DEF_NAME operation. + * + * @return Simple JSON object after COPY OBJ_NAME DEF_NAME operation. + */ + public static JsonObject createSimpleObjectCopyObject() { + return Json.createObjectBuilder().add(OBJ_NAME, OBJ_VALUE) + .add(DEF_NAME, OBJ_VALUE).build(); + } + + /** + * Creates compound JSON object after ADD DEF_OBJ_NAME, + * createSimpleStringArray5(). + * + * @return compound JSON object with ADD operation applied. + */ + public static JsonObject createCompoundObjectWithObjectReplaced() { + return Json.createObjectBuilder().add(DEF_NAME, DEF_VALUE) + .add(DEF_OBJ_NAME, createSimpleStringArray5()).build(); + } + + /** + * Creates simple JSON object with provided {@code name[i]} and + * {@code value[i]} pairs. + * + * @param names + * Names of JSON values to be added. Pairs of {@code names[i]} and + * {@code values[i]} are used for add operations. + * @param values + * JSON values to be added for specified names. + * @return Simple JSON object. + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonObject createSimpleObject(final String[] names, + final Object[] values) { + if (names.length != values.length) { + throw new IllegalArgumentException( + "Number of paths does not match number of indexes"); + } + JsonObjectBuilder builder = Json.createObjectBuilder(); + for (int i = 0; i < names.length; i++) { + switch (JsonValueType.getType(values[i].getClass())) { + case String: + builder = builder.add(names[i], (String) values[i]); + break; + case Integer: + builder = builder.add(names[i], ((Integer) values[i]).intValue()); + break; + case Boolean: + builder = builder.add(names[i], ((Boolean) values[i]).booleanValue()); + break; + case JsonValue: + builder = builder.add(names[i], (JsonValue) values[i]); + break; + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + return builder.build(); + } + + /** + * Creates simple JSON array with specified {@code String} values. + * + * @param values + * JSON array {@code String} values. + * @return Newly created JSON array. + */ + public static JsonArray createStringArray(final String... values) { + JsonArrayBuilder builder = Json.createArrayBuilder(); + if (values != null) { + for (final String value : values) { + builder = builder.add(value); + } + } + return builder.build(); + } + + /** + * Creates simple JSON array with single {@code String}. + * + * @return Newly created JSON array. + */ + public static JsonArray createStringArray1() { + return Json.createArrayBuilder().add(STR_VALUE_1).build(); + } + + /** + * Creates simple JSON array after ADD STR_VALUE operation before existing + * element. + * + * @return Simple JSON array after ADD STR_VALUE operation before existing + * element. + */ + public static JsonArray createSimpleStringArrayWithStrBefore() { + return Json.createArrayBuilder().add(STR_VALUE).add(STR_VALUE_1).build(); + } + + /** + * Creates simple JSON array after ADD STR_VALUE operation after existing + * element. + * + * @return Simple JSON array after ADD STR_VALUE operation after existing + * element. + */ + public static JsonArray createSimpleStringArrayWithStrAfter() { + return Json.createArrayBuilder().add(STR_VALUE_1).add(STR_VALUE).build(); + } + + /** + * Creates simple JSON array after REPLACE STR_VALUE operation on existing + * element. + * + * @return Simple JSON array after REPLACE STR_VALUE operation on existing + * element. + */ + public static JsonArray createSimpleStringArrayReplaceStr() { + return Json.createArrayBuilder().add(STR_VALUE).build(); + } + + /** + * Creates simple JSON array with two {@code String} values. + * + * @return Newly created JSON array. + */ + public static JsonArray createStringArray2() { + return Json.createArrayBuilder().add(STR_VALUE_2).add(STR_VALUE_4).build(); + } + + /** + * Creates simple JSON array with two {@code String} values in reversed order. + * + * @return Newly created JSON array. + */ + public static JsonArray createStringArray2R() { + return Json.createArrayBuilder().add(STR_VALUE_4).add(STR_VALUE_2).build(); + } + + /** + * Creates simple JSON array with two {@code String} values to be inserted + * into another array. + * + * @return Newly created JSON array. + */ + public static JsonArray createStringInnerArray2() { + return Json.createArrayBuilder().add(STR_VALUE_6).add(STR_VALUE_7).build(); + } + + /** + * Creates simple JSON array with three {@code String} values as a result of + * COPY 2nd element to the beginning of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createStringArray2Copy1to0() { + return Json.createArrayBuilder().add(STR_VALUE_4).add(STR_VALUE_2) + .add(STR_VALUE_4).build(); + } + + /** + * Creates simple JSON array with three {@code String} values as a result of + * COPY 1st element to the end of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createStringArray2Copy0to2() { + return Json.createArrayBuilder().add(STR_VALUE_2).add(STR_VALUE_4) + .add(STR_VALUE_2).build(); + } + + /** + * Creates simple JSON array with three {@code String} values as a result of + * COPY 1st element to the middle of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createStringArray2Copy0to1() { + return Json.createArrayBuilder().add(STR_VALUE_2).add(STR_VALUE_2) + .add(STR_VALUE_4).build(); + } + + /** + * Creates simple JSON array with five {@code String} values. + * + * @return Newly created JSON array. + */ + public static JsonArray createSimpleStringArray5() { + return Json.createArrayBuilder().add(STR_VALUE_1).add(STR_VALUE_2) + .add(STR_VALUE_3).add(STR_VALUE_4).add(STR_VALUE_5).build(); + } + + /** + * Creates simple JSON array with five {@code String} values in reversed + * order. + * + * @return Newly created JSON array. + */ + public static JsonArray createSimpleStringArray5R() { + return Json.createArrayBuilder().add(STR_VALUE_5).add(STR_VALUE_4) + .add(STR_VALUE_3).add(STR_VALUE_2).add(STR_VALUE_1).build(); + } + + /** + * Creates simple JSON array after ADD [STR_VALUE_6, STR_VALUE_7] operation + * between two existing elements. + * + * @return Simple JSON array after ADD operation. + */ + public static JsonArray createStringArray2WithStringArrayInTheMiddle() { + return Json.createArrayBuilder().add(STR_VALUE_2) + .add(createStringInnerArray2()).add(STR_VALUE_4).build(); + } + + /** + * Creates simple JSON array with single {@code int}. + * + * @return Newly created JSON array. + */ + public static JsonArray createIntArray1() { + return Json.createArrayBuilder().add(INT_VALUE_1).build(); + } + + /** + * Creates simple JSON array after ADD INT_VALUE operation before existing + * element. + * + * @return Simple JSON array after ADD INT_VALUE operation before existing + * element. + */ + public static JsonArray createSimpleIntArrayWithIntBefore() { + return Json.createArrayBuilder().add(INT_VALUE).add(INT_VALUE_1).build(); + } + + /** + * Creates simple JSON array after ADD INT_VALUE operation after existing + * element. + * + * @return Simple JSON array after ADD INT_VALUE operation after existing + * element. + */ + public static JsonArray createSimpleIntArrayWithIntAfter() { + return Json.createArrayBuilder().add(INT_VALUE_1).add(INT_VALUE).build(); + } + + /** + * Creates simple JSON array after REPLACE INT_VALUE operation on existing + * element. + * + * @return Simple JSON array after REPLACE INT_VALUE operation on existing + * element. + */ + public static JsonArray createSimpleIntArrayReplaceInt() { + return Json.createArrayBuilder().add(INT_VALUE).build(); + } + + /** + * Creates simple JSON array with two {@code int} values. + * + * @return Newly created JSON array. + */ + public static JsonArray createIntArray2() { + return Json.createArrayBuilder().add(INT_VALUE_2).add(INT_VALUE_4).build(); + } + + /** + * Creates simple JSON array with two {@code int} values in reversed order. + * + * @return Newly created JSON array. + */ + public static JsonArray createIntArray2R() { + return Json.createArrayBuilder().add(INT_VALUE_4).add(INT_VALUE_2).build(); + } + + /** + * Creates simple JSON array with three {@code int} values as a result of COPY + * 2nd element to the beginning of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createIntArray2Copy1to0() { + return Json.createArrayBuilder().add(INT_VALUE_4).add(INT_VALUE_2) + .add(INT_VALUE_4).build(); + } + + /** + * Creates simple JSON array with three {@code int} values as a result of COPY + * 1st element to the end of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createIntArray2Copy0to2() { + return Json.createArrayBuilder().add(INT_VALUE_2).add(INT_VALUE_4) + .add(INT_VALUE_2).build(); + } + + /** + * Creates simple JSON array with three {@code int} values as a result of COPY + * 1st element to the middle of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createIntArray2Copy0to1() { + return Json.createArrayBuilder().add(INT_VALUE_2).add(INT_VALUE_2) + .add(INT_VALUE_4).build(); + } + + /** + * Creates simple JSON array with five {@code int} values. + * + * @return Newly created JSON array. + */ + public static JsonArray createSimpleIntArray5() { + return Json.createArrayBuilder().add(INT_VALUE_1).add(INT_VALUE_2) + .add(INT_VALUE_3).add(INT_VALUE_4).add(INT_VALUE_5).build(); + } + + /** + * Creates simple JSON array with five {@code int} values in reversed order. + * + * @return Newly created JSON array. + */ + public static JsonArray createSimpleIntArray5R() { + return Json.createArrayBuilder().add(INT_VALUE_5).add(INT_VALUE_4) + .add(INT_VALUE_3).add(INT_VALUE_2).add(INT_VALUE_1).build(); + } + + /** + * Creates simple JSON array with single {@code boolean}. + * + * @return Newly created JSON array. + */ + public static JsonArray createBoolArray1() { + return Json.createArrayBuilder().add(BOOL_TRUE).build(); + } + + /** + * Creates simple JSON array after ADD BOOL_FALSE operation before existing + * element (BOOL_TRUE). + * + * @return Simple JSON array after ADD BOOL_FALSE operation before existing + * element. + */ + public static JsonArray createSimpleBoolArrayWithBoolBefore() { + return Json.createArrayBuilder().add(BOOL_FALSE).add(BOOL_TRUE).build(); + } + + /** + * Creates simple JSON array after ADD BOOL_FALSE operation after existing + * element (BOOL_TRUE). + * + * @return Simple JSON array after ADD BOOL_FALSE operation after existing + * element. + */ + public static JsonArray createSimpleBoolArrayWithBoolAfter() { + return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_FALSE).build(); + } + + /** + * Creates simple JSON array after REPLACE BOOL_FALSE operation on existing + * element. + * + * @return Simple JSON array after REPLACE BOOL_FALSE operation on existing + * element. + */ + public static JsonArray createSimpleBoolArrayReplaceBool() { + return Json.createArrayBuilder().add(BOOL_FALSE).build(); + } + + /** + * Creates simple JSON array with two {@code boolean} values. + * + * @return Newly created JSON array. + */ + public static JsonArray createBoolArray2() { + return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_FALSE).build(); + } + + /** + * Creates simple JSON array with two {@code boolean} values in reverse order. + * + * @return Newly created JSON array. + */ + public static JsonArray createBoolArray2R() { + return Json.createArrayBuilder().add(BOOL_FALSE).add(BOOL_TRUE).build(); + } + + /** + * Creates simple JSON array with three {@code boolean} values as a result of + * COPY 2nd element to the beginning of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createBoolArray2Copy1to0() { + return Json.createArrayBuilder().add(BOOL_FALSE).add(BOOL_TRUE) + .add(BOOL_FALSE).build(); + } + + /** + * Creates simple JSON array with three {@code boolean} values as a result of + * COPY 1st element to the end of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createBoolArray2Copy0to2() { + return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_FALSE) + .add(BOOL_TRUE).build(); + } + + /** + * Creates simple JSON array with three {@code boolean} values as a result of + * COPY 1st element to the middle of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createBoolArray2Copy0to1() { + return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_TRUE) + .add(BOOL_FALSE).build(); + } + + /** + * Creates simple JSON array with five {@code boolean} values. + * + * @return Newly created JSON array. + */ + public static JsonArray createSimpleBoolArray5() { + return Json.createArrayBuilder().add(BOOL_FALSE).add(BOOL_TRUE) + .add(BOOL_TRUE).add(BOOL_FALSE).add(BOOL_TRUE).build(); + } + + /** + * Creates simple JSON array with five {@code boolean} values in reversed + * order. + * + * @return Newly created JSON array. + */ + public static JsonArray createSimpleBoolArray5R() { + return Json.createArrayBuilder().add(BOOL_TRUE).add(BOOL_FALSE) + .add(BOOL_TRUE).add(BOOL_TRUE).add(BOOL_FALSE).build(); + } + + /** + * Creates simple JSON array with single {@code JsonObject}. + * + * @return Newly created JSON array. + */ + public static JsonArray createObjectArray1() { + return Json.createArrayBuilder().add(OBJ_VALUE_1).build(); + } + + /** + * Creates simple JSON array after ADD OBJ_VALUE operation before existing + * element. + * + * @return Simple JSON array after ADD OBJ_VALUE operation before existing + * element. + */ + public static JsonArray createSimpleObjectArrayWithObjectBefore() { + return Json.createArrayBuilder().add(OBJ_VALUE).add(OBJ_VALUE_1).build(); + } + + /** + * Creates simple JSON array after ADD OBJ_VALUE operation after existing + * element. + * + * @return Simple JSON array after ADD OBJ_VALUE operation after existing + * element. + */ + public static JsonArray createSimpleObjectArrayWithObjectAfter() { + return Json.createArrayBuilder().add(OBJ_VALUE_1).add(OBJ_VALUE).build(); + } + + /** + * Creates simple JSON array after REPLACE OBJ_VALUE operation on existing + * element. + * + * @return Simple JSON array after REPLACE OBJ_VALUE operation on existing + * element. + */ + public static JsonArray createSimpleObjectArrayReplaceObject() { + return Json.createArrayBuilder().add(OBJ_VALUE).build(); + } + + /** + * Creates simple JSON array with two {@code JsonObject} values. + * + * @return Newly created JSON array. + */ + public static JsonArray createObjectArray2() { + return Json.createArrayBuilder().add(OBJ_VALUE_2).add(OBJ_VALUE_4).build(); + } + + /** + * Creates simple JSON array with two {@code JsonObject} values in reverse + * order. + * + * @return Newly created JSON array. + */ + public static JsonArray createObjectArray2R() { + return Json.createArrayBuilder().add(OBJ_VALUE_4).add(OBJ_VALUE_2).build(); + } + + /** + * Creates simple JSON array with three {@code JsonObject} values as a result + * of COPY 2nd element to the beginning of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createObjectArray2Copy1to0() { + return Json.createArrayBuilder().add(OBJ_VALUE_4).add(OBJ_VALUE_2) + .add(OBJ_VALUE_4).build(); + } + + /** + * Creates simple JSON array with three {@code JsonObject} values as a result + * of COPY 1st element to the end of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createObjectArray2Copy0to2() { + return Json.createArrayBuilder().add(OBJ_VALUE_2).add(OBJ_VALUE_4) + .add(OBJ_VALUE_2).build(); + } + + /** + * Creates simple JSON array with three {@code JsonObject} values as a result + * of COPY 1st element to the middle of the array. + * + * @return Newly created JSON array. + */ + public static JsonArray createObjectArray2Copy0to1() { + return Json.createArrayBuilder().add(OBJ_VALUE_2).add(OBJ_VALUE_2) + .add(OBJ_VALUE_4).build(); + } + + /** + * Creates simple JSON array with five {@code JsonObject} values. + * + * @return Newly created JSON array. + */ + public static JsonArray createSimpleObjectArray5() { + return Json.createArrayBuilder().add(OBJ_VALUE_1).add(OBJ_VALUE_2) + .add(OBJ_VALUE_3).add(OBJ_VALUE_4).add(OBJ_VALUE_5).build(); + } + + /** + * Creates simple JSON array with five {@code JsonObject} values in reversed + * order. + * + * @return Newly created JSON array. + */ + public static JsonArray createSimpleObjectArray5R() { + return Json.createArrayBuilder().add(OBJ_VALUE_5).add(OBJ_VALUE_4) + .add(OBJ_VALUE_3).add(OBJ_VALUE_2).add(OBJ_VALUE_1).build(); + } + + /** + * Convert provided {@code Object} instance to {@code JsonValue}. + * + * @param value + * {@code Object} instance to be converted. + * @return JsonValue instance containing provided {@code Object}; + */ + @SuppressWarnings("UnnecessaryUnboxing") + public static JsonValue toJsonValue(final Object value) { + if (value == null) { + return JsonValue.NULL; + } + switch (JsonValueType.getType(value.getClass())) { + case String: + return Json.createValue((String) value); + case Integer: + return Json.createValue(((Integer) value).intValue()); + case Long: + return Json.createValue(((Long) value).longValue()); + case BigInteger: + return Json.createValue((BigInteger) value); + case Double: + return Json.createValue(((Double) value).doubleValue()); + case BigDecimal: + return Json.createValue((BigDecimal) value); + case Boolean: + return ((Boolean) value).booleanValue() ? JsonValue.TRUE + : JsonValue.FALSE; + case JsonValue: + return (JsonValue) value; + case Null: + return JsonValue.NULL; + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + + /** + * Convert JSON value to {@code String} containing value stored in JSON + * format. + * + * @param value + * JSON value to be converted. + * @return Provided value stored in JSON format. + */ + public static String jsonData(final JsonValue value) { + final StringWriter strWriter = new StringWriter(); + try (final JsonWriter writer = Json.createWriter(strWriter)) { + writer.write(value); + } catch (JsonException ex) { + System.out.println( + "Could not initialize JSON data: " + ex.getLocalizedMessage()); + throw ex; + } + return strWriter.toString(); + } + + /** + * Apply patch on provided JSON {@code value} using {@code apply()} method of + * {@code JsonPatch}. + * + * @param patch + * {@code JsonPatch} with patch operations. + * @param value + * JSON {@code value} to be patched. + * @return Result of JSON {@code value} patching. + */ + public static JsonValue patchApply(final JsonPatch patch, + final JsonValue value) { + switch (value.getValueType()) { + case OBJECT: + return patch.apply((JsonObject) value); + case ARRAY: + return patch.apply((JsonArray) value); + default: + throw new IllegalArgumentException( + "Unsupported JSON value type to be pached"); + } + } + + /** + * Convert {@code boolean} value to {@code JsonValue}. + * + * @param value + * Source {@code boolean} value. + * @return {@code JsonValue.TRUE} if provided {@code value} is {@code true} or + * {@code JsonValue.FALSE} otherwise. + */ + public static JsonValue booleanValue(final boolean value) { + return value ? JsonValue.TRUE : JsonValue.FALSE; + } + + /** + * Creates an instance of RFC 6902 operation test. + */ + private SimpleValues() { + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/TestFail.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/TestFail.java new file mode 100644 index 00000000..630c286b --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/TestFail.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +/** + * Test failure notification. + */ +public class TestFail { + + /** Test failure name and message separator. */ + private static final String NM_SEP = ": "; + + /** Name of test that failed. */ + private final String name; + + /** Error message. */ + private final String message; + + /** + * Creates an instance of test failure notification. + * + * @param name + * Test name. + * @param message + * Error message. + */ + public TestFail(final String name, final String message) { + this.name = name; + this.message = message; + } + + /** + * Returns human readable content of test failure notification. + * + * @return Human readable content of test failure notification. + */ + @Override + public String toString() { + final StringBuilder sb = new StringBuilder( + name.length() + message.length() + NM_SEP.length()); + sb.append(name); + sb.append(NM_SEP); + sb.append(message); + return sb.toString(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/TestResult.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/TestResult.java new file mode 100644 index 00000000..69309f2e --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/common/TestResult.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.common; + +import jakarta.jsonp.tck.api.common.TestFail; +import jakarta.jsonp.tck.lib.harness.Fault; + +import java.util.LinkedList; + +/** + * Tests result record. + */ +public class TestResult { + + /** Name of test suite. */ + private final String name; + + /** List of test failures. */ + private final LinkedList fails; + + /** + * Creates an instance of tests result record. + * + * @param name + * Name of test suite. + */ + public TestResult(final String name) { + this.name = name; + this.fails = new LinkedList<>(); + } + + /** + * Records test failure. + * + * @param name + * Test name. + * @param message + * Error message. + */ + public void fail(final String name, final String message) { + fails.addLast(new TestFail(name, message)); + } + + /** + * Evaluate test results. + * + * @throws Fault + * when any test failed. + */ + public void eval() throws Fault { + if (fails.isEmpty()) { + return; + } + final StringBuilder sb = new StringBuilder(); + sb.append(name); + sb.append(" failed:"); + for (TestFail fail : fails) { + sb.append('\n'); + sb.append(fail.toString()); + } + throw new Fault(sb.toString()); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/exceptiontests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/exceptiontests/ClientTests.java new file mode 100644 index 00000000..4ee38c97 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/exceptiontests/ClientTests.java @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.exceptiontests; + +import jakarta.json.*; +import jakarta.json.stream.*; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + + /* Tests */ + + /* + * @testName: jsonExceptionConstructorTest1 + * + * @assertion_ids: JSONP:JAVADOC:37; + * + * @test_Strategy: Test API: JsonException ret = new JsonException(String) + */ + @Test + public void jsonExceptionConstructorTest1() throws Fault { + boolean pass = true; + + try { + String message = "This JSON is incorrect."; + + System.out.println("Test JsonException(String)"); + JsonException exception = new JsonException(message); + try { + throw exception; + } catch (JsonException e) { + if (!e.getMessage().equals(message)) { + System.err.println("Incorrect message: expected " + message + ", received " + + e.getMessage()); + pass = false; + } + } + } catch (Exception e) { + throw new Fault("jsonExceptionConstructorTest1 Failed: ", e); + } + + if (!pass) + throw new Fault("jsonExceptionConstructorTest1 Failed:"); + } + + /* + * @testName: jsonExceptionConstructorTest2 + * + * @assertion_ids: JSONP:JAVADOC:38; + * + * @test_Strategy: Test API: JsonException ret = new JsonException(String, + * Throwable) + */ + @Test + public void jsonExceptionConstructorTest2() throws Fault { + boolean pass = true; + + try { + String message = "This JSON is incorrect due to foo."; + Exception foo = new Exception("This is a foo exception"); + + System.out.println("Test JsonException(String, Throwable)"); + JsonException exception = new JsonException(message, foo); + + try { + throw exception; + } catch (JsonException e) { + if (!e.getCause().equals(foo)) { + System.err.println("Incorrect cause: expected " + foo + ", received " + + e.getCause()); + pass = false; + } + if (!e.getMessage().equals(message)) { + System.err.println("Incorrect message: expected " + message + ", received " + + e.getMessage()); + pass = false; + } + } + + } catch (Exception e) { + throw new Fault("jsonExceptionConstructorTest2 Failed: ", e); + } + + if (!pass) + throw new Fault("jsonExceptionConstructorTest2 Failed:"); + } + + /* + * @testName: jsonParsingExceptionConstructorTest1 + * + * @assertion_ids: JSONP:JAVADOC:285; JSONP:JAVADOC:478; JSONP:JAVADOC:474; + * JSONP:JAVADOC:475; JSONP:JAVADOC:476; + * + * @test_Strategy: Test API: JsonParsingException ret = new + * JsonParsingException(String, JsonLocation) + */ + @Test + public void jsonParsingExceptionConstructorTest1() throws Fault { + boolean pass = true; + + try { + String message = "This JSON is incorrect."; + MyJsonLocation expLoc = new MyJsonLocation(10, 20, 30); + System.out.println("MyJsonLocation"); + JSONP_Util.dumpLocation(expLoc); + + System.out.println("Test JsonParsingException(String, JsonLocation)"); + JsonParsingException exception = new JsonParsingException(message, + expLoc); + try { + throw exception; + } catch (JsonParsingException e) { + if (!e.getMessage().equals(message)) { + System.err.println("Incorrect message: expected " + message + ", received " + + e.getMessage()); + pass = false; + } + } + JsonLocation actLoc = exception.getLocation(); + System.out.println("JsonParsingException.getLocation()"); + JSONP_Util.dumpLocation(actLoc); + if (!JSONP_Util.assertEquals(expLoc, actLoc)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonParsingExceptionConstructorTest1 Failed: ", e); + } + + if (!pass) + throw new Fault("jsonParsingExceptionConstructorTest1 Failed:"); + } + + /* + * @testName: jsonParsingExceptionConstructorTest2 + * + * @assertion_ids: JSONP:JAVADOC:286; JSONP:JAVADOC:478; JSONP:JAVADOC:474; + * JSONP:JAVADOC:475; JSONP:JAVADOC:476; + * + * @test_Strategy: Test API: JsonParsingException ret = new + * JsonParsingException(String, Throwable, JsonLocation) + */ + @Test + public void jsonParsingExceptionConstructorTest2() throws Fault { + boolean pass = true; + + try { + String message = "This JSON is incorrect due to foo."; + Exception foo = new Exception("This is a foo exception"); + MyJsonLocation expLoc = new MyJsonLocation(10, 20, 30); + System.out.println("MyJsonLocation"); + JSONP_Util.dumpLocation(expLoc); + + System.out.println("Test JsonParsingException(String, Throwable)"); + JsonParsingException exception = new JsonParsingException(message, foo, + expLoc); + + try { + throw exception; + } catch (JsonParsingException e) { + if (!e.getCause().equals(foo)) { + System.err.println("Incorrect cause: expected " + foo + ", received " + + e.getCause()); + pass = false; + } + if (!e.getMessage().equals(message)) { + System.err.println("Incorrect message: expected " + message + ", received " + + e.getMessage()); + pass = false; + } + } + JsonLocation actLoc = exception.getLocation(); + System.out.println("JsonParsingException.getLocation()"); + JSONP_Util.dumpLocation(actLoc); + if (!JSONP_Util.assertEquals(expLoc, actLoc)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonParsingExceptionConstructorTest2 Failed: ", e); + } + + if (!pass) + throw new Fault("jsonParsingExceptionConstructorTest2 Failed:"); + } + + /* + * @testName: jsonGenerationExceptionConstructorTest1 + * + * @assertion_ids: JSONP:JAVADOC:278; + * + * @test_Strategy: Test API: JsonGenerationException ret = new + * JsonGenerationException(String) + */ + @Test + public void jsonGenerationExceptionConstructorTest1() throws Fault { + boolean pass = true; + + try { + String message = "This JSON is incorrect."; + + System.out.println("Test JsonGenerationException(String)"); + JsonGenerationException exception = new JsonGenerationException(message); + try { + throw exception; + } catch (JsonGenerationException e) { + if (!e.getMessage().equals(message)) { + System.err.println("Incorrect message: expected " + message + ", received " + + e.getMessage()); + pass = false; + } + } + } catch (Exception e) { + throw new Fault("jsonGenerationExceptionConstructorTest1 Failed: ", e); + } + + if (!pass) + throw new Fault("jsonGenerationExceptionConstructorTest1 Failed:"); + } + + /* + * @testName: jsonGenerationExceptionConstructorTest2 + * + * @assertion_ids: JSONP:JAVADOC:279; + * + * @test_Strategy: Test API: JsonGenerationException ret = new + * JsonGenerationException(String, Throwable) + */ + @Test + public void jsonGenerationExceptionConstructorTest2() throws Fault { + boolean pass = true; + + try { + String message = "This JSON is incorrect due to foo."; + Exception foo = new Exception("This is a foo exception"); + + System.out.println("Test JsonGenerationException(String, Throwable)"); + JsonGenerationException exception = new JsonGenerationException(message, + foo); + + try { + throw exception; + } catch (JsonGenerationException e) { + if (!e.getCause().equals(foo)) { + System.err.println("Incorrect cause: expected " + foo + ", received " + + e.getCause()); + pass = false; + } + if (!e.getMessage().equals(message)) { + System.err.println("Incorrect message: expected " + message + ", received " + + e.getMessage()); + pass = false; + } + } + + } catch (Exception e) { + throw new Fault("jsonGenerationExceptionConstructorTest2 Failed: ", e); + } + + if (!pass) + throw new Fault("jsonGenerationExceptionConstructorTest2 Failed:"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuildAdd.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuildAdd.java new file mode 100644 index 00000000..3c6f463f --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuildAdd.java @@ -0,0 +1,618 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonarraytests; + +import jakarta.jsonp.tck.api.common.ArrayBuilder; +import jakarta.jsonp.tck.api.common.JsonIO; +import jakarta.jsonp.tck.api.common.JsonValueType; +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests: + * {@link JsonArrayBuilder} API add() methods added in JSON-P 1.1.
+ */ +public class ArrayBuildAdd extends ArrayCommon { + + /** + * Creates an instance of {@link JsonArrayBuilder} API add() methods added in + * JSON-P 1.1 test. + */ + ArrayBuildAdd() { + super(); + } + + /** + * Test {@link JsonArrayBuilder} API add() methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonArrayBuilder API add() methods added in JSON-P 1.1."); + System.out.println("JsonArrayBuilder API add() methods added in JSON-P 1.1."); + testAdd(result); + testAddNullBuilder(result); + testAddOutOfBounds(result); + testAddNull(result); + testAddNullOutOfBounds(result); + testAddArrayBuilder(result); + testAddArrayBuilderNull(result); + testAddArrayBuilderOutOfBounds(result); + testAddObjectBuilder(result); + testAddObjectBuilderNull(result); + testAddObjectBuilderOutOfBounds(result); + testAddAllString(result); + testAddAllInt(result); + testAddAllBool(result); + testAddAllObject(result); + testAddAllNull(result); + return result; + } + + /** + * Test {@code default JsonArrayBuilder add(int, Object)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testAdd(final TestResult result) { + final Object[] values = new Object[] { OBJ_VALUE, // add(int,JsonValue) + STR_VALUE, // add(int,String) + INT_VALUE, // add(int,int) + LNG_VALUE, // add(int,long) + DBL_VALUE, // add(int,double) + BIN_VALUE, // add(int,BigInteger) + BDC_VALUE, // add(int,BigDecimal) + BOOL_VALUE // add(int,boolean) + }; + for (Object value : values) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println(" - add(int," + typeName + ")"); + final String json = "[" + JsonValueType.toStringValue(value) + "]"; + final JsonValue check = JsonIO.read(json); + final JsonArrayBuilder builder = createArrayBuilder(0, value); + final JsonValue out = builder.build(); + if (operationFailed(check, out)) { + result.fail("add(" + typeName + ")", "Builder output " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + } + + /** + * Test {@code JsonArrayBuilder add(int, Object)} method on {@code String} + * array with index being out of range + * ({@code index < 0 || index > array size}). + * + * @param result + * Test suite result. + */ + private void testAddOutOfBounds(final TestResult result) { + final Object[] values = new Object[] { OBJ_VALUE, // add(int,JsonValue) + STR_VALUE, // add(int,String) + INT_VALUE, // add(int,int) + LNG_VALUE, // add(int,long) + DBL_VALUE, // add(int,double) + BIN_VALUE, // add(int,BigInteger) + BDC_VALUE, // add(int,BigDecimal) + BOOL_VALUE // add(int,boolean) + }; + final int[] indexes = new int[] { -1, 2, 3 }; + for (Object value : values) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println(" - add(int," + typeName + ")"); + final String json = "[" + JsonValueType.toStringValue(value) + "]"; + // Add value into the array for the first time to het array of size 1. + JsonArrayBuilder builder = createArrayBuilder(value); + for (int index : indexes) { + try { + // Add value on out of bounds index + builder = updateOperationBuilder(builder, index, value); + result.fail("add(int," + typeName + ")", + "Calling method with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println(" - Expected exception for index=" + index + ": " + + e.getMessage()); + } catch (Throwable t) { + result.fail("add(int,(" + typeName + ")null)", + "Calling method with with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException, not " + + t.getClass().getSimpleName()); + } + } + } + } + + /** + * Test {@code JsonArrayBuilder add(int, Object)} method on {@code String} + * array with null value. + * + * @param result + * Test suite result. + */ + private void testAddNullBuilder(final TestResult result) { + final JsonValueType[] types = new JsonValueType[] { JsonValueType.JsonValue, // add(int,(JsonValue)null) + JsonValueType.String, // add(int,(String)null) + JsonValueType.BigInteger, // add(int,(BigInteger)null) + JsonValueType.BigDecimal // add(int,(BigDecimal)null) + }; + for (JsonValueType type : types) { + final String typeName = type.name(); + System.out.println(" - add(int,(" + typeName + ")null)"); + try { + ArrayBuilder.add(Json.createArrayBuilder(), 0, type); + result.fail("add(int,(" + typeName + ")null)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("add(int,(" + typeName + ")null)", + "Calling method with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonArrayBuilder addNull(int)} method on {@code String} array. + * + * @param result + * Test suite result. + */ + private void testAddNull(final TestResult result) { + System.out.println(" - addNull(int)"); + final Object value = null; + final String json = "[" + JsonValueType.toStringValue(value) + "]"; + final JsonValue check = JsonIO.read(json); + final JsonArrayBuilder builder = createArrayBuilder(0, value); + final JsonValue out = builder.build(); + if (operationFailed(check, out)) { + result.fail("addNull(int)", "Builder output " + valueToString(out) + + " value shall be " + valueToString(check)); + } + } + + /** + * Test {@code JsonArrayBuilder addNull(int)} method on {@code String} array + * with index being out of range ({@code index < 0 || index > array size}). + * + * @param result + * Test suite result. + */ + private void testAddNullOutOfBounds(final TestResult result) { + final int[] indexes = new int[] { -1, 2, 3 }; + System.out.println(" - addNull(int)"); + final Object value = null; + JsonArrayBuilder builder = createArrayBuilder(value); + for (int index : indexes) { + try { + // Add value on out of bounds index + builder = updateOperationBuilder(builder, index, value); + result.fail("addNull(int)", "Calling method with out of bounds index=" + + index + " argument shall throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println(" - Expected exception for index=" + index + ": " + + e.getMessage()); + } catch (Throwable t) { + result.fail("addNull(int)", + "Calling method with with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonArrayBuilder add(int,JsonArrayBuilder)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testAddArrayBuilder(final TestResult result) { + System.out.println(" - add(int,JsonArrayBuilder)"); + final JsonValue checkBeg = JsonIO + .read("[[" + JsonValueType.toStringValue(STR_VALUE_1) + "," + + JsonValueType.toStringValue(STR_VALUE_2) + "," + + JsonValueType.toStringValue(STR_VALUE_3) + "," + + JsonValueType.toStringValue(STR_VALUE_4) + "]," + + JsonValueType.toStringValue(STR_VALUE_5) + "]"); + final JsonValue checkEnd = JsonIO + .read("[" + JsonValueType.toStringValue(STR_VALUE_1) + ",[" + + JsonValueType.toStringValue(STR_VALUE_2) + "," + + JsonValueType.toStringValue(STR_VALUE_3) + "," + + JsonValueType.toStringValue(STR_VALUE_4) + "," + + JsonValueType.toStringValue(STR_VALUE_5) + "]]"); + final JsonArrayBuilder inBeg = createArrayBuilder(STR_VALUE_5); + final JsonArrayBuilder inEnd = createArrayBuilder(STR_VALUE_1); + final JsonArrayBuilder argBeg = createArrayBuilder(STR_VALUE_1) + .add(STR_VALUE_2).add(STR_VALUE_3).add(STR_VALUE_4); + final JsonArrayBuilder argEnd = createArrayBuilder(STR_VALUE_2) + .add(STR_VALUE_3).add(STR_VALUE_4).add(STR_VALUE_5); + verifyAddBuilder(result, checkBeg, 0, argBeg, inBeg); + verifyAddBuilder(result, checkEnd, 1, argEnd, inEnd); + } + + /** + * Test {@code JsonArrayBuilder add(int,(JsonArrayBuilder)null)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testAddArrayBuilderNull(final TestResult result) { + System.out.println(" - add(int,(JsonArrayBuilder)null)"); + final JsonArrayBuilder in = createArrayBuilder(DEF_VALUE); + final JsonArrayBuilder arg = null; + try { + in.add(0, arg); + result.fail("add(int,(JsonArrayBuilder)null)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("add(int,(JsonArrayBuilder)null)", + "Calling method with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Test {@code JsonArrayBuilder add(int,JsonArrayBuilder)} method on + * {@code String} array with index being out of range + * ({@code index < 0 || index > array size}). + * + * @param result + * Test suite result. + */ + private void testAddArrayBuilderOutOfBounds(final TestResult result) { + System.out.println(" - add(int,JsonArrayBuilder)"); + final int[] indexes = new int[] { -1, 5, 6 }; + final JsonArrayBuilder in = createArrayBuilder(STR_VALUE_1).add(STR_VALUE_2) + .add(STR_VALUE_3).add(STR_VALUE_4); + final JsonArrayBuilder arg = createArrayBuilder(STR_VALUE_5); + for (int index : indexes) { + try { + // Add value on out of bounds index + in.add(index, arg); + result.fail("add(int,JsonArrayBuilder)", + "Calling method with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println(" - Expected exception for index=" + index + ": " + + e.getMessage()); + } catch (Throwable t) { + result.fail("add(int,JsonArrayBuilder)", + "Calling method with with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonArrayBuilder add(int,JsonObjectBuilder)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testAddObjectBuilder(final TestResult result) { + System.out.println(" - add(int,JsonObjectBuilder)"); + final JsonValue checkBeg = JsonIO + .read("[{" + JsonValueType.toStringValue(STR_NAME) + ":" + + JsonValueType.toStringValue(STR_VALUE) + "}," + + JsonValueType.toStringValue(STR_VALUE_1) + "]"); + final JsonValue checkEnd = JsonIO + .read("[" + JsonValueType.toStringValue(STR_VALUE_1) + ",{" + + JsonValueType.toStringValue(STR_NAME) + ":" + + JsonValueType.toStringValue(STR_VALUE) + "}]"); + final JsonArrayBuilder inBeg = createArrayBuilder(STR_VALUE_1); + final JsonArrayBuilder inEnd = createArrayBuilder(STR_VALUE_1); + final JsonObjectBuilder argBeg = Json.createObjectBuilder().add(STR_NAME, + STR_VALUE); + final JsonObjectBuilder argEnd = Json.createObjectBuilder().add(STR_NAME, + STR_VALUE); + verifyAddBuilder(result, checkBeg, 0, argBeg, inBeg); + verifyAddBuilder(result, checkEnd, 1, argEnd, inEnd); + } + + /** + * Test {@code JsonArrayBuilder add(int,(JsonObjectBuilder)null)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testAddObjectBuilderNull(final TestResult result) { + System.out.println(" - add(int,(JsonObjectBuilder)null)"); + final JsonArrayBuilder in = createArrayBuilder(DEF_VALUE); + final JsonObjectBuilder arg = null; + try { + in.add(0, arg); + result.fail("add(int,(JsonObjectBuilder)null)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("add(int,(JsonObjectBuilder)null)", + "Calling method with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Test {@code JsonArrayBuilder add(int,JsonObjectBuilder)} method on + * {@code String} array with index being out of range + * ({@code index < 0 || index > array size}). + * + * @param result + * Test suite result. + */ + private void testAddObjectBuilderOutOfBounds(final TestResult result) { + System.out.println(" - add(int,JsonObjectBuilder)"); + final int[] indexes = new int[] { -1, 5, 6 }; + final JsonArrayBuilder in = createArrayBuilder(STR_VALUE_1).add(STR_VALUE_2) + .add(STR_VALUE_3).add(STR_VALUE_4); + final JsonObjectBuilder arg = Json.createObjectBuilder().add(STR_NAME, + STR_VALUE); + for (int index : indexes) { + try { + // Add value on out of bounds index + in.add(index, arg); + result.fail("add(int,JsonObjectBuilder)", + "Calling method with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println(" - Expected exception for index=" + index + ": " + + e.getMessage()); + } catch (Throwable t) { + result.fail("add(int,JsonObjectBuilder)", + "Calling method with with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testAddAllString(final TestResult result) { + System.out.println(" - addAll(JsonArrayBuilder) for String array"); + final JsonArray check = createSimpleStringArray5(); + final String[] strings = new String[] { STR_VALUE_1, STR_VALUE_2, + STR_VALUE_3, STR_VALUE_4, STR_VALUE_5 }; + verifyAddAll(result, check, strings); + } + + /** + * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on + * {@code int) array. @param result Test suite result. + */ + private void testAddAllInt(final TestResult result) { + System.out.println(" - addAll(JsonArrayBuilder) for int array"); + final JsonArray check = createSimpleIntArray5(); + final Integer[] ints = new Integer[] { INT_VALUE_1, INT_VALUE_2, + INT_VALUE_3, INT_VALUE_4, INT_VALUE_5 }; + verifyAddAll(result, check, ints); + } + + /** + * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on + * {@code boolean) array. @param result Test suite result. + */ + private void testAddAllBool(final TestResult result) { + System.out.println(" - addAll(JsonArrayBuilder) for boolean array"); + final JsonArray check = createSimpleBoolArray5(); + final Boolean[] bools = new Boolean[] { BOOL_FALSE, BOOL_TRUE, BOOL_TRUE, + BOOL_FALSE, BOOL_TRUE }; + verifyAddAll(result, check, bools); + } + + /** + * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on + * {@code JsonObject) array. @param result Test suite result. + */ + private void testAddAllObject(final TestResult result) { + System.out.println(" - addAll(JsonArrayBuilder) for JsonObject array"); + final JsonArray check = createSimpleObjectArray5(); + final JsonObject[] bools = new JsonObject[] { OBJ_VALUE_1, OBJ_VALUE_2, + OBJ_VALUE_3, OBJ_VALUE_4, OBJ_VALUE_5 }; + verifyAddAll(result, check, bools); + } + + /** + * Test {@code JsonArrayBuilder addAll(JsonArrayBuilder)} method on + * {@code null} builder argument. + * + * @param result + * Test suite result. + */ + private void testAddAllNull(final TestResult result) { + System.out.println(" - addAll(JsonArrayBuilder) for null builder argument"); + JsonArrayBuilder builder = Json.createArrayBuilder(); + try { + builder.addAll((JsonArrayBuilder) null); + result.fail("addAll(null)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("addAll(null)", + "Calling method with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Test helper: Verify + * {@code default JsonArrayBuilder addAll(JsonArrayBuilder)} method on + * provided array. + * + * @param result + * Test suite result. + * @param check + * Expected value (used for operation check). + * @param values + * Values used to build JSON array builder. + */ + private void verifyAddAll(final TestResult result, final JsonArray check, + final Object[] values) { + JsonArrayBuilder builderIn = Json.createArrayBuilder(); + for (Object value : values) { + builderIn = updateOperationBuilder(builderIn, value); + } + final JsonArrayBuilder builderOut = Json.createArrayBuilder(); + builderOut.addAll(builderIn); + final JsonArray out = builderOut.build(); + if (operationFailed(check, out)) { + result.fail("addAll(JsonArrayBuilder)", "Output builder " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Test helper: Verify + * {@code default JsonArrayBuilder add(int,JsonArrayBuilder)} method on + * provided builders. + * + * @param result + * Test suite result. + * @param check + * Expected value (used for operation check). + * @param src + * Source builder (the one to be added). + * @param target + * Target builder (to which to add). + */ + private void verifyAddBuilder(final TestResult result, final JsonValue check, + final int index, final JsonArrayBuilder src, + final JsonArrayBuilder target) { + final JsonArray out = target.add(index, src).build(); + if (operationFailed(check, out)) { + result.fail("add(int,JsonArrayBuilder)", "Output builder " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Test helper: Verify + * {@code default JsonArrayBuilder add(int,JsonObjectBuilder)} method on + * provided builders. + * + * @param result + * Test suite result. + * @param check + * Expected value (used for operation check). + * @param src + * Source builder (the one to be added). + * @param target + * Target builder (to which to add). + */ + private void verifyAddBuilder(final TestResult result, final JsonValue check, + final int index, final JsonObjectBuilder src, + final JsonArrayBuilder target) { + final JsonArray out = target.add(index, src).build(); + if (operationFailed(check, out)) { + result.fail("add(int,JsonObjectBuilder)", "Output builder " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Create and initialize array builder to contain single value. Child class + * callback. + * + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder containing value. + */ + @Override + protected JsonArrayBuilder createArrayBuilder(final Object value) { + return ArrayBuilder.add(Json.createArrayBuilder(), value); + } + + /** + * Create and initialize array builder to contain single value. Child class + * callback. + * + * @param index + * Position in the array where value is added. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder containing value. + */ + @Override + protected JsonArrayBuilder createArrayBuilder(final int index, + final Object value) { + return ArrayBuilder.add(Json.createArrayBuilder(), index, value); + } + + /** + * Update array builder to contain next value. Child class callback. + * + * @param builder + * JSON array builder to update. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder with value updated. + */ + @Override + protected JsonArrayBuilder updateOperationBuilder( + final JsonArrayBuilder builder, final Object value) { + return ArrayBuilder.add(builder, value); + } + + /** + * Update array builder to contain next value. Child class callback. + * + * @param builder + * JSON array builder to update. + * @param index + * Position in the array where value is added. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder with value updated. + */ + @Override + protected JsonArrayBuilder updateOperationBuilder( + final JsonArrayBuilder builder, final int index, final Object value) { + return ArrayBuilder.add(builder, index, value); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuildRemove.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuildRemove.java new file mode 100644 index 00000000..2f5b061d --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuildRemove.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonarraytests; + +import jakarta.jsonp.tck.api.common.ArrayBuilder; +import jakarta.jsonp.tck.api.common.JsonIO; +import jakarta.jsonp.tck.api.common.JsonValueType; +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests: + * {@link JsonArrayBuilder} API remove() methods added in JSON-P 1.1.
+ */ +public class ArrayBuildRemove extends ArrayCommon { + + /** + * Creates an instance of {@link JsonArrayBuilder} API remove() methods added + * in JSON-P 1.1 test. + */ + ArrayBuildRemove() { + super(); + } + + /** + * {@link JsonArrayBuilder} API remove() methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonArrayBuilder API remove() methods added in JSON-P 1.1."); + System.out.println("JsonArrayBuilder API remove() methods added in JSON-P 1.1."); + testRemove(result); + testRemoveOutOfBounds(result); + return result; + } + + /** + * Test {@code default JsonArrayBuilder remove(int, Object)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testRemove(final TestResult result) { + final Object[] values = new Object[] { OBJ_VALUE, // remove(int,JsonValue) + STR_VALUE, // remove(int,String) + INT_VALUE, // remove(int,int) + LNG_VALUE, // remove(int,long) + DBL_VALUE, // remove(int,double) + BIN_VALUE, // remove(int,BigInteger) + BDC_VALUE, // remove(int,BigDecimal) + BOOL_VALUE // remove(int,boolean) + }; + for (Object value : values) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println(" - remove(int," + typeName + ")"); + final String json = "[]"; + final JsonValue check = JsonIO.read(json); + JsonArrayBuilder builder = ArrayBuilder.add(Json.createArrayBuilder(), + value); + builder = updateOperationBuilder(builder, 0, null); + final JsonValue out = builder.build(); + if (operationFailed(check, out)) { + result.fail("remove(" + typeName + ")", "Builder output " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + } + + /** + * Test {@code default JsonArrayBuilder remove(int, Object)} method on + * {@code String} array with index being out of range + * ({@code index < 0 || index > array size}). + * + * @param result + * Test suite result. + */ + private void testRemoveOutOfBounds(final TestResult result) { + final Object[] values = new Object[] { OBJ_VALUE, // remove(int,JsonValue) + STR_VALUE, // remove(int,String) + INT_VALUE, // remove(int,int) + LNG_VALUE, // remove(int,long) + DBL_VALUE, // remove(int,double) + BIN_VALUE, // remove(int,BigInteger) + BDC_VALUE, // remove(int,BigDecimal) + BOOL_VALUE // remove(int,boolean) + }; + final int[] indexes = new int[] { -1, 2, 3 }; + for (Object value : values) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println(" - remove(int," + typeName + ")"); + final String json = "[" + JsonValueType.toStringValue(value) + "]"; + // Add value into the array for the first time to het array of size 1. + JsonArrayBuilder builder = ArrayBuilder.add(Json.createArrayBuilder(), + value); + for (int index : indexes) { + try { + // Add value on out of bounds index + builder = updateOperationBuilder(builder, index, null); + result.fail("remove(int," + typeName + ")", + "Calling method with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println(" - Expected exception for index=" + index + ": " + + e.getMessage()); + } catch (Throwable t) { + result.fail("remove(int,(" + typeName + ")null)", + "Calling method with with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException, not " + + t.getClass().getSimpleName()); + } + } + } + } + + /** + * Create and initialize array builder. Unsupported method call for remove() + * method. + * + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder containing value. + */ + @Override + protected JsonArrayBuilder createArrayBuilder(Object value) { + throw new UnsupportedOperationException( + "Method remove is not implemented."); + } + + /** + * Create and initialize array builder. Unsupported method call for remove() + * method. + * + * @param index + * Position in the array where value is added. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder containing value. + */ + @Override + protected JsonArrayBuilder createArrayBuilder(final int index, + final Object value) { + throw new UnsupportedOperationException( + "Method remove is not implemented."); + } + + /** + * Update array builder. Unsupported method call for remove() method. + * + * @param builder + * JSON array builder to update. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder with value updated. + */ + @Override + protected JsonArrayBuilder updateOperationBuilder(JsonArrayBuilder builder, + Object value) { + throw new UnsupportedOperationException( + "Method remove is not implemented."); + } + + /** + * Update array builder with value removal at specified index. Child class + * callback. + * + * @param builder + * JSON array builder to update. + * @param index + * Position in the array where value is added. + * @param value + * JSON value argument is ignored. + * @return JSON array builder with value updated. + */ + @Override + protected JsonArrayBuilder updateOperationBuilder( + final JsonArrayBuilder builder, final int index, final Object value) { + return ArrayBuilder.remove(builder, index); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuildSet.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuildSet.java new file mode 100644 index 00000000..e41ebe19 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuildSet.java @@ -0,0 +1,494 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonarraytests; + +import jakarta.jsonp.tck.api.common.ArrayBuilder; +import jakarta.jsonp.tck.api.common.JsonIO; +import jakarta.jsonp.tck.api.common.JsonValueType; +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests: + * {@link JsonArrayBuilder} API set() methods added in JSON-P 1.1.
+ */ +public class ArrayBuildSet extends ArrayCommon { + + /** + * Creates an instance of {@link JsonArrayBuilder} API set() methods added in + * JSON-P 1.1 test. + */ + ArrayBuildSet() { + super(); + } + + /** + * {@link JsonArrayBuilder} API set() methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonArrayBuilder API set() methods added in JSON-P 1.1."); + System.out.println("JsonArrayBuilder API set() methods added in JSON-P 1.1."); + testSet(result); + testSetOutOfBounds(result); + testSetNullBuilder(result); + testSetNull(result); + testSetNullOutOfBounds(result); + testSetArrayBuilder(result); + testSetArrayBuilderNull(result); + testSetArrayBuilderOutOfBounds(result); + testSetObjectBuilder(result); + testSetObjectBuilderNull(result); + testSetObjectBuilderOutOfBounds(result); + return result; + } + + /** + * Test {@code default JsonArrayBuilder set(int, Object)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testSet(final TestResult result) { + final Object[] values = new Object[] { OBJ_VALUE, // set(int,JsonValue) + STR_VALUE, // set(int,String) + INT_VALUE, // set(int,int) + LNG_VALUE, // set(int,long) + DBL_VALUE, // set(int,double) + BIN_VALUE, // set(int,BigInteger) + BDC_VALUE, // set(int,BigDecimal) + BOOL_VALUE // set(int,boolean) + }; + for (Object value : values) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println(" - set(int," + typeName + ")"); + final String json = "[" + JsonValueType.toStringValue(value) + "]"; + final JsonValue check = JsonIO.read(json); + final JsonArrayBuilder builder = updateOperationBuilder( + Json.createArrayBuilder().add(DEF_OBJ_VALUE), 0, value); + final JsonValue out = builder.build(); + if (operationFailed(check, out)) { + result.fail("set(" + typeName + ")", "Builder output " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + } + + /** + * Test {@code default JsonArrayBuilder set(int, Object)} method on + * {@code String} array with index being out of range + * ({@code index < 0 || index > array size}). + * + * @param result + * Test suite result. + */ + private void testSetOutOfBounds(final TestResult result) { + final Object[] values = new Object[] { OBJ_VALUE, // set(int,JsonValue) + STR_VALUE, // set(int,String) + INT_VALUE, // set(int,int) + LNG_VALUE, // set(int,long) + DBL_VALUE, // set(int,double) + BIN_VALUE, // set(int,BigInteger) + BDC_VALUE, // set(int,BigDecimal) + BOOL_VALUE // set(int,boolean) + }; + final int[] indexes = new int[] { -1, 2, 3 }; + for (Object value : values) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println(" - set(int," + typeName + ")"); + final String json = "[" + JsonValueType.toStringValue(value) + "]"; + JsonArrayBuilder builder = ArrayBuilder.add(Json.createArrayBuilder(), + DEF_OBJ_VALUE); + for (int index : indexes) { + try { + builder = updateOperationBuilder( + Json.createArrayBuilder().add(DEF_OBJ_VALUE), index, value); + } catch (IndexOutOfBoundsException e) { + System.out.println(" - Expected exception for index=" + index + ": " + + e.getMessage()); + } catch (Throwable t) { + result.fail("set(int," + typeName + ")", + "Calling method with with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException, not " + + t.getClass().getSimpleName()); + } + } + } + } + + /** + * Test {@code default JsonArrayBuilder set(int, Object)} method on + * {@code String} array with null value. + * + * @param result + * Test suite result. + */ + private void testSetNullBuilder(final TestResult result) { + final JsonValueType[] types = new JsonValueType[] { JsonValueType.JsonValue, // set(int,(JsonValue)null) + JsonValueType.String, // set(int,(String)null) + JsonValueType.BigInteger, // set(int,(BigInteger)null) + JsonValueType.BigDecimal // set(int,(BigDecimal)null) + }; + for (JsonValueType type : types) { + final String typeName = type.name(); + System.out.println(" - set(int,(" + typeName + ")null)"); + try { + ArrayBuilder.set(Json.createArrayBuilder(), 0, type); + result.fail("set(int,(" + typeName + ")null)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("set(int,(" + typeName + ")null)", + "Calling method with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code default JsonArrayBuilder setNull(int)} method on {@code String} + * array. + * + * @param result + * Test suite result. + */ + private void testSetNull(final TestResult result) { + System.out.println(" - setNull(int)"); + final Object value = null; + final String json = "[" + JsonValueType.toStringValue(null) + "]"; + final JsonValue check = JsonIO.read(json); + final JsonArrayBuilder builder = ArrayBuilder + .set(Json.createArrayBuilder().add(DEF_OBJ_VALUE), 0, value); + final JsonValue out = builder.build(); + if (operationFailed(check, out)) { + result.fail("setNull(int)", "Builder output " + valueToString(out) + + " value shall be " + valueToString(check)); + } + } + + /** + * Test {@code default JsonArrayBuilder setNull(int)} method on {@code String} + * array with index being out of range + * ({@code index < 0 || index > array size}). + * + * @param result + * Test suite result. + */ + private void testSetNullOutOfBounds(final TestResult result) { + final int[] indexes = new int[] { -1, 2, 3 }; + System.out.println(" - setNull(int)"); + final Object value = null; + JsonArrayBuilder builder = ArrayBuilder.add(Json.createArrayBuilder(), + value); + for (int index : indexes) { + try { + // Add value on out of bounds index + builder = updateOperationBuilder(builder, index, value); + result.fail("setNull(int)", "Calling method with out of bounds index=" + + index + " argument shall throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println(" - Expected exception for index=" + index + ": " + + e.getMessage()); + } catch (Throwable t) { + result.fail("setNull(int)", + "Calling method with with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code default JsonArrayBuilder set(int,JsonArrayBuilder)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testSetArrayBuilder(final TestResult result) { + System.out.println(" - set(int,JsonArrayBuilder)"); + final JsonValue check = JsonIO + .read("[[" + JsonValueType.toStringValue(STR_VALUE_1) + "," + + JsonValueType.toStringValue(STR_VALUE_2) + "," + + JsonValueType.toStringValue(STR_VALUE_3) + "," + + JsonValueType.toStringValue(STR_VALUE_4) + "]]"); + final JsonArrayBuilder in = Json.createArrayBuilder().add(STR_VALUE_5); + final JsonArrayBuilder arg = Json.createArrayBuilder().add(STR_VALUE_1) + .add(STR_VALUE_2).add(STR_VALUE_3).add(STR_VALUE_4); + verifySetBuilder(result, check, 0, arg, in); + } + + /** + * Test {@code default JsonArrayBuilder set(int,(JsonArrayBuilder)null)} + * method on {@code String} array. + * + * @param result + * Test suite result. + */ + private void testSetArrayBuilderNull(final TestResult result) { + System.out.println(" - set(int,(JsonArrayBuilder)null)"); + final JsonArrayBuilder in = Json.createArrayBuilder().add(DEF_VALUE); + final JsonArrayBuilder arg = null; + try { + in.set(0, arg); + result.fail("set(int,(JsonArrayBuilder)null)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("set(int,(JsonArrayBuilder)null)", + "Calling method with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Test {@code default JsonArrayBuilder set(int,JsonArrayBuilder)} method on + * {@code String} array with index being out of range + * ({@code index < 0 || index > array size}). + * + * @param result + * Test suite result. + */ + private void testSetArrayBuilderOutOfBounds(final TestResult result) { + System.out.println(" - set(int,JsonArrayBuilder)"); + final int[] indexes = new int[] { -1, 5, 6 }; + final JsonArrayBuilder in = Json.createArrayBuilder().add(STR_VALUE_1) + .add(STR_VALUE_2).add(STR_VALUE_3).add(STR_VALUE_4); + final JsonArrayBuilder arg = Json.createArrayBuilder().add(STR_VALUE_5); + for (int index : indexes) { + try { + // Add value on out of bounds index + in.set(index, arg); + result.fail("set(int,JsonArrayBuilder)", + "Calling method with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println(" - Expected exception for index=" + index + ": " + + e.getMessage()); + } catch (Throwable t) { + result.fail("set(int,JsonArrayBuilder)", + "Calling method with with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code default JsonArrayBuilder set(int,JsonObjectBuilder)} method on + * {@code String} array. + * + * @param result + * Test suite result. + */ + private void testSetObjectBuilder(final TestResult result) { + System.out.println(" - set(int,JsonObjectBuilder)"); + final JsonValue check = JsonIO + .read("[{" + JsonValueType.toStringValue(STR_NAME) + ":" + + JsonValueType.toStringValue(STR_VALUE) + "}]"); + final JsonArrayBuilder in = Json.createArrayBuilder().add(STR_VALUE_1); + final JsonObjectBuilder arg = Json.createObjectBuilder().add(STR_NAME, + STR_VALUE); + verifySetBuilder(result, check, 0, arg, in); + } + + /** + * Test {@code default JsonArrayBuilder set(int,(JsonObjectBuilder)null)} + * method on {@code String} array. + * + * @param result + * Test suite result. + */ + private void testSetObjectBuilderNull(final TestResult result) { + System.out.println(" - set(int,(JsonObjectBuilder)null)"); + final JsonArrayBuilder in = Json.createArrayBuilder().add(DEF_VALUE); + final JsonObjectBuilder arg = null; + try { + in.set(0, arg); + result.fail("set(int,(JsonObjectBuilder)null)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("set(int,(JsonObjectBuilder)null)", + "Calling method with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Test {@code default JsonArrayBuilder set(int,JsonObjectBuilder)} method on + * {@code String} array with index being out of range + * ({@code index < 0 || index > array size}). + * + * @param result + * Test suite result. + */ + private void testSetObjectBuilderOutOfBounds(final TestResult result) { + System.out.println(" - set(int,JsonObjectBuilder)"); + final int[] indexes = new int[] { -1, 5, 6 }; + final JsonArrayBuilder in = Json.createArrayBuilder().add(STR_VALUE_1) + .add(STR_VALUE_2).add(STR_VALUE_3).add(STR_VALUE_4); + final JsonObjectBuilder arg = Json.createObjectBuilder().add(STR_NAME, + STR_VALUE); + for (int index : indexes) { + try { + // Add value on out of bounds index + in.set(index, arg); + result.fail("set(int,JsonObjectBuilder)", + "Calling method with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println(" - Expected exception for index=" + index + ": " + + e.getMessage()); + } catch (Throwable t) { + result.fail("set(int,JsonObjectBuilder)", + "Calling method with with out of bounds index=" + index + + " argument shall throw IndexOutOfBoundsException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test helper: Verify + * {@code default JsonArrayBuilder set(int,JsonArrayBuilder)} method on + * provided builders. + * + * @param result + * Test suite result. + * @param check + * Expected value (used for operation check). + * @param src + * Source builder (the one to be added). + * @param target + * Target builder (to which to add). + */ + private void verifySetBuilder(final TestResult result, final JsonValue check, + final int index, final JsonArrayBuilder src, + final JsonArrayBuilder target) { + final JsonArray out = target.set(index, src).build(); + if (operationFailed(check, out)) { + result.fail("set(int,JsonArrayBuilder)", "Output builder " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Test helper: Verify + * {@code default JsonArrayBuilder set(int,JsonObjectBuilder)} method on + * provided builders. + * + * @param result + * Test suite result. + * @param check + * Expected value (used for operation check). + * @param src + * Source builder (the one to be added). + * @param target + * Target builder (to which to add). + */ + private void verifySetBuilder(final TestResult result, final JsonValue check, + final int index, final JsonObjectBuilder src, + final JsonArrayBuilder target) { + final JsonArray out = target.set(index, src).build(); + if (operationFailed(check, out)) { + result.fail("set(int,JsonObjectBuilder)", "Output builder " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Create and initialize array builder to contain single value. Unsupported + * method call for set() method. + * + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder containing value. + */ + @Override + protected JsonArrayBuilder createArrayBuilder(Object value) { + throw new UnsupportedOperationException("Method set is not implemented."); + } + + /** + * Create and initialize array builder to contain single value. Child class + * callback. + * + * @param index + * Position in the array where value is added. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder containing value. + */ + @Override + protected JsonArrayBuilder createArrayBuilder(final int index, + final Object value) { + return ArrayBuilder.set(Json.createArrayBuilder(), index, value); + } + + /** + * Update array builder to contain next value. Unsupported method call for + * set() method. + * + * @param builder + * JSON array builder to update. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder with value updated. + */ + @Override + protected JsonArrayBuilder updateOperationBuilder(JsonArrayBuilder builder, + Object value) { + throw new UnsupportedOperationException("Method set is not implemented."); + } + + /** + * Update array builder to contain next value. Child class callback. + * + * @param builder + * JSON array builder to update. + * @param index + * Position in the array where value is added. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder with value updated. + */ + @Override + protected JsonArrayBuilder updateOperationBuilder( + final JsonArrayBuilder builder, final int index, final Object value) { + return ArrayBuilder.set(builder, index, value); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuilders.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuilders.java new file mode 100644 index 00000000..9a71d271 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayBuilders.java @@ -0,0 +1,171 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonarraytests; + +import jakarta.jsonp.tck.api.common.TestResult; +import java.util.ArrayList; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonString; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; +import java.util.Iterator; +import java.util.List; +import jakarta.json.JsonNumber; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests: + * {@link JsonArrayBuilder} API factory methods added in JSON-P 1.1.
+ */ +public class ArrayBuilders { + + /** + * Creates an instance of {@link JsonArrayBuilder} API factory methods added + * in JSON-P 1.1 test. + */ + ArrayBuilders() { + super(); + } + + /** + * Test {@link JsonArrayBuilder} factory method added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonArrayBuilder API factory methods added in JSON-P 1.1."); + System.out.println("JsonArrayBuilder API factory methods added in JSON-P 1.1."); + testCreateFromCollection(result); + testCreateFromJsonArray(result); + testGetStringValuesAs(result); + testGetIntValuesAs(result); + return result; + } + + /** + * Test {@link Json#createArrayBuilder(Collection)} method. + * + * @param result + * Test suite result. + */ + private void testCreateFromCollection(final TestResult result) { + System.out.println(" - Json#createArrayBuilder(Collection)"); + final JsonArray check = createSimpleStringArray5(); + final ArrayList values = new ArrayList<>(check.size()); + for (final JsonValue value : check) { + values.add(((JsonString) value).getString()); + } + final JsonArrayBuilder builder = Json.createArrayBuilder(values); + final JsonArray out = builder.build(); + if (operationFailed(check, out)) { + result.fail("createArrayBuilder(Collection)", "Builder output " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Test {@link Json#createArrayBuilder(JsonArray)} method. + * + * @param result + * Test suite result. + */ + private void testCreateFromJsonArray(final TestResult result) { + System.out.println(" - Json#createArrayBuilder(JsonArray)"); + final JsonArray check = createSimpleStringArray5(); + final JsonArrayBuilder builder = Json.createArrayBuilder(check); + final JsonArray out = builder.build(); + if (operationFailed(check, out)) { + result.fail("createArrayBuilder(JsonArray)", "Builder output " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Test {@code default JsonArray#getValuesAs(Function)} method on + * {@code String} values. + * + * @param result + * Test suite result. + */ + private void testGetStringValuesAs(final TestResult result) { + System.out.println(" - getValuesAs(Function on String array"); + final JsonArray in = createStringArray2(); + final List out = in.getValuesAs(JsonString::getString); + boolean failed = in.size() != out.size(); + if (!failed) { + final Iterator inIt = in.iterator(); + final Iterator outIt = out.iterator(); + while (!failed && inIt.hasNext()) { + final JsonValue inVal = inIt.next(); + final String outVal = outIt.next(); + failed = !((JsonString) inVal).getString().equals(outVal); + } + } + if (failed) { + result.fail("getValuesAs(Function)", "Returned Array " + + out.toString() + " content shall match " + valueToString(in)); + } + } + + /** + * Test {@code default JsonArray#getValuesAs(Function)} method on + * {@code int} values. + * + * @param result + * Test suite result. + */ + private void testGetIntValuesAs(final TestResult result) { + System.out.println(" - getValuesAs(Function on int array"); + final JsonArray in = createIntArray2(); + final List out = in.getValuesAs(JsonNumber::intValue); + boolean failed = in.size() != out.size(); + if (!failed) { + final Iterator inIt = in.iterator(); + final Iterator outIt = out.iterator(); + while (!failed && inIt.hasNext()) { + final JsonValue inVal = inIt.next(); + final Integer outVal = outIt.next(); + failed = ((JsonNumber) inVal).intValue() != outVal; + } + } + if (failed) { + result.fail("getValuesAs(Function)", "Returned Array " + + out.toString() + " content shall match " + valueToString(in)); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayCommon.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayCommon.java new file mode 100644 index 00000000..1560b364 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ArrayCommon.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonarraytests; + +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests for {@link JsonArray} + * and {@link JsonArrayBuilder}. + */ +public abstract class ArrayCommon { + + /** + * Create and initialize array builder to contain single value. Child class + * callback. + * + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder containing value. + */ + protected abstract JsonArrayBuilder createArrayBuilder(final Object value); + + /** + * Create and initialize array builder to contain single value. Child class + * callback. + * + * @param index + * Position in the array where value is added. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder containing value. + */ + protected abstract JsonArrayBuilder createArrayBuilder(final int index, + final Object value); + + /** + * Update array builder to contain next value. Child class callback. + * + * @param builder + * JSON array builder to update. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder with value updated. + */ + protected abstract JsonArrayBuilder updateOperationBuilder( + final JsonArrayBuilder builder, final Object value); + + /** + * Update array builder to contain next value. Child class callback. + * + * @param builder + * JSON array builder to update. + * @param index + * Position in the array where value is added. + * @param value + * JSON value stored in the builder. Value of {@code null} is stored + * as JSON {@code null} keyword. + * @return JSON array builder with value updated. + */ + protected abstract JsonArrayBuilder updateOperationBuilder( + final JsonArrayBuilder builder, final int index, final Object value); + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ClientTests.java new file mode 100644 index 00000000..0fa1978e --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonarraytests/ClientTests.java @@ -0,0 +1,1428 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonarraytests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.json.*; + +//$Id$ + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonArrayTest1 + * + * @assertion_ids: JSONP:JAVADOC:6; JSONP:JAVADOC:8; JSONP:JAVADOC:10; + * JSONP:JAVADOC:12; JSONP:JAVADOC:14; JSONP:JAVADOC:16; JSONP:JAVADOC:18; + * JSONP:JAVADOC:25; JSONP:JAVADOC:21; JSONP:JAVADOC:400; JSONP:JAVADOC:401; + * JSONP:JAVADOC:402; JSONP:JAVADOC:403; JSONP:JAVADOC:404; JSONP:JAVADOC:406; + * JSONP:JAVADOC:408; JSONP:JAVADOC:409; + * + * @test_Strategy: Tests JsonArray/JsonArrayBuilder API's. Build a JsonArray + * using the JsonArrayBuilder API's then verify that the list of JsonArray + * values matches the expected list of JsonArray values. + */ + @Test + public void jsonArrayTest1() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject object = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create sample JsonArray for testing"); + JsonArray array = JSONP_Util.createSampleJsonArray(); + + System.out.println("Create the expected list of JsonArray values"); + List expList = new ArrayList<>(); + expList.add(JsonValue.FALSE); + expList.add(JsonValue.TRUE); + expList.add(JsonValue.NULL); + expList.add(JSONP_Util.createJsonNumber(Double.MIN_VALUE)); + expList.add(JSONP_Util.createJsonNumber(Double.MAX_VALUE)); + expList.add(JSONP_Util.createJsonNumber(Integer.MIN_VALUE)); + expList.add(JSONP_Util.createJsonNumber(Integer.MAX_VALUE)); + expList.add(JSONP_Util.createJsonNumber(Long.MIN_VALUE)); + expList.add(JSONP_Util.createJsonNumber(Long.MAX_VALUE)); + expList.add( + JSONP_Util.createJsonNumber(BigDecimal.valueOf(123456789.123456789))); + expList.add(JSONP_Util.createJsonNumber(new BigInteger("123456789"))); + expList.add(JSONP_Util.createJsonString("string1")); + expList.add(object); + expList.add(array); + JSONP_Util.dumpList(expList, "Expected List"); + + System.out.println("Create JsonArray using all JsonArrayBuilder API's"); + JsonArray myJsonArray = Json.createArrayBuilder() // Indices + .add(JsonValue.FALSE) // 0 + .add(JsonValue.TRUE) // 1 + .add(JsonValue.NULL) // 2 + .add(Double.MIN_VALUE) // 3 + .add(Double.MAX_VALUE) // 4 + .add(Integer.MIN_VALUE) // 5 + .add(Integer.MAX_VALUE) // 6 + .add(Long.MIN_VALUE) // 7 + .add(Long.MAX_VALUE) // 8 + .add(BigDecimal.valueOf(123456789.123456789)) // 9 + .add(new BigInteger("123456789")) // 10 + .add("string1") // 11 + .add(object) // 12 + .add(array) // 13 + .build(); + + List actualList = myJsonArray; + JSONP_Util.dumpList(actualList, "Actual List"); + System.out.println( + "Compare actual list of JsonArray values with expected list of JsonArray values"); + pass = JSONP_Util.assertEqualsList(expList, actualList); + } catch (Exception e) { + throw new Fault("jsonArrayTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonArrayTest1 Failed"); + } + + /* + * @testName: jsonArrayTest2 + * + * @assertion_ids: JSONP:JAVADOC:6; JSONP:JAVADOC:8; JSONP:JAVADOC:10; + * JSONP:JAVADOC:12; JSONP:JAVADOC:14; JSONP:JAVADOC:16; JSONP:JAVADOC:18; + * JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:108; JSONP:JAVADOC:96; + * JSONP:JAVADOC:97; JSONP:JAVADOC:21; JSONP:JAVADOC:25; JSONP:JAVADOC:184; + * JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:403; + * JSONP:JAVADOC:404; JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; + * + * + * @test_Strategy: Tests JsonArray/JsonArrayBuilder API's. Build a JsonArray + * using the JsonArrayBuilder API's. Write the JsonArray to a JsonWriter and + * read it back using a JsonReader. Verify that JsonArray written to the + * JsonWriter and then read back using the JsonReader are equal. + */ + @Test + public void jsonArrayTest2() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject object = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create sample JsonArray for testing"); + JsonArray array = JSONP_Util.createSampleJsonArray(); + + System.out.println( + "Create JsonArray 'myJsonArray1' using all JsonArrayBuilder API's"); + JsonArray myJsonArray1 = Json.createArrayBuilder() // Indices + .add(JsonValue.FALSE) // 0 + .add(JsonValue.TRUE) // 1 + .add(JsonValue.NULL) // 2 + .add(Double.MIN_VALUE) // 3 + .add(Double.MAX_VALUE) // 4 + .add(Integer.MIN_VALUE) // 5 + .add(Integer.MAX_VALUE) // 6 + .add(Long.MIN_VALUE) // 7 + .add(Long.MAX_VALUE) // 8 + .add(BigDecimal.valueOf(123456789.123456789)) // 9 + .add(new BigInteger("123456789")) // 10 + .add("string1") // 11 + .add(object) // 12 + .add(array) // 13 + .build(); + + System.out.println("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); + StringWriter sw = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sw)) { + writer.writeArray(myJsonArray1); + System.out.println("Close JsonWriter"); + } + System.out.println("Save contents of the JsonWriter as a String"); + String contents = sw.toString(); + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + contents); + System.out.println("Read the JsonArray back into 'myJsonArray2' using a JsonReader"); + JsonArray myJsonArray2; + try (JsonReader reader = Json.createReader(new StringReader(contents))) { + myJsonArray2 = reader.readArray(); + } + System.out.println("Dump contents of JsonArray read from String Contents"); + JSONP_Util.dumpJsonValue(myJsonArray2); + + System.out.println("Compare myJsonArray1 and myJsonArray2 for equality"); + pass = JSONP_Util.assertEqualsJsonArrays(myJsonArray1, myJsonArray2); + } catch (Exception e) { + throw new Fault("jsonArrayTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonArrayTest2 Failed"); + } + + /* + * @testName: jsonArrayTest3 + * + * @assertion_ids: JSONP:JAVADOC:6; JSONP:JAVADOC:8; JSONP:JAVADOC:10; + * JSONP:JAVADOC:430; JSONP:JAVADOC:12; JSONP:JAVADOC:14; JSONP:JAVADOC:16; + * JSONP:JAVADOC:18; JSONP:JAVADOC:40; JSONP:JAVADOC:41; JSONP:JAVADOC:42; + * JSONP:JAVADOC:44; JSONP:JAVADOC:45; JSONP:JAVADOC:46; JSONP:JAVADOC:48; + * JSONP:JAVADOC:49; JSONP:JAVADOC:51; JSONP:JAVADOC:21; JSONP:JAVADOC:25; + * JSONP:JAVADOC:101; JSONP:JAVADOC:102; JSONP:JAVADOC:262; JSONP:JAVADOC:263; + * JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:403; + * JSONP:JAVADOC:404; JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; + * JSONP:JAVADOC:433; JSONP:JAVADOC:434; JSONP:JAVADOC:435; JSONP:JAVADOC:490; + * JSONP:JAVADOC:493; JSONP:JAVADOC:496; JSONP:JAVADOC:499; JSONP:JAVADOC:506; + * + * @test_Strategy: Tests JsonArray/JsonArrayBuilder API's. Build a JsonArray + * using the JsonArrayBuilder API's. Verify contents of JsonArray using + * JsonArray().getJsonNumber(int), JsonArray().getJsonString(int), + * JsonArray().getJsonArray(int), JsonArray().getJsonObject(). + * + * This also covers testing the following additional API's: + * + * JsonString.getString(), JsonNumber.bigDecimalValue(), + * JsonNumber.bigIntegerValue(), JsonNumber.doubleValue(), + * JsonNumber.intValue(), JsonNumber.longValue(), JsonNumber.isIntegral(), + * JsonNumber.longValueExact(), JsonNumber.intValueExact(), + * JsonNumber.bigIntegerValueExact(), JsonArray.getInt(int), + * JsonArray.getString(int), JsonArrau.getBoolean(int), + * JsonArray.getBoolean(int, boolean), JsonArray.getInt(int, int), + * JsonArray.getString(int, String) + */ + @SuppressWarnings("SuspiciousIndentAfterControlStatement") + @Test + public void jsonArrayTest3() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject object = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create sample JsonArray for testing"); + JsonArray array = JSONP_Util.createSampleJsonArray(); + + int expInt[] = { -1, 1, 1, -1000, 1000, 1000, -2000, 2000, 2000, + Integer.MAX_VALUE, Integer.MIN_VALUE }; + + long expLong[] = { Long.MAX_VALUE, Long.MIN_VALUE }; + + double expDouble[] = { Double.MAX_VALUE, Double.MIN_VALUE }; + + System.out.println("Create myArray Jsonarray of 23 elements"); + JsonArray myArray = Json.createArrayBuilder() // Indices + .add(-1).add(+1).add(1) // 0,1,2 + .add(-1e3).add(+1e3).add(1e3) // 3,4,5 + .add(-2E3).add(+2E3).add(2E3) // 6,7,8 + .add(Integer.MAX_VALUE) // 9 + .add(Integer.MIN_VALUE) // 10 + .add(Long.MAX_VALUE) // 11 + .add(Long.MIN_VALUE) // 12 + .add(Double.MAX_VALUE) // 13 + .add(Double.MIN_VALUE) // 14 + .add(BigDecimal.valueOf(123456789.123456789)) // 15 + .add(new BigInteger("123456789")) // 16 + .add(JsonValue.TRUE) // 17 + .add(JsonValue.FALSE) // 18 + .add(JsonValue.NULL) // 19 + .add(JSONP_Data.asciiCharacters) // 20 + .add(object) // 21 + .add(array) // 22 + .build(); + + System.out.println("Array size=" + myArray.size()); + + // Following array is used to test for Ints that could be one of following + // types: + boolean expectedIntTypes[] = { JSONP_Util.INTEGRAL, + JSONP_Util.NON_INTEGRAL }; + // Verify JsonValueType=NUMBER and integer value equals expectedIntValue + for (int i = 0; i < 11; i++) { + System.out.println("Checking getValue(" + i + ") for correctness"); + System.out.println("Retrieve and verify (JsonValueType=NUMBER)"); + if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, + myArray.getJsonNumber(i).getValueType())) + pass = false; + System.out.println("Retrieve and (expect JsonNumber NumberType be one of " + + JSONP_Util.toStringJsonNumberTypes(expectedIntTypes) + ")"); + if (!JSONP_Util.assertEqualsJsonNumberTypes(expectedIntTypes, + myArray.getJsonNumber(i).isIntegral())) + pass = false; + System.out.println("Retrieve and verify integer value via JsonNumber.intValue()"); + if (!JSONP_Util.assertEquals(expInt[i], + myArray.getJsonNumber(i).intValue())) + pass = false; + System.out.println("Retrieve and verify integer value via JsonArray.getInt"); + if (!JSONP_Util.assertEquals(expInt[i], myArray.getInt(i))) + pass = false; + System.out.println( + "Retrieve and verify integer value via JsonNumber.intValueExact()"); + if (!JSONP_Util.assertEquals(expInt[i], + myArray.getJsonNumber(i).intValueExact())) + pass = false; + } + + // Verify JsonValueType=NUMBER and long value equals expectedLongValue + for (int i = 11, j = 0; i < 13; i++, j++) { + System.out.println("Checking getValue(" + i + ") for correctness"); + System.out.println("Retrieve and verify (JsonValueType=NUMBER)"); + if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, + myArray.getJsonNumber(i).getValueType())) + pass = false; + System.out.println("Retrieve and (expect JsonNumber NumberType be INTEGRAL)"); + if (!JSONP_Util.assertEqualsJsonNumberType(JSONP_Util.INTEGRAL, + myArray.getJsonNumber(i).isIntegral())) + pass = false; + System.out.println("Retrieve and verify long value via JsonNumber.longValue()"); + if (!JSONP_Util.assertEquals(expLong[j], + myArray.getJsonNumber(i).longValue())) + pass = false; + System.out.println( + "Retrieve and verify long value via JsonNumber.longValueExact()"); + if (!JSONP_Util.assertEquals(expLong[j], + myArray.getJsonNumber(i).longValueExact())) + pass = false; + } + + // Following array is used to test for Doubles that could be one of + // following types: + boolean expectedDoubleTypes[] = { JSONP_Util.INTEGRAL, + JSONP_Util.NON_INTEGRAL }; + + // Verify JsonValueType=NUMBER and double value equals expectedDoubleValue + for (int i = 13, j = 0; i < 15; i++, j++) { + System.out.println("Checking getValue(" + i + ") for correctness"); + System.out.println("Retrieve and verify (JsonValueType=NUMBER)"); + if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, + myArray.getJsonNumber(i).getValueType())) + pass = false; + System.out.println("Retrieve and (expect JsonNumber NumberType be one of " + + JSONP_Util.toStringJsonNumberTypes(expectedDoubleTypes) + ")"); + if (!JSONP_Util.assertEqualsJsonNumberTypes(expectedDoubleTypes, + myArray.getJsonNumber(i).isIntegral())) + pass = false; + System.out.println("Retrieve and verify double value via JsonNumber.doubleValue()"); + if (!JSONP_Util.assertEquals(expDouble[j], + myArray.getJsonNumber(i).doubleValue())) + pass = false; + } + + // Verify JsonValueType=NUMBER and BigDecimalValue equals + // expectedBigDecimal + System.out.println("Checking getValue(15) for correctness"); + System.out.println("Retrieve and verify (JsonValueType=NUMBER)"); + if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, + myArray.getJsonNumber(15).getValueType())) + pass = false; + System.out.println("Retrieve and (expect JsonNumber NumberType be one of " + + JSONP_Util.toStringJsonNumberTypes(expectedDoubleTypes) + ")"); + if (!JSONP_Util.assertEqualsJsonNumberTypes(expectedDoubleTypes, + myArray.getJsonNumber(15).isIntegral())) + pass = false; + System.out.println( + "Retrieve and verify BigDecimal value via JsonNumber.bigDecimalValue()"); + if (!JSONP_Util.assertEquals(BigDecimal.valueOf(123456789.123456789), + myArray.getJsonNumber(15).bigDecimalValue())) + pass = false; + + // Verify JsonValueType=NUMBER and BigIntegerValue equals + // expectedBigInteger + System.out.println("Checking getValue(16) for correctness"); + System.out.println("Retrieve and verify (JsonValueType=NUMBER)"); + if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.NUMBER, + myArray.getJsonNumber(16).getValueType())) + pass = false; + System.out.println("Retrieve and (expect JsonNumber NumberType be INTEGRAL)"); + if (!JSONP_Util.assertEqualsJsonNumberType(JSONP_Util.INTEGRAL, + myArray.getJsonNumber(16).isIntegral())) + pass = false; + System.out.println( + "Retrieve and verify BigInteger value via JsonNumber.bigIntegerValue()"); + if (!JSONP_Util.assertEquals(new BigInteger("123456789"), + myArray.getJsonNumber(16).bigIntegerValue())) + pass = false; + System.out.println( + "Retrieve and verify BigInteger value via JsonNumber.bigIntegerValueExact()"); + if (!JSONP_Util.assertEquals(new BigInteger("123456789"), + myArray.getJsonNumber(16).bigIntegerValueExact())) + pass = false; + + // Verify getBoolean(int)=true + System.out.println("Retrieve and verify true value via JsonArray.getBoolean(int)"); + if (!JSONP_Util.assertEquals(true, myArray.getBoolean(17))) + pass = false; + + // Verify getBoolean(int)=false + System.out.println("Retrieve and verify false value via JsonArray.getBoolean(int)"); + if (!JSONP_Util.assertEquals(false, myArray.getBoolean(18))) + pass = false; + + // Verify isNull(int)=true + System.out.println("Retrieve and verify null value via JsonArray.isNull(int)"); + if (!JSONP_Util.assertEquals(true, myArray.isNull(19))) + pass = false; + + // Verify isNull(int)=false + System.out.println("Retrieve and verify non-null value via JsonArray.isNull(int)"); + if (!JSONP_Util.assertEquals(false, myArray.isNull(20))) + pass = false; + + // Verify JsonValueType=STRING and getJsonString()=expectedString + System.out.println("Checking getValue(20) for correctness"); + System.out.println("Retrieve and (expect JsonValueType=STRING)"); + if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.STRING, + myArray.getJsonString(20).getValueType())) + pass = false; + System.out.println("Retrieve and verify string value via JsonString.getString()"); + if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, + myArray.getJsonString(20).getString())) + pass = false; + System.out.println("Retrieve and verify string value via JsonArray.getString()"); + if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, + myArray.getString(20))) + pass = false; + + // Verify JsonValueType=OBJECT and getJsonObject()=expectedObject + System.out.println("Checking getJsonObject(21) for correctness"); + System.out.println("Retrieve and (expect JsonValueType=OBJECT)"); + if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.OBJECT, + myArray.getJsonObject(21).getValueType())) + pass = false; + System.out.println( + "Retrieve and verify object value via JsonArray.getJsonObject(int)"); + if (!JSONP_Util.assertEqualsJsonObjects(object, + myArray.getJsonObject(21))) + pass = false; + + // Verify JsonValueType=ARRAY and getJsonArray()=expectedArray + System.out.println("Checking getJsonArray(22) for correctness"); + System.out.println("Retrieve and (expect JsonValueType=ARRAY)"); + if (!JSONP_Util.assertEqualsJsonValueType(JsonValue.ValueType.ARRAY, + myArray.getJsonArray(22).getValueType())) + pass = false; + System.out.println("Retrieve and verify array value via JsonArray.getJsonArray(int)"); + if (!JSONP_Util.assertEqualsJsonArrays(array, myArray.getJsonArray(22))) + pass = false; + + // Verify calls to JsonArray.getBoolean(int) + if (!JSONP_Util.assertEquals(true, myArray.getBoolean(17))) + pass = false; + if (!JSONP_Util.assertEquals(false, myArray.getBoolean(18))) + pass = false; + + // Verify calls to JsonArray.getBoolean(int, boolean) + System.out.println( + "Testing JsonArray.getBoolean(int, boolean) with/without default value setting."); + if (!JSONP_Util.assertEquals(true, myArray.getBoolean(17, false))) + pass = false; + if (!JSONP_Util.assertEquals(false, myArray.getBoolean(0, false))) + pass = false; + if (!JSONP_Util.assertEquals(false, myArray.getBoolean(19, false))) + pass = false; + if (!JSONP_Util.assertEquals(false, myArray.getBoolean(20, false))) + pass = false; + if (!JSONP_Util.assertEquals(false, myArray.getBoolean(21, false))) + pass = false; + if (!JSONP_Util.assertEquals(false, myArray.getBoolean(22, false))) + pass = false; + + // Verify calls to JsonArray.getInt(int, int) + System.out.println( + "Testing JsonArray.getInt(int, int) with/without default value setting."); + if (!JSONP_Util.assertEquals(-1, myArray.getInt(0, 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myArray.getInt(17, 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myArray.getInt(19, 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myArray.getInt(20, 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myArray.getInt(21, 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myArray.getInt(22, 10))) + pass = false; + + // Verify calls to JsonArray.getString(int, String) + System.out.println( + "Testing JsonArray.getString(int, String) with/without default value setting."); + if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, + myArray.getString(20, "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myArray.getString(17, "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myArray.getString(19, "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myArray.getString(2, "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myArray.getString(21, "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myArray.getString(22, "foo"))) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonArrayTest3 Failed: ", e); + } + if (!pass) + throw new Fault("jsonArrayTest3 Failed"); + } + + /* + * @testName: jsonArrayTest4 + * + * @assertion_ids: JSONP:JAVADOC:6; JSONP:JAVADOC:8; JSONP:JAVADOC:14; + * JSONP:JAVADOC:16; JSONP:JAVADOC:18; JSONP:JAVADOC:21; JSONP:JAVADOC:25; + * JSONP:JAVADOC:106; JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:402; + * JSONP:JAVADOC:403; JSONP:JAVADOC:404; JSONP:JAVADOC:406; JSONP:JAVADOC:409; + * + * @test_Strategy: Build a JsonArray and than write the JsonArray. Compare the + * Json text from the writer contents with the expected Json text output + * expected based on the JsonArray. + */ + @Test + public void jsonArrayTest4() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonArray for testing"); + JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); + System.out.println("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); + StringWriter sw = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sw)) { + writer.writeArray(myJsonArray1); + System.out.println("Close JsonWriter"); + } + System.out.println("Save contents of the JsonWriter as a String"); + String contents = sw.toString(); + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + contents); + System.out.println("Remove whitespace from contents."); + String actJsonText = JSONP_Util.removeWhitespace(contents); + System.out.println( + "Compare expected JsonArray text with actual JsonArray text for equality"); + pass = JSONP_Util.assertEqualsJsonText( + JSONP_Util.EXPECTED_SAMPLEJSONARRAY_TEXT, actJsonText); + } catch (Exception e) { + throw new Fault("jsonArrayTest4 Failed: ", e); + } + if (!pass) + throw new Fault("jsonArrayTest4 Failed"); + } + + /* + * @testName: jsonArrayGetValuesAsTest + * + * @assertion_ids: JSONP:JAVADOC:403; JSONP:JAVADOC:481; JSONP:JAVADOC:8; + * JSONP:JAVADOC:14; + * + * @test_Strategy: Build a Json array of values of the same type. Get the + * values as a list for that type. Compare results in list to what is expected + * for equality. + * + * APIs called: JsonArray array = Json.createArrayBuilder().add(...).build() + * List JsonArray.getValuesAs(Class) + */ + @SuppressWarnings("SuspiciousIndentAfterControlStatement") + @Test + public void jsonArrayGetValuesAsTest() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonArray of JsonNumber types for testing"); + JsonArray jsonArr = Json.createArrayBuilder().add(100).add(500).build(); + + System.out.println("Create the expected list of JsonArray values"); + List expList = new ArrayList<>(); + expList.add(JSONP_Util.createJsonNumber(100)); + expList.add(JSONP_Util.createJsonNumber(500)); + JSONP_Util.dumpList(expList, "Expected List"); + + System.out.println("Create the JsonNumber list of JsonArray values"); + List numList = jsonArr.getValuesAs(JsonNumber.class); + + System.out.println("Create the actual list of JsonArray values"); + List actList = new ArrayList<>(); + for (JsonNumber num : numList) + actList.add(num); + + System.out.println("Compare actual list with expected list for equality"); + pass = JSONP_Util.assertEqualsList(expList, actList); + + System.out.println("Create sample JsonArray of JsonString types for testing"); + jsonArr = Json.createArrayBuilder().add("hello").add("world").build(); + + System.out.println("Create the list of JsonString values"); + List strList = jsonArr.getValuesAs(JsonString.class); + + System.out.println("Comparing JsonString list elements to expected values."); + if (!JSONP_Util.assertEquals(jsonArr.getString(0), + strList.get(0).getString())) + pass = false; + + if (!JSONP_Util.assertEquals(jsonArr.getString(1), + strList.get(1).getString())) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonArrayGetValuesAsTest Failed: ", e); + } + if (!pass) + throw new Fault("jsonArrayGetValuesAsTest Failed"); + } + + /* + * @testName: jsonArrayExceptionTests + * + * @assertion_ids: JSONP:JAVADOC:43; JSONP:JAVADOC:47; JSONP:JAVADOC:50; + * JSONP:JAVADOC:20; JSONP:JAVADOC:377; JSONP:JAVADOC:432; JSONP:JAVADOC:379; + * JSONP:JAVADOC:378; JSONP:JAVADOC:380; JSONP:JAVADOC:431; JSONP:JAVADOC:400; + * JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:403; JSONP:JAVADOC:404; + * JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; JSONP:JAVADOC:491; + * JSONP:JAVADOC:492; JSONP:JAVADOC:494; JSONP:JAVADOC:495; JSONP:JAVADOC:497; + * JSONP:JAVADOC:498; JSONP:JAVADOC:500; JSONP:JAVADOC:501; JSONP:JAVADOC:507; + * + * @test_Strategy: Test JsonArray exception conditions. Trips the exceptions: + * java.lang.IndexOutOfBoundsException java.lang.ArithmeticException + * java.lang.NumberFormatException java.lang.ClassCastException + * java.lang.UnsupportedOperationException + */ + @Test + public void jsonArrayExceptionTests() throws Fault { + boolean pass = true; + JsonObject testObject = null; + JsonArray testArray = null; + + try { + System.out.println("Create sample JsonObject for testing"); + testObject = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create sample JsonArray for testing"); + testArray = JSONP_Util.createSampleJsonArray(); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to JsonNumber via getJsonNumber(int)"); + JsonNumber value = testArray.getJsonNumber(0); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonArray to JsonNumber via getJsonNumber(int)"); + JsonNumber value = testArray.getJsonNumber(15); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonNumber to JsonString via getJsonString(int)"); + JsonString value = testArray.getJsonString(4); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonString to JsonNumber via getJsonNumber(int)"); + JsonNumber value = testArray.getJsonNumber(6); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonValue.TRUE to JsonNumber via getJsonNumber(int)"); + JsonNumber value = testArray.getJsonNumber(1); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to JsonArray via getJsonArray(int)"); + JsonArray value = testArray.getJsonArray(0); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonArray to JsonObject via getJsonObject(int)"); + JsonObject value = testArray.getJsonObject(15); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to JsonNumber via getInt(int)"); + int value = testArray.getInt(0); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to JsonString via getString(int)"); + String value = testArray.getString(0); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonArray to JsonString via getString(int)"); + String value = testArray.getString(15); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to boolean via getBoolean(int)"); + boolean value = testArray.getBoolean(0); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonArray to boolean via getBoolean(int)"); + boolean value = testArray.getBoolean(13); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonString to boolean via getBoolean(int)"); + boolean value = testArray.getBoolean(6); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonNumber to boolean via getBoolean(int)"); + boolean value = testArray.getBoolean(4); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing -1 as index to getJsonNumber(int)"); + int myInt = testArray.getJsonNumber(-1).intValue(); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing 10000 as index to getJsonNumber(int)"); + JsonValue myJsonValue = testArray.getJsonNumber(10000); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing -1 as index to getJsonArray(int)"); + JsonValue myJsonValue = testArray.getJsonArray(-1); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing 10000 as index to getJsonArray(int)"); + JsonValue myJsonValue = testArray.getJsonArray(10000); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing -1 as index to getJsonObject(int)"); + JsonValue myJsonValue = testArray.getJsonObject(-1); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing 10000 as index to getJsonObject(int)"); + JsonValue myJsonValue = testArray.getJsonObject(10000); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing -1 as index to getJsonString(int)"); + JsonValue myJsonValue = testArray.getJsonString(-1); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing 10000 as index to getJsonString(int)"); + JsonValue myJsonValue = testArray.getJsonString(10000); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing -1 as index to getInt(int)"); + int myInt = testArray.getInt(-1); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing 10000 as index to getInt(int)"); + int myInt = testArray.getInt(10000); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing -1 as index to getString(int)"); + String myString = testArray.getString(-1); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing 10000 as index to getString(int)"); + String myString = testArray.getString(10000); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing -1 as index to getBoolean(int)"); + boolean myBoolean = testArray.getBoolean(-1); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing 10000 as index to getBoolean(int)"); + boolean myBoolean = testArray.getBoolean(10000); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing -1 as index to isNull(int)"); + boolean myBoolean = testArray.isNull(-1); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip IndexOutOfBoundsException + try { + System.out.println( + "Trip IndexOutOfBoundsException passing 10000 as index to isNull(int)"); + boolean myBoolean = testArray.isNull(10000); + pass = false; + System.err.println("Failed to throw IndexOutOfBoundsException"); + } catch (IndexOutOfBoundsException e) { + System.out.println("Got expected IndexOutOfBoundsException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NumberFormatException calling add(Double.NaN) + try { + System.out.println("Trip NumberFormatException calling add(Double.NaN)"); + JsonArray array = Json.createArrayBuilder().add(Double.NaN).build(); + pass = false; + System.err.println("Failed to throw NumberFormatException"); + } catch (NumberFormatException e) { + System.out.println("Got expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NumberFormatException calling add(Double.NEGATIVE_INFINITY) + try { + System.out.println( + "Trip NumberFormatException calling add(Double.NEGATIVE_INFINITY)"); + JsonArray array = Json.createArrayBuilder().add(Double.NEGATIVE_INFINITY) + .build(); + pass = false; + System.err.println("Failed to throw NumberFormatException"); + } catch (NumberFormatException e) { + System.out.println("Got expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NumberFormatException calling add(Double.POSITIVE_INFINITY) + try { + System.out.println( + "Trip NumberFormatException calling add(Double.POSITIVE_INFINITY)"); + JsonArray array = Json.createArrayBuilder().add(Double.POSITIVE_INFINITY) + .build(); + pass = false; + System.err.println("Failed to throw NumberFormatException"); + } catch (NumberFormatException e) { + System.out.println("Got expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test for ArithmeticException + try { + System.out.println( + "Trip ArithmeticException calling add(12345.12345) and attempting to extract as an exact integer value"); + JsonArray array = Json.createArrayBuilder().add(12345.12345).build(); + System.out.println("Call JsonArray.getJsonNumber(0).intValueExact()"); + int value = array.getJsonNumber(0).intValueExact(); + pass = false; + System.err.println("Failed to throw ArithmeticException"); + } catch (ArithmeticException e) { + System.out.println("Got expected ArithmeticException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test for ArithmeticException + try { + System.out.println( + "Trip ArithmeticException calling add(12345.12345) and attempting to extract as an exact long value"); + JsonArray array = Json.createArrayBuilder().add(12345.12345).build(); + System.out.println("Call JsonArray.getJsonNumber(0).longValueExact()"); + long value = array.getJsonNumber(0).longValueExact(); + pass = false; + System.err.println("Failed to throw ArithmeticException"); + } catch (ArithmeticException e) { + System.out.println("Got expected ArithmeticException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test for ArithmeticException + try { + System.out.println( + "Trip ArithmeticException calling add(12345.12345) and attempting to extract as an exact biginteger value"); + JsonArray array = Json.createArrayBuilder().add(12345.12345).build(); + System.out.println("Call JsonArray.getJsonNumber(0).bigIntegerValueExact()"); + BigInteger value = array.getJsonNumber(0).bigIntegerValueExact(); + pass = false; + System.err.println("Failed to throw ArithmeticException"); + } catch (ArithmeticException e) { + System.out.println("Got expected ArithmeticException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Tests for UnsupportedOperationException using Collection methods to + // modify JsonArray List + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonArray.add(E) trying to modify JsonArray list which should be immutable"); + testArray.add(JsonValue.FALSE); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonArray.add(int,E) trying to modify JsonArray list which should be immutable"); + testArray.add(0, JsonValue.FALSE); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonArray.addAll(C) trying to modify JsonArray list which should be immutable"); + testArray.addAll(testArray); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonArray.addAll(int, C) trying to modify JsonArray list which should be immutable"); + testArray.addAll(0, testArray); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonArray.clear() trying to modify JsonArray list which should be immutable"); + testArray.clear(); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonArray.remove(int) trying to modify JsonArray list which should be immutable"); + testArray.remove(0); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonArray.removeAll(C) trying to modify JsonArray list which should be immutable"); + testArray.removeAll(testArray); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException trying to modify JsonArray list which should be immutable"); + testArray.remove(JsonValue.TRUE); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonArrayExceptionTests Failed"); + } + + /* + * @testName: jsonArrayNullValueExceptionTests + * + * @assertion_ids: JSONP:JAVADOC:555; JSONP:JAVADOC:556; JSONP:JAVADOC:557; + * JSONP:JAVADOC:558; JSONP:JAVADOC:559; JSONP:JAVADOC:560; + * + * @test_Strategy: Test JSON NPE exception conditions when attempting to add a + * specified value that is null. + */ + @Test + public void jsonArrayNullValueExceptionTests() throws Fault { + boolean pass = true; + JsonArrayBuilder jab = Json.createArrayBuilder(); + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonArrayBuilder.add(JsonValue) when JsonValue is null."); + jab.add((JsonValue) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + try { + System.out.println( + "Trip NullPointerException for JsonArrayBuilder.add(BigInteger) when BigInteger is null."); + jab.add((BigInteger) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + try { + System.out.println( + "Trip NullPointerException for JsonArrayBuilder.add(JsonArrayBuilder) when JsonArrayBuilder is null."); + jab.add((JsonArrayBuilder) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + try { + System.out.println( + "Trip NullPointerException for JsonArrayBuilder.add(JsonObjectBuilder) when JsonObjectBuilder is null."); + jab.add((JsonObjectBuilder) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + try { + System.out.println( + "Trip NullPointerException for JsonArrayBuilder.add(BigDecimal) when BigDecimal is null."); + jab.add((BigDecimal) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonArrayBuilder.add(String) when String is null."); + jab.add((String) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonArrayNullValueExceptionTests Failed"); + } + + /* + * @testName: jsonCreateArrayBuilder11Test + * + * @assertion_ids: JSONP:JAVADOC:572; JSONP:JAVADOC:573; JSONP:JAVADOC:651; + * JSONP:JAVADOC:652; + * + * @test_Strategy: Tests JsonArrayBuilder API factory methods added in JSON-P + * 1.1. + */ + @Test + public void jsonCreateArrayBuilder11Test() throws Fault { + ArrayBuilders createTest = new ArrayBuilders(); + final TestResult result = createTest.test(); + result.eval(); + } + + /* + * @testName: jsonArrayBuilder11AddTest + * + * @assertion_ids: JSONP:JAVADOC:589; JSONP:JAVADOC:590; JSONP:JAVADOC:591; + * JSONP:JAVADOC:592; JSONP:JAVADOC:593; JSONP:JAVADOC:594; JSONP:JAVADOC:595; + * JSONP:JAVADOC:596; JSONP:JAVADOC:597; JSONP:JAVADOC:598; JSONP:JAVADOC:599; + * JSONP:JAVADOC:600; JSONP:JAVADOC:601; + * + * @test_Strategy: Tests JsonArrayBuilder API add() methods added in JSON-P + * 1.1. + */ + @Test + public void jsonArrayBuilder11AddTest() throws Fault { + ArrayBuildAdd addTest = new ArrayBuildAdd(); + final TestResult result = addTest.test(); + result.eval(); + } + + /* + * @testName: jsonArrayBuilder11SetTest + * + * @assertion_ids: JSONP:JAVADOC:603; JSONP:JAVADOC:604; JSONP:JAVADOC:605; + * JSONP:JAVADOC:606; JSONP:JAVADOC:607; JSONP:JAVADOC:608; JSONP:JAVADOC:609; + * JSONP:JAVADOC:610; JSONP:JAVADOC:611; JSONP:JAVADOC:612; JSONP:JAVADOC:613; + * + * @test_Strategy: Tests JsonArrayBuilder API set() methods added in JSON-P + * 1.1. + */ + @Test + public void jsonArrayBuilder11SetTest() throws Fault { + ArrayBuildSet setTest = new ArrayBuildSet(); + final TestResult result = setTest.test(); + result.eval(); + } + + /* + * @testName: jsonArrayBuilder11RemoveTest + * + * @assertion_ids: JSONP:JAVADOC:602; + * + * @test_Strategy: Tests JsonArrayBuilder API remove() methods added in JSON-P + * 1.1. + */ + @Test + public void jsonArrayBuilder11RemoveTest() throws Fault { + ArrayBuildRemove removeTest = new ArrayBuildRemove(); + final TestResult result = removeTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonbuilderfactorytests/BuilderFactory.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonbuilderfactorytests/BuilderFactory.java new file mode 100644 index 00000000..0ba5076f --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonbuilderfactorytests/BuilderFactory.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonbuilderfactorytests; + +import jakarta.jsonp.tck.api.common.TestResult; + +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonBuilderFactory; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests for + * {@link JsonBuilderFactory}. + */ +public class BuilderFactory { + + + /** + * {@link JsonBuilderFactory} API methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonBuilderFactory API methods added in JSON-P 1.1."); + System.out.println("JsonBuilderFactory API methods added in JSON-P 1.1."); + testCreateArrayBuilderString(result); + testCreateArrayBuilderInt(result); + testCreateArrayBuilderBool(result); + testCreateArrayBuilderObject(result); + testCreateArrayBuilderNull(result); + testCreateObjectBuilderString(result); + testCreateObjectBuilderInt(result); + testCreateObjectBuilderBool(result); + testCreateObjectBuilderObject(result); + testCreateObjectBuilderNull(result); + return result; + } + + /** + * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on + * {@code String} value. + * + * @param result + * Test suite result. + */ + private void testCreateArrayBuilderString(final TestResult result) { + System.out.println(" - createArrayBuilder(JsonArray) for String"); + final JsonArray in = createStringArray2(); + final JsonArray check = createStringArray2(); + verifyCreateArrayBuilder(result, check, in); + } + + /** + * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on + * {@code int} value. + * + * @param result + * Test suite result. + */ + private void testCreateArrayBuilderInt(final TestResult result) { + System.out.println(" - createArrayBuilder(JsonArray) for int"); + final JsonArray in = createIntArray2(); + final JsonArray check = createIntArray2(); + verifyCreateArrayBuilder(result, check, in); + } + + /** + * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on + * {@code boolean} value. + * + * @param result + * Test suite result. + */ + private void testCreateArrayBuilderBool(final TestResult result) { + System.out.println(" - createArrayBuilder(JsonArray) for boolean"); + final JsonArray in = createBoolArray2(); + final JsonArray check = createBoolArray2(); + verifyCreateArrayBuilder(result, check, in); + } + + /** + * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on + * {@code JsonObject} value. + * + * @param result + * Test suite result. + */ + private void testCreateArrayBuilderObject(final TestResult result) { + System.out.println(" - createArrayBuilder(JsonArray) for JsonObject"); + final JsonArray in = createObjectArray2(); + final JsonArray check = createObjectArray2(); + verifyCreateArrayBuilder(result, check, in); + } + + /** + * Test {@code JsonArrayBuilder createArrayBuilder(JsonArray)} method on + * {@code null} value. Method shall throw NullPointerException. + * + * @param result + * Test suite result. + */ + private void testCreateArrayBuilderNull(final TestResult result) { + System.out.println(" - createArrayBuilder(JsonArray) for null"); + final JsonArray in = null; + final JsonBuilderFactory factory = Json.createBuilderFactory(null); + try { + factory.createArrayBuilder(in); + result.fail("createArrayBuilder(JsonArray)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println( + " - Expected exception for null argument: " + e.getMessage()); + } catch (Throwable t) { + result.fail("createObjectBuilder(JsonObject)", + "Calling method with with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on + * {@code String} value. + * + * @param result + * Test suite result. + */ + private void testCreateObjectBuilderString(final TestResult result) { + System.out.println(" - createObjectBuilder(JsonObject) for String"); + final JsonObject in = createSimpleObjectStr(); + final JsonObject check = createSimpleObjectStr(); + verifyCreateObjectBuilder(result, check, in); + } + + /** + * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on + * {@code int} value. + * + * @param result + * Test suite result. + */ + private void testCreateObjectBuilderInt(final TestResult result) { + System.out.println(" - createObjectBuilder(JsonObject) for int"); + final JsonObject in = createSimpleObjectInt(); + final JsonObject check = createSimpleObjectInt(); + verifyCreateObjectBuilder(result, check, in); + } + + /** + * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on + * {@code boolean} value. + * + * @param result + * Test suite result. + */ + private void testCreateObjectBuilderBool(final TestResult result) { + System.out.println(" - createObjectBuilder(JsonObject) for boolean"); + final JsonObject in = createSimpleObjectBool(); + final JsonObject check = createSimpleObjectBool(); + verifyCreateObjectBuilder(result, check, in); + } + + /** + * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on + * {@code JsonObject} value. + * + * @param result + * Test suite result. + */ + private void testCreateObjectBuilderObject(final TestResult result) { + System.out.println(" - createObjectBuilder(JsonObject) for JsonObject"); + final JsonObject in = createSimpleObjectObject(); + final JsonObject check = createSimpleObjectObject(); + verifyCreateObjectBuilder(result, check, in); + } + + /** + * Test helper: Verify {@code JsonArrayBuilder createArrayBuilder(JsonArray)} + * method on provided array. + * + * @param result + * Test suite result. + * @param check + * Expected value (used for operation check). + * @param in + * JSON array to pass to the method. + */ + private void verifyCreateArrayBuilder(final TestResult result, + final JsonArray check, final JsonArray in) { + final JsonBuilderFactory factory = Json.createBuilderFactory(null); + final JsonArrayBuilder builder = factory.createArrayBuilder(in); + final JsonArray out = builder.build(); + if (operationFailed(check, out)) { + result.fail("createArrayBuilder(JsonArray)", "Output builder " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Test helper: Verify + * {@code JsonObjectBuilder createObjectBuilder(JsonObjecty)} method on + * provided object. + * + * @param result + * Test suite result. + * @param check + * Expected value (used for operation check). + * @param in + * JSON object to pass to the method. + */ + private void verifyCreateObjectBuilder(final TestResult result, + final JsonObject check, final JsonObject in) { + System.out.println(" - IN: " + valueToString(in)); + final JsonBuilderFactory factory = Json.createBuilderFactory(null); + final JsonObjectBuilder builder = factory.createObjectBuilder(in); + final JsonObject out = builder.build(); + if (operationFailed(check, out)) { + result.fail("createObjectBuilder(JsonObject)", "Output builder " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Test {@code JsonObjectBuilder createObjectBuilder(JsonObject)} method on + * {@code null} value. Method shall throw NullPointerException. + * + * @param result + * Test suite result. + */ + private void testCreateObjectBuilderNull(final TestResult result) { + System.out.println(" - createObjectBuilder(JsonObject) for null"); + final JsonObject in = null; + final JsonBuilderFactory factory = Json.createBuilderFactory(null); + try { + factory.createObjectBuilder(in); + result.fail("createObjectBuilder(JsonObject)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println( + " - Expected exception for null argument: " + e.getMessage()); + } catch (Throwable t) { + result.fail("createObjectBuilder(JsonObject)", + "Calling method with with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonbuilderfactorytests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonbuilderfactorytests/ClientTests.java new file mode 100644 index 00000000..94ad80c2 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonbuilderfactorytests/ClientTests.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonbuilderfactorytests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +import java.util.Map; +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.json.*; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonBuilderFactoryTest1 + * + * @assertion_ids: JSONP:JAVADOC:445; JSONP:JAVADOC:453; JSONP:JAVADOC:454; + * JSONP:JAVADOC:455; + * + * @test_Strategy: Tests the JsonBuilderFactory API. + * + * JsonBuilderFactory builderFactory = Json.createBuilderFactory(Map); JsonArray array = builderFactory.createArrayBuilder() JsonObject + * object = builderFactory.createObjectBuilder() + */ + @Test + public void jsonBuilderFactoryTest1() throws Fault { + boolean pass = true; + try { + System.out.println("Create JsonBuilderFactory with Map with EMPTY config"); + JsonBuilderFactory builderFactory = Json + .createBuilderFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = builderFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("---------------------------------------------------"); + System.out.println("TEST CASE [JsonBuilderFactory.createArrayBuilder()]"); + System.out.println("---------------------------------------------------"); + System.out.println("Create JsonArrayBuilder using JsonBuilderFactory"); + JsonArray expJsonArray = JSONP_Util.createJsonArrayFromString("[0,2]"); + JsonArray actJsonArray = builderFactory.createArrayBuilder().add(0).add(2) + .build(); + if (!JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray)) + pass = false; + + System.out.println("----------------------------------------------------"); + System.out.println("TEST CASE [JsonBuilderFactory.createObjectBuilder()]"); + System.out.println("----------------------------------------------------"); + System.out.println("Create JsonObjectBuilder using JsonBuilderFactory"); + JsonObject expJsonObject = JSONP_Util + .createJsonObjectFromString("{\"foo\":\"bar\"}"); + JsonObject actJsonObject = builderFactory.createObjectBuilder() + .add("foo", "bar").build(); + if (!JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject)) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonBuilderFactoryTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonBuilderFactoryTest1 Failed"); + } + + /* + * @testName: jsonBuilderFactoryTest2 + * + * @assertion_ids: JSONP:JAVADOC:445; JSONP:JAVADOC:455; + * + * @test_Strategy: Tests the JsonBuilderFactory API. + * + * JsonBuilderFactory builderFactory = Json.createBuilderFactory(Map); Map config = JsonBuilderFactory.getConfigInUse(); + * + * Test for the following 3 scenarios: 1) no supported provider property + * (empty config) 2) non supported provider property + */ + @Test + public void jsonBuilderFactoryTest2() throws Fault { + boolean pass = true; + JsonBuilderFactory builderFactory; + Map config; + try { + System.out.println("----------------------------------------------"); + System.out.println("Test scenario1: no supported provider property"); + System.out.println("----------------------------------------------"); + System.out.println("Create JsonBuilderFactory with Map with EMPTY config"); + builderFactory = Json.createBuilderFactory(JSONP_Util.getEmptyConfig()); + config = builderFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("-----------------------------------------------"); + System.out.println("Test scenario2: non supported provider property"); + System.out.println("-----------------------------------------------"); + System.out.println("Create JsonBuilderFactory with Map with FOO config"); + builderFactory = Json.createBuilderFactory(JSONP_Util.getFooConfig()); + config = builderFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonBuilderFactoryTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonBuilderFactoryTest2 Failed"); + } + + /* + * @testName: jsonBuilderFactory11Test + * + * @assertion_ids: JSONP:JAVADOC:614; JSONP:JAVADOC:615; + * + * @test_Strategy: Tests JsonBuilderFactory API methods added in JSON-P 1.1. + */ + @Test + public void jsonBuilderFactory11Test() throws Fault { + BuilderFactory factoryTest = new BuilderFactory(); + final TestResult result = factoryTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsoncoding/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsoncoding/ClientTests.java new file mode 100644 index 00000000..cecc832a --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsoncoding/ClientTests.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsoncoding; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.json.Json; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonEncodeTest + * + * @assertion_ids: JSONP:JAVADOC:681; JSONP:JAVADOC:682; + * + * @test_Strategy: Encode and decode Json Pointer as defined by RFC 6901 + */ + @Test + public void jsonEncodeTest() throws Fault { + String DECODED = "/a/~b/c"; + String ENCODED = "~1a~1~0b~1c"; + StringBuilder error = new StringBuilder(); + System.out.println("----------------------------------------------"); + System.out.println("Test encode " + DECODED); + System.out.println("----------------------------------------------"); + String encoded = Json.encodePointer(DECODED); + if (!ENCODED.equals(encoded)) + error.append("The pointer ").append(DECODED) + .append(" has been encoded as ").append(encoded).append('\n'); + + System.out.println("----------------------------------------------"); + System.out.println("Test decode " + ENCODED); + String decoded = Json.decodePointer(ENCODED); + if (!DECODED.equals(decoded)) + error.append("The pointer ").append(ENCODED) + .append(" has been decoded as ").append(decoded).append('\n'); + if (error.length() != 0) + throw new Fault(error.toString()); + System.out.println("----------------------------------------------"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsongeneratorfactorytests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsongeneratorfactorytests/ClientTests.java new file mode 100644 index 00000000..af39a34c --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsongeneratorfactorytests/ClientTests.java @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsongeneratorfactorytests; + +import jakarta.json.*; +import jakarta.json.stream.*; + +import java.io.*; +import java.nio.charset.Charset; + +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.List; +import java.util.Iterator; +import java.util.Map; +import java.util.ArrayList; + +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonGeneratorFactoryTest1 + * + * @assertion_ids: JSONP:JAVADOC:162; JSONP:JAVADOC:416; JSONP:JAVADOC:427; + * + * @test_Strategy: Tests the JsonGeneratorFactory API. + * + * JsonGeneratorFactory generatorFactory = + * Json.createGeneratorFactory(Map); JsonGenerator generator1 = + * generatorFactory.createGenerator(Writer) JsonGenerator generator2 = + * generatorFactory.createGenerator(Writer) + */ + @Test + public void jsonGeneratorFactoryTest1() throws Fault { + boolean pass = true; + JsonGenerator generator1 = null; + JsonGenerator generator2 = null; + String expString; + String actString; + try { + System.out.println( + "Create JsonGeneratorFactory with Map with PRETTY_PRINTING config"); + JsonGeneratorFactory generatorFactory = Json + .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()); + System.out.println("Checking factory configuration properties"); + Map config = generatorFactory.getConfigInUse(); + String[] props = { JsonGenerator.PRETTY_PRINTING, }; + if (!JSONP_Util.doConfigCheck(config, 1, props)) + pass = false; + System.out.println("--------------------------------------------------------"); + System.out.println("TEST CASE [JsonGeneratorFactory.createGenerator(Writer)]"); + System.out.println("--------------------------------------------------------"); + System.out.println("Create 1st JsonGenerator using JsonGeneratorFactory"); + StringWriter sWriter1 = new StringWriter(); + generator1 = generatorFactory.createGenerator(sWriter1); + if (generator1 == null) { + System.err.println("GeneratorFactory failed to create generator1"); + pass = false; + } else { + generator1.writeStartObject().writeEnd(); + generator1.close(); + } + System.out.println("sWriter1=" + sWriter1.toString()); + expString = "{}"; + actString = JSONP_Util.removeWhitespace(sWriter1.toString()); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + System.out.println("Create 2nd JsonGenerator using JsonGeneratorFactory"); + StringWriter sWriter2 = new StringWriter(); + generator2 = generatorFactory.createGenerator(sWriter2); + if (generator2 == null) { + System.err.println("GeneratorFactory failed to create generator2"); + pass = false; + } else { + generator2.writeStartArray().writeEnd(); + generator2.close(); + } + System.out.println("sWriter2=" + sWriter2.toString()); + expString = "[]"; + actString = JSONP_Util.removeWhitespace(sWriter2.toString()); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonGeneratorFactoryTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorFactoryTest1 Failed"); + } + + /* + * @testName: jsonGeneratorFactoryTest2 + * + * @assertion_ids: JSONP:JAVADOC:163; JSONP:JAVADOC:416; JSONP:JAVADOC:427; + * + * @test_Strategy: Tests the JsonGeneratorFactory API. + * + * JsonGeneratorFactory generatorFactory = + * Json.createGeneratorFactory(Map); JsonGenerator generator1 = + * generatorFactory.createGenerator(OutputStream, Charset) JsonGenerator + * generator2 = generatorFactory.createGenerator(OutputStream, Charset) + * + * Create generator with both UTF-8 and UTF-16BE. + */ + @Test + public void jsonGeneratorFactoryTest2() throws Fault { + boolean pass = true; + JsonGenerator generator1 = null; + JsonGenerator generator2 = null; + String expString, actString; + try { + System.out.println( + "Create JsonGeneratorFactory with Map with PRETTY_PRINTING config"); + JsonGeneratorFactory generatorFactory = Json + .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()); + System.out.println("Checking factory configuration properties"); + Map config = generatorFactory.getConfigInUse(); + String[] props = { JsonGenerator.PRETTY_PRINTING, }; + if (!JSONP_Util.doConfigCheck(config, 1, props)) + pass = false; + + System.out.println( + "-----------------------------------------------------------------------"); + System.out.println( + "TEST CASE [JsonGeneratorFactory.createGenerator(OutputStream, Charset)]"); + System.out.println( + "-----------------------------------------------------------------------"); + System.out.println( + "Create 1st JsonGenerator using JsonGeneratorFactory with UTF-8 encoding"); + ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + generator1 = generatorFactory.createGenerator(baos1, JSONP_Util.UTF_8); + if (generator1 == null) { + System.err.println("GeneratorFactory failed to create generator1"); + pass = false; + } else { + generator1.writeStartObject().writeEnd(); + generator1.close(); + } + System.out.println("baos1=" + baos1.toString("UTF-8")); + expString = "{}"; + actString = JSONP_Util.removeWhitespace(baos1.toString("UTF-8")); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + System.out.println( + "Create 2nd JsonGenerator using JsonGeneratorFactory with UTF-16BE encoding"); + ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); + generator2 = generatorFactory.createGenerator(baos2, JSONP_Util.UTF_16BE); + if (generator2 == null) { + System.err.println("GeneratorFactory failed to create generator2"); + pass = false; + } else { + generator2.writeStartArray().writeEnd(); + generator2.close(); + } + System.out.println("baos2=" + baos2.toString("UTF-16BE")); + expString = "[]"; + actString = JSONP_Util.removeWhitespace(baos2.toString("UTF-16BE")); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonGeneratorFactoryTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorFactoryTest2 Failed"); + } + + /* + * @testName: jsonGeneratorFactoryTest3 + * + * @assertion_ids: JSONP:JAVADOC:200; JSONP:JAVADOC:416; JSONP:JAVADOC:427; + * + * @test_Strategy: Tests the JsonGeneratorFactory API. + * + * JsonGeneratorFactory generatorFactory = + * Json.createGeneratorFactory(Map); JsonGenerator generator1 = + * generatorFactory.createGenerator(OutputStream) JsonGenerator generator2 = + * generatorFactory.createGenerator(OutputStream) + */ + @Test + public void jsonGeneratorFactoryTest3() throws Fault { + boolean pass = true; + JsonGenerator generator1 = null; + JsonGenerator generator2 = null; + String expString; + String actString; + try { + System.out.println( + "Create JsonGeneratorFactory with Map with PRETTY_PRINTING config"); + JsonGeneratorFactory generatorFactory = Json + .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()); + System.out.println("Checking factory configuration properties"); + Map config = generatorFactory.getConfigInUse(); + String[] props = { JsonGenerator.PRETTY_PRINTING, }; + if (!JSONP_Util.doConfigCheck(config, 1, props)) + pass = false; + System.out.println( + "-----------------------------------------------------------------"); + System.out.println( + "TEST CASE [JsonGeneratorFactory.createGenerator(OutputStream os)]"); + System.out.println( + "-----------------------------------------------------------------"); + System.out.println("Create 1st JsonGenerator using JsonGeneratorFactory"); + ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + generator1 = generatorFactory.createGenerator(baos1); + if (generator1 == null) { + System.err.println("GeneratorFactory failed to create generator1"); + pass = false; + } else { + generator1.writeStartObject().writeEnd(); + generator1.close(); + } + System.out.println("baos1=" + baos1.toString("UTF-8")); + expString = "{}"; + actString = JSONP_Util.removeWhitespace(baos1.toString("UTF-8")); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + System.out.println("Create 2nd JsonGenerator using JsonGeneratorFactory"); + ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); + generator2 = generatorFactory.createGenerator(baos2); + if (generator2 == null) { + System.err.println("GeneratorFactory failed to create generator2"); + pass = false; + } else { + generator2.writeStartArray().writeEnd(); + generator2.close(); + } + System.out.println("baos2=" + baos2.toString("UTF-8")); + expString = "[]"; + actString = JSONP_Util.removeWhitespace(baos2.toString("UTF-8")); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonGeneratorFactoryTest3 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorFactoryTest3 Failed"); + } + + /* + * @testName: jsonGeneratorFactoryTest4 + * + * @assertion_ids: JSONP:JAVADOC:416; JSONP:JAVADOC:427; + * + * @test_Strategy: Tests the JsonGeneratorFactory API. + * + * JsonGeneratorFactory generatorFactory = + * Json.createGeneratorFactory(Map); Map config = + * JsonGeneratorFactory.getConfigInUse(); + * + * Test for the following 3 scenarios: 1) no supported provider property + * (empty config) 2) supported provider property 3) supported and non + * supported provider property + */ + @Test + public void jsonGeneratorFactoryTest4() throws Fault { + boolean pass = true; + JsonGeneratorFactory generatorFactory; + Map config; + try { + System.out.println("----------------------------------------------"); + System.out.println("Test scenario1: no supported provider property"); + System.out.println("----------------------------------------------"); + System.out.println( + "Create JsonGeneratorFactory with Map with EMPTY config"); + generatorFactory = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()); + config = generatorFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("-------------------------------------------"); + System.out.println("Test scenario2: supported provider property"); + System.out.println("-------------------------------------------"); + System.out.println( + "Create JsonGeneratorFactory with Map with PRETTY_PRINTING config"); + generatorFactory = Json + .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()); + config = generatorFactory.getConfigInUse(); + String[] props = { JsonGenerator.PRETTY_PRINTING, }; + if (!JSONP_Util.doConfigCheck(config, 1, props)) + pass = false; + + System.out.println("-------------------------------------------------------------"); + System.out.println("Test scenario3: supported and non supported provider property"); + System.out.println("-------------------------------------------------------------"); + System.out.println("Create JsonGeneratorFactory with Map with all config"); + generatorFactory = Json.createGeneratorFactory(JSONP_Util.getAllConfig()); + config = generatorFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 1, props)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonGeneratorFactoryTest4 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorFactoryTest4 Failed"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsongeneratortests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsongeneratortests/ClientTests.java new file mode 100644 index 00000000..616decea --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsongeneratortests/ClientTests.java @@ -0,0 +1,2142 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsongeneratortests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.json.*; +import jakarta.json.stream.*; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* private Utility methods */ + + /********************************************************************************* + * generateSimpleJsonObject + *********************************************************************************/ + private void generateSimpleJsonObject(JsonGenerator generator) { + try { + generator.writeStartObject().writeStartObject("object") + .write("string", "string").write("number", 1) + .write("true", JsonValue.TRUE).write("false", JsonValue.FALSE) + .write("null", JsonValue.NULL).writeEnd().writeStartArray("array") + .write("string").write(1).write(JsonValue.TRUE).write(JsonValue.FALSE) + .write(JsonValue.NULL).writeEnd().writeEnd(); + generator.close(); + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + } + } + + /********************************************************************************* + * generateSimpleJsonArray + *********************************************************************************/ + private void generateSimpleJsonArray(JsonGenerator generator) { + try { + generator.writeStartArray().writeStartObject().write("string", "string") + .write("number", 1).write("true", JsonValue.TRUE) + .write("false", JsonValue.FALSE).write("null", JsonValue.NULL) + .writeEnd().writeStartArray().write("string").write(1) + .write(JsonValue.TRUE).write(JsonValue.FALSE).write(JsonValue.NULL) + .writeEnd().writeEnd(); + generator.close(); + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + } + } + + /********************************************************************************* + * generateJsonObject + *********************************************************************************/ + private String generateJsonObject() { + try { + System.out.println("Generate a JsonObject"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write("emptyString", "") + .writeStartArray("emptyArray").writeEnd() + .writeStartObject("emptyObject").writeEnd().write("string", "string") + .write("intMin", Integer.MIN_VALUE).write("intMax", Integer.MAX_VALUE) + .write("longMin", Long.MIN_VALUE).write("longMax", Long.MAX_VALUE) + .write("doubleMin", Double.MIN_VALUE) + .write("doubleMax", Double.MAX_VALUE) + .write("bigInteger", + new BigInteger(Integer.toString(Integer.MAX_VALUE))) + .write("bigDecimal", BigDecimal.valueOf(Integer.MIN_VALUE)) + .write("true", JsonValue.TRUE).write("false", JsonValue.FALSE) + .write("null", JsonValue.NULL).writeStartObject("object") + .write("emptyString", "").writeStartArray("emptyArray").writeEnd() + .writeStartObject("emptyObject").writeEnd().write("string", "string") + .write("number", 100).write("true", true).write("false", false) + .writeNull("null").writeStartObject("object").write("name", "value") + .write("objectFooBar", JSONP_Util.buildJsonObjectFooBar()) + .write("arrayFooBar", JSONP_Util.buildJsonArrayFooBar()).writeEnd() + .writeStartArray("array").write("one").write("two") + .write(JSONP_Util.buildJsonObjectFooBar()) + .write(JSONP_Util.buildJsonArrayFooBar()).writeEnd().writeEnd() + .writeStartArray("array").write("string").write(Integer.MAX_VALUE) + .write(Long.MAX_VALUE).write(Double.MAX_VALUE) + .write(new BigInteger(Integer.toString(Integer.MAX_VALUE))) + .write(JsonValue.TRUE).write(JsonValue.FALSE).write(JsonValue.NULL) + .writeStartObject().write("name", "value").writeEnd() + .writeStartArray().write("one").write("two").writeEnd().writeEnd() + .write("asciiChars", + "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") + .writeEnd(); + generator.close(); + return sWriter.toString(); + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + return null; + } + } + + /********************************************************************************* + * buildJsonObject + *********************************************************************************/ + private JsonObject buildJsonObject() { + try { + System.out.println("Build a JsonObject"); + JsonObject jsonObject = Json.createObjectBuilder().add("emptyString", "") + .add("emptyArray", Json.createArrayBuilder()) + .add("emptyObject", Json.createObjectBuilder()) + .add("string", "string").add("intMin", Integer.MIN_VALUE) + .add("intMax", Integer.MAX_VALUE).add("longMin", Long.MIN_VALUE) + .add("longMax", Long.MAX_VALUE).add("doubleMin", Double.MIN_VALUE) + .add("doubleMax", Double.MAX_VALUE) + .add("bigInteger", + new BigInteger(Integer.toString(Integer.MAX_VALUE))) + .add("bigDecimal", BigDecimal.valueOf(Integer.MIN_VALUE)) + .add("true", JsonValue.TRUE).add("false", JsonValue.FALSE) + .add("null", JsonValue.NULL) + .add("object", + Json.createObjectBuilder().add("emptyString", "") + .add("emptyArray", Json.createArrayBuilder()) + .add("emptyObject", Json.createObjectBuilder()) + .add("string", "string").add("number", 100) + .add("true", JsonValue.TRUE).add("false", JsonValue.FALSE) + .add("null", JsonValue.NULL) + .add("object", Json.createObjectBuilder().add("name", "value") + .add("objectFooBar", JSONP_Util.buildJsonObjectFooBar()) + .add("arrayFooBar", JSONP_Util.buildJsonArrayFooBar())) + .add("array", + Json.createArrayBuilder().add("one").add("two") + .add(JSONP_Util.buildJsonObjectFooBar()) + .add(JSONP_Util.buildJsonArrayFooBar()))) + .add("array", + Json.createArrayBuilder().add("string").add(Integer.MAX_VALUE) + .add(Long.MAX_VALUE).add(Double.MAX_VALUE) + .add(new BigInteger(Integer.toString(Integer.MAX_VALUE))) + .add(JsonValue.TRUE).add(JsonValue.FALSE).add(JsonValue.NULL) + .add(Json.createObjectBuilder().add("name", "value")) + .add(Json.createArrayBuilder().add("one").add("two"))) + .add("asciiChars", + "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") + .build(); + return jsonObject; + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + return null; + } + } + + /********************************************************************************* + * generateJsonArray + *********************************************************************************/ + private String generateJsonArray() { + try { + System.out.println("Generate a JsonArray"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("").writeStartArray().writeEnd() + .writeStartObject().writeEnd().write("string") + .write(Integer.MIN_VALUE).write(Integer.MAX_VALUE) + .write(Long.MIN_VALUE).write(Long.MAX_VALUE).write(Double.MIN_VALUE) + .write(Double.MAX_VALUE) + .write(new BigInteger(new Integer(Integer.MAX_VALUE).toString())) + .write(BigDecimal.valueOf(Integer.MIN_VALUE)).write(JsonValue.TRUE) + .write(JsonValue.FALSE).write(JsonValue.NULL).writeStartObject() + .write("emptyString", "").writeStartArray("emptyArray").writeEnd() + .writeStartObject("emptyObject").writeEnd().write("string", "string") + .write("number", 100).write("true", JsonValue.TRUE) + .write("false", JsonValue.FALSE).write("null", JsonValue.NULL) + .writeStartObject("object").write("name", "value") + .write("objectFooBar", JSONP_Util.buildJsonObjectFooBar()) + .write("arrayFooBar", JSONP_Util.buildJsonArrayFooBar()).writeEnd() + .writeStartArray("array").write("one").write("two") + .write(JSONP_Util.buildJsonObjectFooBar()) + .write(JSONP_Util.buildJsonArrayFooBar()).writeEnd().writeEnd() + .writeStartArray().write("string").write(Integer.MAX_VALUE) + .write(Long.MAX_VALUE).write(Double.MAX_VALUE) + .write(new BigInteger(new Integer(Integer.MAX_VALUE).toString())) + .write(true).write(false).writeNull().writeStartObject() + .write("name", "value").writeEnd().writeStartArray().write("one") + .write("two").writeEnd().writeEnd() + .write( + "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") + .writeEnd(); + generator.close(); + return sWriter.toString(); + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + return null; + } + } + + /********************************************************************************* + * buildJsonArray + *********************************************************************************/ + private JsonArray buildJsonArray() { + try { + System.out.println("Build a JsonArray"); + JsonArray jsonArray = Json.createArrayBuilder().add("") + .add(Json.createArrayBuilder()).add(Json.createObjectBuilder()) + .add("string").add(Integer.MIN_VALUE).add(Integer.MAX_VALUE) + .add(Long.MIN_VALUE).add(Long.MAX_VALUE).add(Double.MIN_VALUE) + .add(Double.MAX_VALUE) + .add(new BigInteger(new Integer(Integer.MAX_VALUE).toString())) + .add(BigDecimal.valueOf(Integer.MIN_VALUE)).add(JsonValue.TRUE) + .add(JsonValue.FALSE).add(JsonValue.NULL) + .add(Json.createObjectBuilder().add("emptyString", "") + .add("emptyArray", Json.createArrayBuilder()) + .add("emptyObject", Json.createObjectBuilder()) + .add("string", "string").add("number", 100) + .add("true", JsonValue.TRUE).add("false", JsonValue.FALSE) + .add("null", JsonValue.NULL) + .add("object", + Json.createObjectBuilder().add("name", "value") + .add("objectFooBar", JSONP_Util.buildJsonObjectFooBar()) + .add("arrayFooBar", JSONP_Util.buildJsonArrayFooBar())) + .add("array", + Json.createArrayBuilder().add("one").add("two") + .add(JSONP_Util.buildJsonObjectFooBar()) + .add(JSONP_Util.buildJsonArrayFooBar()))) + .add(Json.createArrayBuilder().add("string").add(Integer.MAX_VALUE) + .add(Long.MAX_VALUE).add(Double.MAX_VALUE) + .add(new BigInteger(new Integer(Integer.MAX_VALUE).toString())) + .add(JsonValue.TRUE).add(JsonValue.FALSE).add(JsonValue.NULL) + .add(Json.createObjectBuilder().add("name", "value")) + .add(Json.createArrayBuilder().add("one").add("two"))) + .add( + "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") + .build(); + return jsonArray; + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + return null; + } + } + + /* Tests */ + + /* + * @testName: jsonGeneratorObjectTest1 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:131; + * JSONP:JAVADOC:289; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. + * The output is written to a writer, read back as a string and filtered to + * remove whitespace and is compared against an expected string. + * + * { "object":{"string":"string","number":1,"true":true,"false":false,"null": + * null}, "array":["string", 1, true, false, null] } + */ + @Test + public void jsonGeneratorObjectTest1() throws Fault { + boolean pass = true; + try { + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generateSimpleJsonObject(generator); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; + System.out.println("Read the JSON text back from Writer removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(sWriter.toString()); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorObjectTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorObjectTest1 Failed"); + } + + /* + * @testName: jsonGeneratorObjectTest2 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:168; + * JSONP:JAVADOC:289; JSONP:JAVADOC:307; JSONP:JAVADOC:327; JSONP:JAVADOC:339; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. + * The output is written to a writer, read back as a string and filtered to + * remove whitespace and is compared against an expected string. + * + * { "emptyString":"", "emptyArray":[], "emptyObject":{}, "string":"string","+ + * "intMin":Integer.MIN_VALUE, "intMax":Integer.MAX_VALUE, + * "longMin":Long.MIN_VALUE, "longMax":Long.MAX_VALUE, "true":true, + * "false":false, "null":null, "object": { "emptyString":"", "emptyArray":[], + * "emptyObject":{}, "string":"string", "number":100, "true":true, + * "false":false, "null":null, "object":{"name":"value"} "array":["one","two"] + * }, "array": [ "string", Integer.MAX_VALUE, Long.MAX_VALUE, true, false, + * null, {"name":"value"}, ["one","two"] ], + * "asciiChars":"\"\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" + * } + */ + @Test + public void jsonGeneratorObjectTest2() throws Fault { + boolean pass = true; + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json.createGenerator(baos); + generator.writeStartObject().write("emptyString", "") + .writeStartArray("emptyArray").writeEnd() + .writeStartObject("emptyObject").writeEnd().write("string", "string") + .write("intMin", Integer.MIN_VALUE).write("intMax", Integer.MAX_VALUE) + .write("longMin", Long.MIN_VALUE).write("longMax", Long.MAX_VALUE) + .write("true", JsonValue.TRUE).write("false", JsonValue.FALSE) + .write("null", JsonValue.NULL).writeStartObject("object") + .write("emptyString", "").writeStartArray("emptyArray").writeEnd() + .writeStartObject("emptyObject").writeEnd().write("string", "string") + .write("number", 100).write("true", JsonValue.TRUE) + .write("false", JsonValue.FALSE).write("null", JsonValue.NULL) + .writeStartObject("object").write("name", "value").writeEnd() + .writeStartArray("array").write("one").write("two").writeEnd() + .writeEnd().writeStartArray("array").write("string") + .write(Integer.MAX_VALUE).write(Long.MAX_VALUE).write(JsonValue.TRUE) + .write(JsonValue.FALSE).write(JsonValue.NULL).writeStartObject() + .write("name", "value").writeEnd().writeStartArray().write("one") + .write("two").writeEnd().writeEnd() + .write("asciiChars", + "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") + .writeEnd(); + generator.close(); + + System.out.println("Dump of string: " + baos.toString("UTF-8")); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "{\"emptyString\":\"\",\"emptyArray\":[],\"emptyObject\":{},\"string\":\"string\"," + + "\"intMin\":" + Integer.MIN_VALUE + "," + "\"intMax\":" + + Integer.MAX_VALUE + "," + "\"longMin\":" + Long.MIN_VALUE + "," + + "\"longMax\":" + Long.MAX_VALUE + "," + + "\"true\":true,\"false\":false,\"null\":null,\"object\":{\"emptyString\":\"\",\"emptyArray\":[]," + + "\"emptyObject\":{},\"string\":\"string\",\"number\":100,\"true\":true,\"false\":false," + + "\"null\":null,\"object\":{\"name\":\"value\"}," + + "\"array\":[\"one\",\"two\"]},\"array\":[\"string\"," + + Integer.MAX_VALUE + "," + Long.MAX_VALUE + ",true,false,null," + + "{\"name\":\"value\"},[\"one\",\"two\"]],\"asciiChars\":" + + "\"\\\\\\\"\\\\\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\"" + + "}"; + + System.out.println("Read the JSON text back from OutputStream removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorObjectTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorObjectTest2 Failed"); + } + + /* + * @testName: jsonGeneratorObjectTest3 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:131; + * JSONP:JAVADOC:289; JSONP:JAVADOC:307; JSONP:JAVADOC:327; JSONP:JAVADOC:339; + * JSONP:JAVADOC:301; JSONP:JAVADOC:310; JSONP:JAVADOC:329; JSONP:JAVADOC:323; + * JSONP:JAVADOC:298; JSONP:JAVADOC:314; JSONP:JAVADOC:334; + * + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. + * The output is written to a writer, read back as a JsonObject and compared + * against an expected JsonObject. + * + * { "emptyString":"", "emptyArray":[], "emptyObject":{}, "string":"string","+ + * "intMin":Integer.MIN_VALUE, "intMax":Integer.MAX_VALUE, + * "longMin":Long.MIN_VALUE, "longMax":Long.MAX_VALUE, + * "doubleMin":Double.MIN_VALUE, "doubleMax":Double.MAX_VALUE, + * "bigInteger":Integer.MAX_VALUE, "bigDecimal":Integer.MIN_VALUE, + * "true":true, "false":false, "null":null, "object": { "emptyString":"", + * "emptyArray":[], "emptyObject":{}, "string":"string", "number":100, + * "true":true, "false":false, "null":null, + * "object":{"name":"value",{"foo":"bar"}}, + * "array":["one","two",["foo","bar"]] }, "array": [ "string", + * Integer.MAX_VALUE, Long.MAX_VALUE, Double.MAX_VALUE, Integer.MAX_VALUE + * true, false, null, {"name":"value"}, ["one","two"] ], + * "asciiChars":"\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" + * } + */ + @Test + public void jsonGeneratorObjectTest3() throws Fault { + boolean pass = true; + try { + JsonObject expJsonObject = buildJsonObject(); + String jsonText = generateJsonObject(); + + JsonReader reader = Json.createReader(new StringReader(jsonText)); + JsonObject actJsonObject = (JsonObject) reader.read(); + + // Do comparison + System.out.println("Compare expJsonObject and actJsonObject for equality"); + pass = JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject); + + } catch (Exception e) { + throw new Fault("jsonGeneratorObjectTest3 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorObjectTest3 Failed"); + } + + /* + * @testName: jsonGeneratorObjectTest4 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:416; + * JSONP:JAVADOC:289; JSONP:JAVADOC:163; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. + * Encoding is done in UTF-16BE. The output is written to an OutputStream as + * UTF-16BE encoding, read back as a string using UTF-16BE encoding and + * filtered to remove whitespace and is compared against an expected string. + * + * { "object":{"string":"string","number":1,"true":true,"false":false,"null": + * null}, "array":["string", 1, true, false, null] } Tests the following API + * call: + * + * JsonGenerator generator = + * Json.createGeneratorFactory(Map).createGenerator(OutputStream, + * Charset); + */ + @Test + public void jsonGeneratorObjectTest4() throws Fault { + boolean pass = true; + try { + System.out.println("Create generator output in UTF-16BE encoding."); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()) + .createGenerator(baos, JSONP_Util.UTF_16BE); + generateSimpleJsonObject(generator); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; + System.out.println( + "Read the JSON text back encoding from OutputStream using UTF-16BE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorObjectTest4 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorObjectTest4 Failed"); + } + + /* + * @testName: jsonGeneratorObjectTest5 + * + * @assertion_ids: JSONP:JAVADOC:131; JSONP:JAVADOC:341; JSONP:JAVADOC:295; + * JSONP:JAVADOC:289; + * + * @test_Strategy: Test generation of object data with multiple unicode chars + * in data. The output is written to a writer, read back using a reader as a + * JsonObject and extracts the JsonString value out and compares it against + * the expected JsonString value. + * + * Generate the following object of unicode char(s): + * + * {"unicodechars":"\u0000\u000f\u001f\u00ff\uff00\uffff"} + */ + @Test + public void jsonGeneratorObjectTest5() throws Fault { + boolean pass = true; + JsonReader reader = null; + String expUnicodeChars = "\u0000\u000f\u001f\u00ff\uff00\uffff"; + try { + + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject() + .write("unicodechars", "\u0000\u000f\u001f\u00ff\uff00\uffff") + .writeEnd(); + generator.close(); + sWriter.close(); + + System.out.println("Testing read of " + sWriter.toString()); + reader = Json.createReader(new StringReader(sWriter.toString())); + JsonObject jsonObject = reader.readObject(); + String actUnicodeChars = jsonObject.getJsonString("unicodechars") + .getString(); + reader.close(); + System.out.println("actUnicodeChars=" + actUnicodeChars); + + pass = JSONP_Util.assertEquals(expUnicodeChars, actUnicodeChars); + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + pass = false; + } + if (!pass) + throw new Fault("jsonGeneratorObjectTest5 Failed"); + } + + /* + * @testName: jsonGeneratorArrayTest1 + * + * @assertion_ids: JSONP:JAVADOC:339; JSONP:JAVADOC:341; JSONP:JAVADOC:295; + * JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; JSONP:JAVADOC:325; + * JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:131; JSONP:JAVADOC:289; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonArray. + * The output is written to a writer, read back as a string and filtered to + * remove whitespace and is compared against an expected string. + * + * [ {"string":"string","number":1,"true":true,"false":false,"null":null}, + * ["string", 1, true, false, null] ] + * + */ + @Test + public void jsonGeneratorArrayTest1() throws Fault { + boolean pass = true; + try { + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generateSimpleJsonArray(generator); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "[{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},[\"string\",1,true,false,null]]"; + System.out.println("Read the JSON text back from Writer removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(sWriter.toString()); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorArrayTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorArrayTest1 Failed"); + } + + /* + * @testName: jsonGeneratorArrayTest2 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:168; + * JSONP:JAVADOC:289; JSONP:JAVADOC:327; JSONP:JAVADOC:339; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonArray. + * The output is written to a writer, read back as a string and filtered to + * remove whitespace and is compared against an expected string. + * + * [ "", [], {}, "string", Integer.MIN_VALUE, Integer.MAX_VALUE, + * Long.MIN_VALUE, Long.MAX_VALUE, true, false, null, { "emptyString":"", + * "emptyArray":[], "emptyObject":{}, "string":"string", "number":100, + * "true":true, "false":false, "null":null, "object":{"name":"value"}, + * "array":["one","two"] }, [ "string", Integer.MAX_VALUE, Long.MAX_VALUE, + * true, false, null, {"name":"value"}, ["one","two"] ], + * "\"\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" + * ] + */ + @Test + public void jsonGeneratorArrayTest2() throws Fault { + boolean pass = true; + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json.createGenerator(baos); + generator.writeStartArray().write("").writeStartArray().writeEnd() + .writeStartObject().writeEnd().write("string") + .write(Integer.MIN_VALUE).write(Integer.MAX_VALUE) + .write(Long.MIN_VALUE).write(Long.MAX_VALUE).write(JsonValue.TRUE) + .write(JsonValue.FALSE).write(JsonValue.NULL).writeStartObject() + .write("emptyString", "").writeStartArray("emptyArray").writeEnd() + .writeStartObject("emptyObject").writeEnd().write("string", "string") + .write("number", 100).write("true", JsonValue.TRUE) + .write("false", JsonValue.FALSE).write("null", JsonValue.NULL) + .writeStartObject("object").write("name", "value").writeEnd() + .writeStartArray("array").write("one").write("two").writeEnd() + .writeEnd().writeStartArray().write("string").write(Integer.MAX_VALUE) + .write(Long.MAX_VALUE).write(JsonValue.TRUE).write(JsonValue.FALSE) + .write(JsonValue.NULL).writeStartObject().write("name", "value") + .writeEnd().writeStartArray().write("one").write("two").writeEnd() + .writeEnd() + .write( + "\\\"\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM") + .writeEnd(); + generator.close(); + + System.out.println("Dump of string: " + baos.toString("UTF-8")); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "[\"\",[],{},\"string\"," + Integer.MIN_VALUE + "," + + Integer.MAX_VALUE + "," + Long.MIN_VALUE + "," + Long.MAX_VALUE + + "," + "true,false,null,{\"emptyString\":\"\",\"emptyArray\":[]," + + "\"emptyObject\":{},\"string\":\"string\",\"number\":100,\"true\":true,\"false\":false," + + "\"null\":null,\"object\":{\"name\":\"value\"}," + + "\"array\":[\"one\",\"two\"]},[\"string\"," + Integer.MAX_VALUE + + "," + Long.MAX_VALUE + ",true,false,null," + + "{\"name\":\"value\"},[\"one\",\"two\"]]," + + "\"\\\\\\\"\\\\\\\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM\"" + + "]"; + + System.out.println("Read the JSON text back from Writer removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorArrayTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorArrayTest2 Failed"); + } + + /* + * @testName: jsonGeneratorArrayTest3 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:131; + * JSONP:JAVADOC:289; JSONP:JAVADOC:327; JSONP:JAVADOC:339; JSONP:JAVADOC:329; + * JSONP:JAVADOC:321; JSONP:JAVADOC:323; JSONP:JAVADOC:332; JSONP:JAVADOC:337; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonArray. + * The output is written to a writer, read back as a JsonArray and compared + * against an expected JsonArray. + * + * [ "", [], {}, "string", Integer.MIN_VALUE, Integer.MAX_VALUE, + * Long.MIN_VALUE, Long.MAX_VALUE, Double.MIN_VALUE, Double.MAX_VALUE, + * Integer.MAX_VALUE, Integer.MIN_VALUE, true, false, null, { + * "emptyString":"", "emptyArray":[], "emptyObject":{}, "string":"string", + * "number":100, "true":true, "false":false, "null":null, + * "object":{"name":"value",{"foo":"bar"}}, + * "array":["one","two",["foo","bar"]] }, [ "string", Integer.MAX_VALUE, + * Long.MAX_VALUE, Double.MAX_VALUE, Integer.MAX_VALUE true, false, null, + * {"name":"value"}, ["one","two"] ], + * "\"\\!@#$%^&*()_+|~1234567890-=`[]{}:;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" + * ] + */ + @Test + public void jsonGeneratorArrayTest3() throws Fault { + boolean pass = true; + try { + JsonArray expJsonArray = buildJsonArray(); + String jsonText = generateJsonArray(); + System.out.println("generator json text: " + jsonText); + + JsonReader reader = Json.createReader(new StringReader(jsonText)); + JsonArray actJsonArray = (JsonArray) reader.read(); + + // Do comparison + System.out.println("Compare expJsonArray and actJsonArray for equality"); + pass = JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray); + + } catch (Exception e) { + throw new Fault("jsonGeneratorArrayTest3 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorArrayTest3 Failed"); + } + + /* + * @testName: jsonGeneratorArrayTest4 + * + * @assertion_ids: JSONP:JAVADOC:339; JSONP:JAVADOC:341; JSONP:JAVADOC:115; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:163; JSONP:JAVADOC:289; + * JSONP:JAVADOC:416; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonArray. + * Encoding is done in UTF-16BE. The output is written to an OutputStream as + * UTF-16BE encoding, read back as a string using UTF-16BE encoding and + * filtered to remove whitespace and is compared against an expected string. + * + * [ {"string":"string","number":1,"true":true,"false":false,"null":null}, + * ["string", 1, true, false, null] ] + * + */ + @Test + public void jsonGeneratorArrayTest4() throws Fault { + boolean pass = true; + try { + System.out.println("Create generator output in UTF-16BE encoding."); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()) + .createGenerator(baos, JSONP_Util.UTF_16BE); + generateSimpleJsonArray(generator); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "[{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},[\"string\",1,true,false,null]]"; + System.out.println( + "Read the JSON text back from OutputStream using UTF-16BE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorArrayTest4 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorArrayTest4 Failed"); + } + + /* + * @testName: jsonGeneratorArrayTest5 + * + * @assertion_ids: JSONP:JAVADOC:131; JSONP:JAVADOC:339; JSONP:JAVADOC:319; + * JSONP:JAVADOC:289; + * + * @test_Strategy: Test generation of array data with multiple unicode chars + * in data. The output is written to a writer, read back using a reader as a + * JsonArray and extracts the JsonString value out and compares it against the + * expected JsonString value. + * + * Generate the following array of unicode char(s): + * + * ["\u0000\u000f\u001f\u00ff\uff00\uffff"] + */ + @Test + public void jsonGeneratorArrayTest5() throws Fault { + boolean pass = true; + JsonReader reader = null; + String expUnicodeChars = "\u0000\u000f\u001f\u00ff\uff00\uffff"; + try { + + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("\u0000\u000f\u001f\u00ff\uff00\uffff") + .writeEnd(); + generator.close(); + sWriter.close(); + + System.out.println("Testing read of " + sWriter.toString()); + reader = Json.createReader(new StringReader(sWriter.toString())); + JsonArray jsonArray = reader.readArray(); + String actUnicodeChars = jsonArray.getJsonString(0).getString(); + reader.close(); + System.out.println("actUnicodeChars=" + actUnicodeChars); + + pass = JSONP_Util.assertEquals(expUnicodeChars, actUnicodeChars); + } catch (Exception e) { + System.err.println("Exception occurred: " + e); + pass = false; + } + if (!pass) + throw new Fault("jsonGeneratorArrayTest5 Failed"); + } + + /* + * @testName: jsonGeneratorObjectConfigTest1 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:289; + * JSONP:JAVADOC:162; JSONP:JAVADOC:416; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. + * This test uses the configuration feature to PRETTY PRINT. The output is + * written to a Writer, read back as a string and filtered to remove + * whitespace and is compared against an expected string. + * + * { "object":{"string":"string","number":1,"true":true,"false":false,"null": + * null}, "array":["string", 1, true, false, null] } Tests following API call: + * + * JsonGenerator generator = Json.createGeneratorFactory(Map).createGenerator(Writer) + */ + @Test + public void jsonGeneratorObjectConfigTest1() throws Fault { + boolean pass = true; + try { + System.out.println("Create JsonGenerator using configuration with PRETTY_PRINTING"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()) + .createGenerator(sWriter); + generateSimpleJsonObject(generator); + + // Dump JsonText output with PRETTY_PRINTING feature + System.out.println("PRETTY_PRINTING feature\n" + sWriter.toString()); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; + System.out.println("Read the JSON text back from Writer removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(sWriter.toString()); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorObjectConfigTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorObjectConfigTest1 Failed"); + } + + /* + * @testName: jsonGeneratorObjectConfigTest2 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:289; + * JSONP:JAVADOC:200; JSONP:JAVADOC:416; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. + * This test uses the configuration feature to PRETTY PRINT. The output is + * written to a OutputStream, read back as a string and filtered to remove + * whitespace and is compared against an expected string. + * + * { "object":{"string":"string","number":1,"true":true,"false":false,"null": + * null}, "array":["string", 1, true, false, null] } Tests following API call: + * + * JsonGenerator generator = Json.createGeneratorFactory(Map).createGenerator(OutputStream) + */ + @Test + public void jsonGeneratorObjectConfigTest2() throws Fault { + boolean pass = true; + try { + System.out.println("Create JsonGenerator using configuration with PRETTY_PRINTING"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()) + .createGenerator(baos); + generateSimpleJsonObject(generator); + + // Dump JsonText output with PRETTY_PRINTING feature + System.out.println("PRETTY_PRINTING feature\n" + baos.toString("UTF-8")); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; + System.out.println("Read the JSON text back from Writer removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorObjectConfigTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorObjectConfigTest2 Failed"); + } + + /* + * @testName: jsonGeneratorObjectEncodingTest1 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:163; + * JSONP:JAVADOC:289; JSONP:JAVADOC:416; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. + * The output is written to an OutputStream using UTF-8 encoding, read back as + * a string and filtered to remove whitespace and is compared against an + * expected string. + * + * { "object":{"string":"string","number":1,"true":true,"false":false,"null": + * null}, "array":["string", 1, true, false, null] } + */ + @Test + public void jsonGeneratorObjectEncodingTest1() throws Fault { + boolean pass = true; + try { + System.out.println("Create JsonGenerator using UTF-8 encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()) + .createGenerator(baos, JSONP_Util.UTF_8); + generateSimpleJsonObject(generator); + + // Dump JsonText output + System.out.println("Generator Output=" + baos.toString("UTF-8")); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; + System.out.println( + "Read the JSON text back from OutputStream using UTF-8 encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorObjectEncodingTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorObjectEncodingTest1 Failed"); + } + + /* + * @testName: jsonGeneratorObjectEncodingTest2 + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:289; + * JSONP:JAVADOC:163; JSONP:JAVADOC:416; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. + * This test uses the configuration feature to PRETTY PRINT. The output is + * written to an OutputStream using UTF-16BE encoding, read back as a string + * and filtered to remove whitespace and is compared against an expected + * string. + * + * { "object":{"string":"string","number":1,"true":true,"false":false,"null": + * null}, "array":["string", 1, true, false, null] } Tests the following API + * call: + * + * JsonGenerator generator = Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset); + */ + @Test + public void jsonGeneratorObjectEncodingTest2() throws Fault { + boolean pass = true; + try { + System.out.println( + "Create JsonGenerator using configuration with PRETTY_PRINTING using UTF-16BE encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getPrettyPrintingConfig()) + .createGenerator(baos, JSONP_Util.UTF_16BE); + generateSimpleJsonObject(generator); + + // Dump JsonText output with PRETTY_PRINTING feature + System.out.println("PRETTY_PRINTING feature\n" + baos.toString("UTF-16BE")); + + // Do comparison + System.out.println("Create expected JSON text with no whitespace"); + String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; + System.out.println( + "Read the JSON text back from OutputStream using UTF-16BE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); + pass = JSONP_Util.assertEqualsJsonText(expJson, actJson); + + } catch (Exception e) { + throw new Fault("jsonGeneratorObjectEncodingTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonGeneratorObjectEncodingTest2 Failed"); + } + + /* + * @testName: jsonGeneratorUTFEncodedTests + * + * @assertion_ids: JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * JSONP:JAVADOC:295; JSONP:JAVADOC:304; JSONP:JAVADOC:292; JSONP:JAVADOC:317; + * JSONP:JAVADOC:325; JSONP:JAVADOC:319; JSONP:JAVADOC:115; JSONP:JAVADOC:163; + * JSONP:JAVADOC:289; JSONP:JAVADOC:416; + * + * @test_Strategy: Tests various JsonGenerator API's to create a JsonObject. + * + * The output is written to an OutputStream using all supported UTF encodings + * and read back as a string and filtered to remove whitespace and is compared + * against an expected string. The following UTF encodings are tested: + * + * UTF8 UTF16 UTF16LE UTF16BE UTF32LE UTF32BE + * + * { "object":{"string":"string","number":1,"true":true,"false":false,"null": + * null}, "array":["string", 1, true, false, null] } + */ + @Test + public void jsonGeneratorUTFEncodedTests() throws Fault { + boolean pass = true; + System.out.println( + "Create expected JSON text with no whitespace for use with comparison"); + String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; + try { + System.out.println( + "-----------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-8]"); + System.out.println( + "-----------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonGenerator using UTF-8 encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()) + .createGenerator(baos, JSONP_Util.UTF_8); + generateSimpleJsonObject(generator); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-8")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-8 encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing generation to UTF-8 encoding: " + e); + } + try { + System.out.println( + "------------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-16]"); + System.out.println( + "------------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonGenerator using UTF-16 encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()) + .createGenerator(baos, JSONP_Util.UTF_16); + generateSimpleJsonObject(generator); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-16")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-16 encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing generation to UTF-16 encoding: " + e); + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-16LE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonGenerator using UTF-16LE encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()) + .createGenerator(baos, JSONP_Util.UTF_16LE); + generateSimpleJsonObject(generator); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-16LE")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-16LE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16LE")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println( + "Exception occurred testing generation to UTF-16LE encoding: " + e); + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-16BE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonGenerator using UTF-16BE encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()) + .createGenerator(baos, JSONP_Util.UTF_16BE); + generateSimpleJsonObject(generator); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-16BE")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-16BE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println( + "Exception occurred testing generation to UTF-16BE encoding: " + e); + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-32LE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonGenerator using UTF-32LE encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()) + .createGenerator(baos, JSONP_Util.UTF_32LE); + generateSimpleJsonObject(generator); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-32LE")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-32LE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-32LE")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println( + "Exception occurred testing generation to UTF-32LE encoding: " + e); + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createGeneratorFactory(Map).createGenerator(OutputStream, Charset) as UTF-32BE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonGenerator using UTF-32BE encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json + .createGeneratorFactory(JSONP_Util.getEmptyConfig()) + .createGenerator(baos, JSONP_Util.UTF_32BE); + generateSimpleJsonObject(generator); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-32BE")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-32BE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-32BE")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println( + "Exception occurred testing generation to UTF-32BE encoding: " + e); + } + if (!pass) + throw new Fault("jsonGeneratorUTFEncodedTests Failed"); + } + + /* + * @testName: jsonGeneratorExceptionTests + * + * @assertion_ids: JSONP:JAVADOC:339; JSONP:JAVADOC:341; JSONP:JAVADOC:115; + * JSONP:JAVADOC:293; JSONP:JAVADOC:296; JSONP:JAVADOC:299; JSONP:JAVADOC:302; + * JSONP:JAVADOC:305; JSONP:JAVADOC:308; JSONP:JAVADOC:311; JSONP:JAVADOC:315; + * JSONP:JAVADOC:297; JSONP:JAVADOC:303; JSONP:JAVADOC:306; JSONP:JAVADOC:309; + * JSONP:JAVADOC:312; JSONP:JAVADOC:316; JSONP:JAVADOC:336; JSONP:JAVADOC:335; + * JSONP:JAVADOC:290; JSONP:JAVADOC:331; JSONP:JAVADOC:381; JSONP:JAVADOC:382; + * JSONP:JAVADOC:350; JSONP:JAVADOC:352; JSONP:JAVADOC:354; JSONP:JAVADOC:356; + * JSONP:JAVADOC:358; JSONP:JAVADOC:360; JSONP:JAVADOC:362; JSONP:JAVADOC:364; + * JSONP:JAVADOC:366; JSONP:JAVADOC:347; JSONP:JAVADOC:348; JSONP:JAVADOC:368; + * JSONP:JAVADOC:370; JSONP:JAVADOC:372; JSONP:JAVADOC:374; + * + * @test_Strategy: Tests various exception test cases. + * + * NumberFormatException JsonGenerationException + * + */ + @Test + public void jsonGeneratorExceptionTests() throws Fault { + boolean pass = true; + + // Test NumberFormatException for write(double) if value is + // Not-a-Number(NaN) or infinity + try { + System.out.println( + "Trip NumberFormatException for write(double) if value is Not-a-Number(NaN) or infinity"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write(Double.NaN); + System.err.println("Did not get expected NumberFormatException"); + pass = false; + } catch (NumberFormatException e) { + System.out.println("Caught expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test NumberFormatException for write(double) if value is + // Not-a-Number(NaN) or infinity + try { + System.out.println( + "Trip NumberFormatException for write(double) if value is Not-a-Number(NaN) or infinity"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write(Double.NEGATIVE_INFINITY); + System.err.println("Did not get expected NumberFormatException"); + pass = false; + } catch (NumberFormatException e) { + System.out.println("Caught expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test NumberFormatException for write(double) if value is + // Not-a-Number(NaN) or infinity + try { + System.out.println( + "Trip NumberFormatException for write(double) if value is Not-a-Number(NaN) or infinity"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write(Double.POSITIVE_INFINITY); + System.err.println("Did not get expected NumberFormatException"); + pass = false; + } catch (NumberFormatException e) { + System.out.println("Caught expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test NumberFormatException for write(String,double) if value is + // Not-a-Number(NaN) or infinity + try { + System.out.println( + "Trip NumberFormatException for write(String,double) if value is Not-a-Number(NaN) or infinity"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write("badnumber", Double.NaN); + System.err.println("Did not get expected NumberFormatException"); + pass = false; + } catch (NumberFormatException e) { + System.out.println("Caught expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test NumberFormatException for write(String,double) if value is + // Not-a-Number(NaN) or infinity + try { + System.out.println( + "Trip NumberFormatException for write(String,double) if value is Not-a-Number(NaN) or infinity"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write("badnumber", Double.NEGATIVE_INFINITY); + System.err.println("Did not get expected NumberFormatException"); + pass = false; + } catch (NumberFormatException e) { + System.out.println("Caught expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test NumberFormatException for write(String,double) if value is + // Not-a-Number(NaN) or infinity + try { + System.out.println( + "Trip NumberFormatException for write(String,double) if value is Not-a-Number(NaN) or infinity"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write("badnumber", Double.POSITIVE_INFINITY); + System.err.println("Did not get expected NumberFormatException"); + pass = false; + } catch (NumberFormatException e) { + System.out.println("Caught expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonGenerationExceptipn if an incomplete JSON is generated. + try { + System.out.println( + "Trip JsonGenerationExceptipn if an incomplete JSON is generated."); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write("name", "value"); + generator.close(); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonGenerationExceptipn if an incomplete JSON is generated. + try { + System.out.println( + "Trip JsonGenerationExceptipn if an incomplete JSON is generated."); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("string"); + generator.close(); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(JsonValue) if not called within + // array context + try { + System.out.println( + "Trip JsonGenerationException for write(JsonValue) if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write(JsonValue.TRUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String) if not called within array + // context + try { + System.out.println( + "Trip JsonGenerationException for write(String) if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write("name"); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(BigInteger) if not called within + // array context + try { + System.out.println( + "Trip JsonGenerationException for write(BigInteger) if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject() + .write(new BigInteger(new Integer(Integer.MAX_VALUE).toString())); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(BigDecimal) if not called within + // array context + try { + System.out.println( + "Trip JsonGenerationException for write(BigDecimal) if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write(BigDecimal.valueOf(Integer.MIN_VALUE)); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(int) if not called within array + // context + try { + System.out.println( + "Trip JsonGenerationException for write(int) if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write(Integer.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(long) if not called within array + // context + try { + System.out.println( + "Trip JsonGenerationException for write(long) if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write(Long.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(double) if not called within array + // context + try { + System.out.println( + "Trip JsonGenerationException for write(double) if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write(Double.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(boolean) if not called within + // array context + try { + System.out.println( + "Trip JsonGenerationException for write(boolean) if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write(true); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for writeNull() if not called within array + // context + try { + System.out.println( + "Trip JsonGenerationException for writeNull() if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeNull(); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for writeStartArray() if not called within + // array context + try { + System.out.println( + "Trip JsonGenerationException for writeStartArray() if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeStartArray(); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for writeStartObject() if not called within + // array context + try { + System.out.println( + "Trip JsonGenerationException for writeStartObject() if not called within array context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeStartObject(); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,JsonValue) if not called + // within object context + try { + System.out.println( + "Trip JsonGenerationException for write(String,JsonValue) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("string", JsonValue.TRUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,String) if not called + // within object context + try { + System.out.println( + "Trip JsonGenerationException for write(String,String) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("string", "name"); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,BigInteger) if not called + // within object context + try { + System.out.println( + "Trip JsonGenerationException for write(String,BigInteger) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("string", + new BigInteger(new Integer(Integer.MAX_VALUE).toString())); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,BigDecimal) if not called + // within object context + try { + System.out.println( + "Trip JsonGenerationException for write(String,BigDecimal) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("string", + BigDecimal.valueOf(Integer.MIN_VALUE)); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,int) if not called within + // object context + try { + System.out.println( + "Trip JsonGenerationException for write(String,int) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("string", Integer.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,long) if not called within + // object context + try { + System.out.println( + "Trip JsonGenerationException for write(String,long) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("string", Long.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,double) if not called + // within object context + try { + System.out.println( + "Trip JsonGenerationException for write(String,double) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("string", Double.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,boolean) if not called + // within object context + try { + System.out.println( + "Trip JsonGenerationException for write(String,boolean) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write("string", true); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for writeNull(String) if not called within + // object context + try { + System.out.println( + "Trip JsonGenerationException for writeNull(String) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeNull("string"); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for writeStartArray(String) if not called + // within object context + try { + System.out.println( + "Trip JsonGenerationException for writeStartArray(String) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeStartArray("string"); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for writeStartObject(String) if not called + // within object context + try { + System.out.println( + "Trip JsonGenerationException for writeStartObject(String) if not called within object context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeStartObject("string"); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,JsonValue) when invoked + // after the writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(String,JsonValue) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeEnd().write("name", "value"); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for writeEnd() when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for writeEnd() when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeEnd().writeEnd(); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,BigInteger) when invoked + // after the writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(String,BigInteger) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeEnd().write("name", + new BigInteger(new Integer(Integer.MAX_VALUE).toString())); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,BigDecimal) when invoked + // after the writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(String,BigDecimal) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeEnd().write("name", + BigDecimal.valueOf(Integer.MIN_VALUE)); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,int) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(String,int) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeEnd().write("name", Integer.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,long) when invoked after + // the writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(String,long) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeEnd().write("name", Long.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,double) when invoked after + // the writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(String,double) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeEnd().write("name", Double.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String,boolean) when invoked after + // the writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(String,boolean) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeEnd().write("name", false); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for writeNull(String) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for writeNull(String) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeEnd().writeNull("name"); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(JsonValue) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(JsonValue) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeEnd().write(JsonValue.TRUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(String) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(String) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeEnd().write(JsonValue.TRUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(BigDecimal) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(BigDecimal) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeEnd() + .write(BigDecimal.valueOf(Integer.MIN_VALUE)); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(BigInteger) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(BigInteger) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeEnd() + .write(new BigInteger(new Integer(Integer.MAX_VALUE).toString())); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(int) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(int) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeEnd().write(Integer.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(long) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(long) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeEnd().write(Long.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(double) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(double) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeEnd().write(Double.MAX_VALUE); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for write(boolean) when invoked after the + // writeEnd method is called + try { + System.out.println( + "Trip JsonGenerationException for write(boolean) when invoked after the writeEnd method is called"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeEnd().write(true); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test JsonGenerationException for for writeNull() when invoked with no + // context + try { + System.out.println( + "Trip JsonGenerationException for for writeNull() when invoked with no context"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().writeEnd().writeNull(); + System.err.println("Did not get expected JsonGenerationException"); + pass = false; + } catch (JsonGenerationException e) { + System.out.println("Caught expected JsonGenerationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonGeneratorExceptionTests Failed"); + } + + /* + * @testName: flushTest + * + * @assertion_ids: JSONP:JAVADOC:131; JSONP:JAVADOC:289; JSONP:JAVADOC:291; + * JSONP:JAVADOC:340; JSONP:JAVADOC:341; JSONP:JAVADOC:342; + * + * @test_Strategy: Generate some partial Json, flush output and compare + * output. Generate additional Json to complete, flush output again and + * compare. Test passes if comparisons are correct. + * + * {"object":{},"array":[]} + */ + @Test + public void flushTest() throws Fault { + boolean pass = true; + try { + System.out.println("Generate some partial Json and flush output."); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().writeStartObject("object").writeEnd() + .flush(); + + // Do comparison 1 + System.out.println("Create expected partial JSON text with no whitespace"); + String expJson = "{\"object\":{}"; + System.out.println("Read the JSON text back from Writer removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(sWriter.toString()); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + System.out.println("Generate additional Json to complete and flush output."); + generator.writeStartArray("array").writeEnd().writeEnd().flush(); + + // Do comparison 2 + expJson = "{\"object\":{},\"array\":[]}"; + System.out.println("Read the JSON text back from Writer removing whitespace"); + actJson = JSONP_Util.removeWhitespace(sWriter.toString()); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + generator.close(); + + } catch (Exception e) { + throw new Fault("flushTest Failed: ", e); + } + if (!pass) + throw new Fault("flushTest Failed"); + } + + /* + * @testName: jsonGeneratorIOErrorTests + * + * @assertion_ids: JSONP:JAVADOC:346; JSONP:JAVADOC:551; + * + * @test_Strategy: Tests for JsonException for testable i/o errors. + * + */ + @Test + public void jsonGeneratorIOErrorTests() throws Fault { + boolean pass = true; + + // Trip JsonException if there is an i/o error on JsonGenerator.close() + try { + System.out.println( + "Trip JsonException if there is an i/o error on JsonGenerator.close()."); + MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); + JsonGenerator generator = Json.createGenerator(mbw); + generator.writeStartObject().writeEnd(); + mbw.setThrowIOException(true); + System.out.println("Calling JsonGenerator.close()"); + generator.close(); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonException if there is an i/o error on JsonGenerator.flush() + try { + System.out.println( + "Trip JsonException if there is an i/o error on JsonGenerator.flush()."); + MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); + JsonGenerator generator = Json.createGenerator(mbw); + generator.writeStartObject().writeEnd(); + mbw.setThrowIOException(true); + System.out.println("Calling JsonGenerator.flush()"); + generator.flush(); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonGeneratorIOErrorTests Failed"); + } + + /* + * @testName: jsonGeneratorDocumentRootTest + * + * @assertion_ids: JSONP:JAVADOC:317; JSONP:JAVADOC:319; JSONP:JAVADOC:321; + * JSONP:JAVADOC:323; JSONP:JAVADOC:325; JSONP:JAVADOC:327; JSONP:JAVADOC:329; + * JSONP:JAVADOC:332; JSONP:JAVADOC:583; JSONP:JAVADOC:584; JSONP:JAVADOC:585; + * JSONP:JAVADOC:586; JSONP:JAVADOC:587; JSONP:JAVADOC:588; JSONP:JAVADOC:662; + * JSONP:JAVADOC:663; JSONP:JAVADOC:664; JSONP:JAVADOC:665; JSONP:JAVADOC:666; + * JSONP:JAVADOC:667; JSONP:JAVADOC:289; JSONP:JAVADOC:341; JSONP:JAVADOC:672; + * + * @test_Strategy: Tests RFC 7159 grammar changes:
{@code + * "JSON-text = ws value ws"}
{@code + * "value = false / null / true / object / array / number / string"} + */ + @Test + public void jsonGeneratorDocumentRootTest() throws Fault { + Generator genTest = new Generator(); + final TestResult result = genTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsongeneratortests/Generator.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsongeneratortests/Generator.java new file mode 100644 index 00000000..0064716a --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsongeneratortests/Generator.java @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsongeneratortests; + +import jakarta.jsonp.tck.api.common.JsonValueType; +import jakarta.jsonp.tck.api.common.TestResult; +import java.io.StringReader; +import java.io.StringWriter; +import java.math.BigDecimal; +import java.math.BigInteger; +import jakarta.json.Json; +import jakarta.json.JsonReader; +import jakarta.json.JsonValue; +import jakarta.json.stream.JsonGenerator; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; +import jakarta.json.JsonObject; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests: {@link JsonGenerator} + * API methods. + */ +public class Generator { + + /** Tests input data. */ + private static final Object[] VALUES = new Object[] { OBJ_VALUE, // write(JsonValue) + // for + // JsonObject + createEmptyArrayWithStr(), // write(JsonValue) for simple JsonArray + STR_VALUE, // write(JsonValue) for String + INT_VALUE, // write(JsonValue) for int + LNG_VALUE, // write(JsonValue) for long + DBL_VALUE, // write(JsonValue) for double + BIN_VALUE, // write(JsonValue) for BigInteger + BDC_VALUE, // write(JsonValue) for BigDecimal + BOOL_VALUE, // write(JsonValue) for boolean + null // write(JsonValue) for null + }; + + /** + * Test {@link JsonGenerator} API methods. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonGenerator API methods for RFC 7159 grammar changes."); + System.out.println("JsonGenerator API methods for RFC 7159 grammar changes."); + testPrimitiveTypesInRoot(result); + testWrittingObjectByParts(result); + return result; + } + + /** + * Test primitive types as JSON value stored in JSON document root. RFC 7159 + * grammar changes now allows such a values to be stored in JSON document + * root. + */ + private void testPrimitiveTypesInRoot(final TestResult result) { + for (Object value : VALUES) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println(" - write(JsonValue) for " + typeName + " as an argument"); + verifyJsonGeneratorForJsonValue(result, value); + verifyJsonGeneratorForSimpleType(result, value); + } + } + + /** + * Verify JSON object generation using low level methods + * {@code writeStartObject()}, {@code writeEnd()}, {@code writeKey(String)} + * and {@code write(String)}. + */ + private void testWrittingObjectByParts(final TestResult result) { + System.out.println(" - generate JSON object"); + final StringWriter strWriter = new StringWriter(); + try (JsonGenerator generator = Json.createGenerator(strWriter)) { + generator.writeStartObject(); + generator.writeKey(STR_NAME); + generator.write(STR_VALUE); + generator.writeEnd(); + } + final String out = strWriter.toString(); + final JsonObject check = createSimpleObjectStr(); + if (operationFailed(check, out)) { + final String checkStr = check.toString(); + System.out.println( + " Generated JSON object " + out + " shall be " + checkStr); + result.fail("generate JSON object", + "Generated value " + out + " shall be " + checkStr); + } else { + System.out.println(" Output: " + out); + } + + } + + /** + * Verify JSON document root generation for provided JSON value. + */ + private void verifyJsonGeneratorForJsonValue(final TestResult result, + final Object value) { + final StringWriter strWriter = new StringWriter(); + final JsonValue jsonValue = toJsonValue(value); + try (JsonGenerator generator = Json.createGenerator(strWriter)) { + generator.write(jsonValue); + } + final String out = strWriter.toString(); + if (operationFailed(jsonValue, out)) { + final String check = jsonValue.toString(); + System.out.println(" Generated JSON value " + out + " shall be " + check); + result.fail("write(JsonValue)", + "Generated value " + out + " shall be " + check); + } else { + System.out.println(" Output (JsonValue): " + out); + } + } + + /** + * Verify JSON document root generation for provided JSON value. + */ + @SuppressWarnings("UnnecessaryUnboxing") + private void verifyJsonGeneratorForSimpleType(final TestResult result, + final Object value) { + final StringWriter strWriter = new StringWriter(); + try (JsonGenerator generator = Json.createGenerator(strWriter)) { + switch (JsonValueType.getType(value)) { + case String: + generator.write((String) value); + break; + case Integer: + generator.write(((Integer) value).intValue()); + break; + case Long: + generator.write(((Long) value).longValue()); + break; + case BigInteger: + generator.write((BigInteger) value); + break; + case Double: + generator.write(((Double) value).doubleValue()); + break; + case BigDecimal: + generator.write((BigDecimal) value); + break; + case Boolean: + generator.write(((Boolean) value).booleanValue() ? JsonValue.TRUE + : JsonValue.FALSE); + break; + case JsonValue: + generator.write((JsonValue) value); + break; + case Null: + generator.write(JsonValue.NULL); + break; + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + final String out = strWriter.toString(); + if (operationFailed(value, out)) { + final String check = toJsonValue(value).toString(); + System.out.println(" Generated simple value " + out + " shall be " + check); + result.fail("write(JsonValue)", + "Generated value " + out + " shall be " + check); + } else { + System.out.println(" Output (simple): " + out); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final Object check, final String out) { + return out == null || !assertEquals(check, out); + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, final String out) { + if (out == null) { + return true; + } + try (final JsonReader reader = Json.createReader(new StringReader(out))) { + final JsonValue actVal = reader.readValue(); + return !assertEquals((JsonValue) check, actVal); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonnumbertests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonnumbertests/ClientTests.java new file mode 100644 index 00000000..6c79b665 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonnumbertests/ClientTests.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonnumbertests; + +import jakarta.json.*; +import jakarta.json.stream.*; + +import java.io.*; + +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.List; +import java.util.Iterator; +import java.util.ArrayList; +import java.math.BigDecimal; +import java.math.BigInteger; + +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonNumberEqualsTest + * + * @assertion_ids: JSONP:JAVADOC:250; + * + * @test_Strategy: Tests JsonNumber equals method. Create 2 equal JsonNumbers + * and compare them for equality and expect true. Create 2 non-equal + * JsonNumbers and compare them for equality and expect false. + */ + @Test + public void jsonNumberEqualsTest() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonNumber 1 for testing"); + JsonNumber number1 = JSONP_Util.createJsonNumber(10); + System.out.println("number1=" + JSONP_Util.toStringJsonNumber(number1)); + + System.out.println("Create sample JsonNumber 2 for testing"); + JsonNumber number2 = JSONP_Util.createJsonNumber(10); + System.out.println("number2=" + JSONP_Util.toStringJsonNumber(number2)); + + System.out.println( + "Call JsonNumber.equals() to compare 2 equal JsonNumbers and expect true"); + if (number1.equals(number2)) { + System.out.println("JsonNumbers are equal - expected."); + } else { + pass = false; + System.err.println("JsonNumbers are not equal - unexpected."); + } + + System.out.println("Create sample JsonNumber 1 for testing"); + number1 = JSONP_Util.createJsonNumber(10); + System.out.println("number1=" + JSONP_Util.toStringJsonNumber(number1)); + + System.out.println("Create sample JsonNumber 2 for testing"); + number2 = JSONP_Util.createJsonNumber((double) 10.25); + System.out.println("number2=" + JSONP_Util.toStringJsonNumber(number2)); + + System.out.println( + "Call JsonNumber.equals() to compare 2 equal JsonNumbers and expect false"); + if (!number1.equals(number2)) { + System.out.println("JsonNumbers are not equal - expected."); + } else { + pass = false; + System.err.println("JsonNumbers are equal - unexpected."); + } + } catch (Exception e) { + throw new Fault("jsonNumberEqualsTest Failed: ", e); + } + if (!pass) + throw new Fault("jsonNumberEqualsTest Failed"); + } + + /* + * @testName: jsonNumberHashCodeTest + * + * @assertion_ids: JSONP:JAVADOC:251; + * + * @test_Strategy: Tests JsonNumber equals method. Create 2 equal JsonNumbers + * and compare them for hashcode and expect true. Create 2 non-equal + * JsonNumbers and compare them for hashcode and expect false. + */ + @Test + public void jsonNumberHashCodeTest() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonNumber 1 for testing"); + JsonNumber number1 = JSONP_Util.createJsonNumber(10); + System.out.println("number1=" + JSONP_Util.toStringJsonNumber(number1)); + System.out.println("number1.hashCode()=" + number1.hashCode()); + + System.out.println("Create sample JsonNumber 2 for testing"); + JsonNumber number2 = JSONP_Util.createJsonNumber(10); + System.out.println("number2=" + JSONP_Util.toStringJsonNumber(number2)); + System.out.println("number2.hashCode()=" + number2.hashCode()); + + System.out.println( + "Call JsonNumber.hashCode() to compare 2 equal JsonNumbers and expect true"); + if (number1.hashCode() == number2.hashCode()) { + System.out.println("JsonNumbers hashCode are equal - expected."); + } else { + pass = false; + System.err.println("JsonNumbers hashCode are not equal - unexpected."); + } + + System.out.println("Create sample JsonNumber 1 for testing"); + number1 = JSONP_Util.createJsonNumber(10); + System.out.println("number1=" + JSONP_Util.toStringJsonNumber(number1)); + System.out.println("number1.hashCode()=" + number1.hashCode()); + + System.out.println("Create sample JsonNumber 2 for testing"); + number2 = JSONP_Util.createJsonNumber((double) 10.25); + System.out.println("number2=" + JSONP_Util.toStringJsonNumber(number2)); + System.out.println("number2.hashCode()=" + number2.hashCode()); + + System.out.println( + "Call JsonNumber.hashCode() to compare 2 equal JsonNumbers and expect false"); + if (number1.hashCode() != number2.hashCode()) { + System.out.println("JsonNumbers hashCode are not equal - expected."); + } else { + pass = false; + System.err.println("JsonNumbers hashCode are equal - unexpected."); + } + } catch (Exception e) { + throw new Fault("jsonNumberHashCodeTest Failed: ", e); + } + if (!pass) + throw new Fault("jsonNumberHashCodeTest Failed"); + } + + /* + * @testName: jsonNumberIsIntegralTest + * + * @assertion_ids: JSONP:JAVADOC:51; + * + * @test_Strategy: Test JsonNumber.isIntegral() method. + */ + @Test + public void jsonNumberIsIntegralTest() throws Fault { + boolean pass = true; + JsonNumber jsonNumber = null; + try { + // INTEGRAL NUMBER TEST + JsonNumber number1 = JSONP_Util.createJsonNumber(123); + if (!JSONP_Util.assertEqualsJsonNumberType(number1.isIntegral(), + JSONP_Util.INTEGRAL)) + pass = false; + else { + if (!JSONP_Util.assertEquals(123, number1.intValue())) + pass = false; + } + // NON_INTEGRAL NUMBER TEST + JsonNumber number2 = JSONP_Util.createJsonNumber(12345.45); + if (!JSONP_Util.assertEqualsJsonNumberType(number2.isIntegral(), + JSONP_Util.NON_INTEGRAL)) + pass = false; + else { + if (!JSONP_Util.assertEquals(12345.45, number2.doubleValue())) + pass = false; + } + + } catch (Exception e) { + throw new Fault("jsonNumberIsIntegralTest Failed: ", e); + } + + if (!pass) + throw new Fault("jsonNumberIsIntegralTest Failed"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonobjecttests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonobjecttests/ClientTests.java new file mode 100644 index 00000000..9ba6ce24 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonobjecttests/ClientTests.java @@ -0,0 +1,1360 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonobjecttests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.json.*; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonObjectTest1 + * + * @assertion_ids: JSONP:JAVADOC:58; JSONP:JAVADOC:61; JSONP:JAVADOC:64; + * JSONP:JAVADOC:67; JSONP:JAVADOC:70; JSONP:JAVADOC:73; JSONP:JAVADOC:76; + * JSONP:JAVADOC:80; JSONP:JAVADOC:86; JSONP:JAVADOC:400; JSONP:JAVADOC:401; + * JSONP:JAVADOC:402; JSONP:JAVADOC:403; JSONP:JAVADOC:404; JSONP:JAVADOC:406; + * JSONP:JAVADOC:408; JSONP:JAVADOC:409; + * + * @test_Strategy: Tests JsonObject/JsonObjectBuilder API's. Build a + * JsonObject using the JsonObjectBuilder API's then verify that the Map of + * JsonObject values matches the expected Map of JsonObject values. + */ + @Test + public void jsonObjectTest1() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject object = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create sample JsonArray for testing"); + JsonArray array = JSONP_Util.createSampleJsonArray(); + + System.out.println("Create the expected map of JsonObject values"); + Map expMap = new HashMap<>(); + expMap.put("false", JsonValue.FALSE); + expMap.put("true", JsonValue.TRUE); + expMap.put("null", JsonValue.NULL); + expMap.put("doublemin", JSONP_Util.createJsonNumber(Double.MIN_VALUE)); + expMap.put("doublemax", JSONP_Util.createJsonNumber(Double.MAX_VALUE)); + expMap.put("intmin", JSONP_Util.createJsonNumber(Integer.MIN_VALUE)); + expMap.put("intmax", JSONP_Util.createJsonNumber(Integer.MAX_VALUE)); + expMap.put("longmin", JSONP_Util.createJsonNumber(Long.MIN_VALUE)); + expMap.put("longmax", JSONP_Util.createJsonNumber(Long.MAX_VALUE)); + expMap.put("bigdecimal", + JSONP_Util.createJsonNumber(BigDecimal.valueOf(123456789.123456789))); + expMap.put("biginteger", + JSONP_Util.createJsonNumber(new BigInteger("123456789"))); + expMap.put("string", JSONP_Util.createJsonString("string1")); + expMap.put("false2", JsonValue.FALSE); + expMap.put("true2", JsonValue.TRUE); + expMap.put("null2", JsonValue.NULL); + expMap.put("object", object); + expMap.put("array", array); + JSONP_Util.dumpMap(expMap, "Expected Map"); + + System.out.println("Create JsonObject using all JsonObjectBuilder API's"); + JsonObject myJsonObject = Json.createObjectBuilder() + .add("false", JsonValue.FALSE).add("true", JsonValue.TRUE) + .add("null", JsonValue.NULL).add("doublemin", Double.MIN_VALUE) + .add("doublemax", Double.MAX_VALUE).add("intmin", Integer.MIN_VALUE) + .add("intmax", Integer.MAX_VALUE).add("longmin", Long.MIN_VALUE) + .add("longmax", Long.MAX_VALUE) + .add("bigdecimal", BigDecimal.valueOf(123456789.123456789)) + .add("biginteger", new BigInteger("123456789")) + .add("string", "string1").add("false2", false).add("true2", true) + .addNull("null2").add("object", object).add("array", array).build(); + + Map actMap = myJsonObject; + JSONP_Util.dumpMap(actMap, "Actual Map"); + System.out.println( + "Compare actual Map of JsonObject values with expected Map of JsonObject values"); + pass = JSONP_Util.assertEqualsMap(expMap, actMap); + } catch (Exception e) { + throw new Fault("jsonObjectTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonObjectTest1 Failed"); + } + + /* + * @testName: jsonObjectTest2 + * + * @assertion_ids: JSONP:JAVADOC:86; JSONP:JAVADOC:58; JSONP:JAVADOC:61; + * JSONP:JAVADOC:64; JSONP:JAVADOC:67; JSONP:JAVADOC:70; JSONP:JAVADOC:73; + * JSONP:JAVADOC:76; JSONP:JAVADOC:80; JSONP:JAVADOC:185; JSONP:JAVADOC:400; + * JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:403; JSONP:JAVADOC:404; + * JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; + * + * @test_Strategy: Tests JsonObject/JsonObjectBuilder API's. Build a + * JsonObject using the JsonObjectBuilder API's. Write the JsonObject to a + * JsonWriter and read it back using a JsonReader. Verify that JsonObject + * written to the JsonWriter and then read back using the JsonReader are + * equal. + */ + @Test + public void jsonObjectTest2() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject object = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create sample JsonArray for testing"); + JsonArray array = JSONP_Util.createSampleJsonArray(); + + System.out.println( + "Create JsonObject 'myJsonObject1' using all JsonObjectBuilder API's"); + JsonObject myJsonObject1 = Json.createObjectBuilder() + .add("false", JsonValue.FALSE).add("true", JsonValue.TRUE) + .add("null", JsonValue.NULL).add("doublemin", Double.MIN_VALUE) + .add("doublemax", Double.MAX_VALUE).add("intmin", Integer.MIN_VALUE) + .add("intmax", Integer.MAX_VALUE).add("longmin", Long.MIN_VALUE) + .add("longmax", Long.MAX_VALUE) + .add("bigdecimal", BigDecimal.valueOf(123456789.123456789)) + .add("biginteger", new BigInteger("123456789")) + .add("string", "string1").add("false2", false).add("true2", true) + .addNull("null2").add("object", object).add("array", array).build(); + + System.out.println("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); + StringWriter sw = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sw)) { + writer.writeObject(myJsonObject1); + System.out.println("Close JsonWriter"); + } + System.out.println("Save contents of the JsonWriter as a String"); + String contents = sw.toString(); + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + contents); + System.out.println( + "Read the JsonObject back into 'myJsonObject2' using a JsonReader"); + JsonObject myJsonObject2; + try (JsonReader reader = Json.createReader(new StringReader(contents))) { + myJsonObject2 = reader.readObject(); + System.out.println("Save contents of the JsonReader as a String"); + contents = reader.toString(); + } + System.out.println("Dump contents of JsonReader as a String"); + System.out.println("JsonReaderContents=" + contents); + + System.out.println("Compare myJsonObject1 and myJsonObject2 for equality"); + pass = JSONP_Util.assertEqualsJsonObjects(myJsonObject1, myJsonObject2); + } catch (Exception e) { + throw new Fault("jsonObjectTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonObjectTest2 Failed"); + } + + /* + * @testName: jsonObjectTest3 + * + * @assertion_ids: JSONP:JAVADOC:58; JSONP:JAVADOC:61; JSONP:JAVADOC:64; + * JSONP:JAVADOC:67; JSONP:JAVADOC:70; JSONP:JAVADOC:73; JSONP:JAVADOC:76; + * JSONP:JAVADOC:80; JSONP:JAVADOC:86; JSONP:JAVADOC:215; JSONP:JAVADOC:101; + * JSONP:JAVADOC:403; JSONP:JAVADOC:264; JSONP:JAVADOC:265; JSONP:JAVADOC:436; + * JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:402; JSONP:JAVADOC:404; + * JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; JSONP:JAVADOC:439; + * JSONP:JAVADOC:441; JSONP:JAVADOC:443; JSONP:JAVADOC:527; JSONP:JAVADOC:529; + * JSONP:JAVADOC:531; JSONP:JAVADOC:533; JSONP:JAVADOC:539; + * + * @test_Strategy: Tests JsonObject/JsonObjectBuilder API's. Build a + * JsonObject using the JsonObjectBuilder API's. Verify contents of JsonObject + * using JsonObject().getJsonArray(String), + * JsonObject().getJsonNumber(String), JsonObject().getJsonObject(String), + * JsonObject().getJsonString(String), JsonObject.getInt(String) and + * JsonObject.getString(String), JsonObject.getBoolean(String), + * JsonObject.getBoolean(String, boolean), JsonObject.getInt(String, int), + * JsonObject.getString(String, String) + */ + @Test + public void jsonObjectTest3() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject object = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create sample JsonArray for testing"); + JsonArray array = JSONP_Util.createSampleJsonArray(); + + System.out.println("Create myObject JsonObject with 22 name/value pairs"); + JsonObject myObject = Json.createObjectBuilder().add("key0", -1) + .add("key1", +1).add("key2", 1).add("key3", -1e3).add("key4", +1e3) + .add("key5", 1e3).add("key6", -2E3).add("key7", +2E3).add("key8", 2E3) + .add("key9", Long.MAX_VALUE).add("key10", Long.MIN_VALUE) + .add("key11", Integer.MAX_VALUE).add("key12", Integer.MIN_VALUE) + .add("key13", Double.MAX_VALUE).add("key14", Double.MIN_VALUE) + .add("key15", BigDecimal.valueOf(123456789.123456789)) + .add("key16", new BigInteger("123456789")) + .add("key17", JsonValue.TRUE).add("key18", JsonValue.FALSE) + .add("key19", JsonValue.NULL).add("key20", JSONP_Data.asciiCharacters) + .add("key21", false).add("key22", true).addNull("key23") + .add("key24", object).add("key25", array).build(); + System.out.println("Checking intValue of key0 for correctness"); + if (!JSONP_Util.assertEquals(-1, + myObject.getJsonNumber("key0").intValue())) + pass = false; + System.out.println("key0 via JsonNumber.toString()=" + + myObject.getJsonNumber("key0").toString()); + System.out.println("Checking intValue of key1 for correctness"); + if (!JSONP_Util.assertEquals(1, myObject.getInt("key1"))) + pass = false; + System.out.println("key1 via JsonNumber.toString()=" + myObject.getInt("key1")); + System.out.println("Checking intValue of key2 for correctness"); + if (!JSONP_Util.assertEquals(1, + myObject.getJsonNumber("key2").intValue())) + pass = false; + System.out.println("key2 via JsonNumber.toString()=" + + myObject.getJsonNumber("key2").toString()); + System.out.println("Checking intValue of key3 for correctness"); + if (!JSONP_Util.assertEquals(-1000, myObject.getInt("key3"))) + pass = false; + System.out.println("key3 via JsonNumber.toString()=" + + myObject.getJsonNumber("key3").toString()); + System.out.println("Checking intValue of key4 for correctness"); + if (!JSONP_Util.assertEquals(1000, + myObject.getJsonNumber("key4").intValue())) + pass = false; + System.out.println("key4 via JsonNumber.toString()=" + + myObject.getJsonNumber("key4").toString()); + System.out.println("Checking intValue of key5 for correctness"); + if (!JSONP_Util.assertEquals(1000, + myObject.getJsonNumber("key5").intValue())) + pass = false; + System.out.println("key5 via JsonNumber.toString()=" + + myObject.getJsonNumber("key5").toString()); + System.out.println("Checking intValue of key6 for correctness"); + if (!JSONP_Util.assertEquals(-2000, + myObject.getJsonNumber("key6").intValue())) + pass = false; + System.out.println("key6 via JsonNumber.toString()=" + + myObject.getJsonNumber("key6").toString()); + System.out.println("Checking intValue of key7 for correctness"); + if (!JSONP_Util.assertEquals(2000, + myObject.getJsonNumber("key7").intValue())) + pass = false; + System.out.println("key7 via JsonNumber.toString()=" + + myObject.getJsonNumber("key7").toString()); + System.out.println("Checking intValue of key8 for correctness"); + if (!JSONP_Util.assertEquals(2000, + myObject.getJsonNumber("key8").intValue())) + pass = false; + System.out.println("key8 via JsonNumber.toString()=" + + myObject.getJsonNumber("key8").toString()); + System.out.println("Checking longValue of key9 for correctness"); + if (!JSONP_Util.assertEquals(Long.MAX_VALUE, + myObject.getJsonNumber("key9").longValue())) + pass = false; + System.out.println("LongMax via JsonNumber.toString()=" + + myObject.getJsonNumber("key9").toString()); + if (!JSONP_Util.assertEquals("" + Long.MAX_VALUE, + myObject.getJsonNumber("key9").toString())) + pass = false; + System.out.println("Checking longValue of key10 for correctness"); + if (!JSONP_Util.assertEquals(Long.MIN_VALUE, + myObject.getJsonNumber("key10").longValue())) + pass = false; + System.out.println("LongMin via JsonNumber.toString()=" + + myObject.getJsonNumber("key10").toString()); + if (!JSONP_Util.assertEquals("" + Long.MIN_VALUE, + myObject.getJsonNumber("key10").toString())) + pass = false; + System.out.println("Checking intValue of key11 for correctness"); + if (!JSONP_Util.assertEquals(Integer.MAX_VALUE, + myObject.getJsonNumber("key11").intValue())) + pass = false; + System.out.println("IntMax via JsonNumber.toString()=" + + myObject.getJsonNumber("key11").toString()); + if (!JSONP_Util.assertEquals("" + Integer.MAX_VALUE, + myObject.getJsonNumber("key11").toString())) + pass = false; + System.out.println("Checking intValue of key12 for correctness"); + if (!JSONP_Util.assertEquals(Integer.MIN_VALUE, + myObject.getJsonNumber("key12").intValue())) + pass = false; + System.out.println("IntMin via JsonNumber.toString()=" + + myObject.getJsonNumber("key12").toString()); + if (!JSONP_Util.assertEquals("" + Integer.MIN_VALUE, + myObject.getJsonNumber("key12").toString())) + pass = false; + System.out.println("Checking doubleValue of key13 for correctness"); + if (!JSONP_Util.assertEquals(Double.MAX_VALUE, + myObject.getJsonNumber("key13").doubleValue())) + pass = false; + System.out.println("Checking doubleValue of key14 for correctness"); + if (!JSONP_Util.assertEquals(Double.MIN_VALUE, + myObject.getJsonNumber("key14").doubleValue())) + pass = false; + System.out.println("Checking bigDecimalValue of key15 for correctness"); + if (!JSONP_Util.assertEquals(BigDecimal.valueOf(123456789.123456789), + myObject.getJsonNumber("key15").bigDecimalValue())) + pass = false; + System.out.println("Checking bigIntegerValue of key16 for correctness"); + if (!JSONP_Util.assertEquals(new BigInteger("123456789"), + myObject.getJsonNumber("key16").bigIntegerValue())) + pass = false; + System.out.println("Checking getBoolean of key17 for correctness"); + if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key17"))) + pass = false; + System.out.println("Checking getBoolean of key18 for correctness"); + if (!JSONP_Util.assertEquals(false, myObject.getBoolean("key18"))) + pass = false; + System.out.println("Checking isNull of key19 for correctness"); + if (!JSONP_Util.assertEquals(true, myObject.isNull("key19"))) + pass = false; + System.out.println("Checking getJsonString of key20 for correctness"); + if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, + myObject.getJsonString("key20").getString())) + pass = false; + System.out.println("Checking getString of key20 for correctness"); + if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, + myObject.getString("key20"))) + pass = false; + System.out.println("Checking getBoolean of key21 for correctness"); + if (!JSONP_Util.assertEquals(false, myObject.getBoolean("key21"))) + pass = false; + System.out.println("Checking getBoolean of key22 for correctness"); + if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key22"))) + pass = false; + System.out.println("Checking isNull of key23 for correctness"); + if (!JSONP_Util.assertEquals(true, myObject.isNull("key23"))) + pass = false; + System.out.println("Checking getJsonObject of key24 for correctness"); + if (!JSONP_Util.assertEqualsJsonObjects(object, + myObject.getJsonObject("key24"))) + pass = false; + System.out.println("Checking getJsonArray of key25 for correctness"); + if (!JSONP_Util.assertEqualsJsonArrays(array, + myObject.getJsonArray("key25"))) + pass = false; + + // Verify calls to JsonObject.getBoolean(int) + if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key17"))) + pass = false; + if (!JSONP_Util.assertEquals(false, myObject.getBoolean("key18"))) + pass = false; + + // Verify calls to JsonObject.getBoolean(String, boolean) + System.out.println( + "Testing JsonObject.getBoolean(String, boolean) with/without default value setting."); + if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key17", false))) + pass = false; + if (!JSONP_Util.assertEquals(false, myObject.getBoolean("key18", true))) + pass = false; + if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key0", true))) + pass = false; + if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key19", true))) + pass = false; + if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key20", true))) + pass = false; + if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key24", true))) + pass = false; + if (!JSONP_Util.assertEquals(true, myObject.getBoolean("key25", true))) + pass = false; + + // Verify calls to JsonObject.getInt(String, int) + System.out.println( + "Testing JsonObject.getInt(String, int) with/without default value setting."); + if (!JSONP_Util.assertEquals(-1, myObject.getInt("key0", 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myObject.getInt("key18", 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myObject.getInt("key19", 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myObject.getInt("key20", 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myObject.getInt("key24", 10))) + pass = false; + if (!JSONP_Util.assertEquals(10, myObject.getInt("key25", 10))) + pass = false; + + // Verify calls to JsonObject.getString(String, String) + System.out.println( + "Testing JsonObject.getString(String, String) with/without default value setting."); + if (!JSONP_Util.assertEquals(JSONP_Data.asciiCharacters, + myObject.getString("key20", "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myObject.getString("key0", "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myObject.getString("key18", "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myObject.getString("key19", "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myObject.getString("key24", "foo"))) + pass = false; + if (!JSONP_Util.assertEquals("foo", myObject.getString("key25", "foo"))) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonObjectTest3 Failed: ", e); + } + if (!pass) + throw new Fault("jsonObjectTest3 Failed"); + } + + /* + * @testName: jsonObjectTest4 + * + * @assertion_ids: JSONP:JAVADOC:61; JSONP:JAVADOC:70; JSONP:JAVADOC:58; + * JSONP:JAVADOC:400; JSONP:JAVADOC:401; JSONP:JAVADOC:403; JSONP:JAVADOC:404; + * JSONP:JAVADOC:406; JSONP:JAVADOC:408; JSONP:JAVADOC:409; JSONP:JAVADOC:438; + * + * @test_Strategy: Build a JsonObject and than write the JsonObject. Compare + * the Json text from the writer contents with the expected Json text output + * expected based on the JsonObject. + */ + @Test + public void jsonObjectTest4() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); + System.out.println("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); + StringWriter sw = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sw)) { + writer.writeObject(myJsonObject1); + System.out.println("Close JsonWriter"); + } + System.out.println("Save contents of the JsonWriter as a String"); + String contents = sw.toString(); + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + contents); + System.out.println("Remove whitespace from contents."); + String actJsonText = JSONP_Util.removeWhitespace(contents); + System.out.println( + "Compare expected JsonObject text with actual JsonObject text for equality"); + pass = JSONP_Util.assertEqualsJsonText( + JSONP_Util.EXPECTED_SAMPLEJSONOBJECT_TEXT, actJsonText); + } catch (Exception e) { + throw new Fault("jsonObjectTest4 Failed: ", e); + } + if (!pass) + throw new Fault("jsonObjectTest4 Failed"); + } + + /* + * @testName: jsonObjectExceptionTests + * + * @assertion_ids: JSONP:JAVADOC:43; JSONP:JAVADOC:47; JSONP:JAVADOC:50; + * JSONP:JAVADOC:344; JSONP:JAVADOC:345; JSONP:JAVADOC:79; JSONP:JAVADOC:437; + * JSONP:JAVADOC:440; JSONP:JAVADOC:442; JSONP:JAVADOC:528; JSONP:JAVADOC:530; + * JSONP:JAVADOC:532; JSONP:JAVADOC:534; JSONP:JAVADOC:540; + * + * @test_Strategy: Test JSON exception conditions. Trips the exceptions: + * java.lang.ArithmeticException java.lang.ClassCastException + * java.lang.NumberFormatException java.lang.UnsupportedOperationException + * java.lang.NullPointerException + */ + @Test + public void jsonObjectExceptionTests() throws Fault { + boolean pass = true; + JsonObject testObject = null; + JsonArray testArray = null; + + try { + System.out.println("Create sample JsonObject for testing"); + testObject = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create sample JsonArray for testing"); + testArray = JSONP_Util.createSampleJsonArray(); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to JsonNumber via getJsonNumber(String)"); + JsonNumber value = testObject.getJsonNumber("address"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to JsonString via getJsonString(String)"); + JsonString value = testObject.getJsonString("address"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to JsonArray via getJsonArray(String)"); + JsonArray value = testObject.getJsonArray("address"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonArray to JsonNumber via getNumber(String)"); + JsonNumber value = testObject.getJsonNumber("phoneNumber"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonArray to JsonString via getJsonString(String)"); + JsonString value = testObject.getJsonString("phoneNumber"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to String via getString(String)"); + String value = testObject.getString("address"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonArray to String via getString(String)"); + String value = testObject.getString("phoneNumber"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonObject to int via getInt(String)"); + int value = testObject.getInt("address"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonArray to int via getInt(String)"); + int value = testObject.getInt("phoneNumber"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonArray to JsonObject via getJsonObject(String)"); + JsonObject value = testObject.getJsonObject("phoneNumber"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonNumber to JsonString via getJsonString(String)"); + JsonString value = testObject.getJsonString("age"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonNumber to JsonObject via getJsonNumber(String)"); + JsonObject value = testObject.getJsonObject("age"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonNumber to JsonArray via getJsonArray(String)"); + JsonArray value = testObject.getJsonArray("age"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonString to JsonNumber via getJsonNumber(String)"); + JsonNumber value = testObject.getJsonNumber("firstName"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonString to int via getInt(String)"); + int value = testObject.getInt("firstName"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonString to JsonObject via getJsonString(String)"); + JsonObject value = testObject.getJsonObject("firstName"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonString to JsonArray via getJsonArray(String)"); + JsonArray value = testObject.getJsonArray("firstName"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonValue.FALSE to JsonNumber via getJsonNumber(String)"); + JsonNumber value = testObject.getJsonNumber("elderly"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonValue.FALSE to JsonString via getJsonString(String)"); + JsonString value = testObject.getJsonString("elderly"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonValue.FALSE to JsonObject via getJsonObject(String)"); + JsonObject value = testObject.getJsonObject("elderly"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a JsonValue.FALSE to JsonArray via getJsonArray(String)"); + JsonArray value = testObject.getJsonArray("elderly"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a non JsonValue.FALSE|JsonValue.TRUE to boolean via getBoolean(String)"); + boolean value = testObject.getBoolean("firstName"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a non JsonValue.FALSE|JsonValue.TRUE to boolean via getBoolean(String)"); + boolean value = testObject.getBoolean("age"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a non JsonValue.FALSE|JsonValue.TRUE to boolean via getBoolean(String)"); + boolean value = testObject.getBoolean("objectOfFooBar"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip ClassCastException + try { + System.out.println( + "Trip ClassCastException trying to cast a non JsonValue.FALSE|JsonValue.TRUE to boolean via getBoolean(String)"); + boolean value = testObject.getBoolean("arrayOfFooBar"); + pass = false; + System.err.println("Failed to throw ClassCastException"); + } catch (ClassCastException e) { + System.out.println("Got expected ClassCastException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Testing NumberFormatException calling add(String, Double.NaN) + try { + System.out.println("Trip NumberFormatException calling add(String, Double.NaN)"); + JsonObject object = Json.createObjectBuilder().add("double", Double.NaN) + .build(); + pass = false; + System.err.println("Failed to throw NumberFormatException"); + } catch (NumberFormatException e) { + System.out.println("Got expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Testing NumberFormatException calling add(String, + // Double.NEGATIVE_INFINITY) + try { + System.out.println( + "Trip NumberFormatException calling add(String, Double.NEGATIVE_INFINITY)"); + JsonObject object = Json.createObjectBuilder() + .add("double", Double.NEGATIVE_INFINITY).build(); + pass = false; + System.err.println("Failed to throw NumberFormatException"); + } catch (NumberFormatException e) { + System.out.println("Got expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Testing NumberFormatException calling add(String, + // Double.POSITIVE_INFINITY) + try { + System.out.println( + "Trip NumberFormatException calling add(String, Double.POSITIVE_INFINITY)"); + JsonObject object = Json.createObjectBuilder() + .add("double", Double.POSITIVE_INFINITY).build(); + pass = false; + System.err.println("Failed to throw NumberFormatException"); + } catch (NumberFormatException e) { + System.out.println("Got expected NumberFormatException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test for ArithmeticException + try { + System.out.println( + "Trip ArithmeticException calling add(\"number\", 12345.12345) and attempting to extract as an exact integer value"); + JsonObject object = Json.createObjectBuilder().add("number", 12345.12345) + .build(); + System.out.println("Call JsonObject.getJsonNumber(\"number\").intValueExact()"); + int value = object.getJsonNumber("number").intValueExact(); + pass = false; + System.err.println("Failed to throw ArithmeticException"); + } catch (ArithmeticException e) { + System.out.println("Got expected ArithmeticException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test for ArithmeticException + try { + System.out.println( + "Trip ArithmeticException calling add(\"number\", 12345.12345) and attempting to extract as an exact long value"); + JsonObject object = Json.createObjectBuilder().add("number", 12345.12345) + .build(); + System.out.println("Call JsonObject.getJsonNumber(\"number\").longValueExact()"); + long value = object.getJsonNumber("number").longValueExact(); + pass = false; + System.err.println("Failed to throw ArithmeticException"); + } catch (ArithmeticException e) { + System.out.println("Got expected ArithmeticException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Test for ArithmeticException + try { + System.out.println( + "Trip ArithmeticException calling add(\"number\", 12345.12345) and attempting to extract as an exact biginteger value"); + JsonObject object = Json.createObjectBuilder().add("number", 12345.12345) + .build(); + System.out.println( + "Call JsonObject.getJsonNumber(\"number\").bigIntegerValueExact()"); + BigInteger value = object.getJsonNumber("number").bigIntegerValueExact(); + pass = false; + System.err.println("Failed to throw ArithmeticException"); + } catch (ArithmeticException e) { + System.out.println("Got expected ArithmeticException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Tests for UnsupportedOperationException using Collection methods to + // modify JsonObject Map + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonObject.put(K,V) trying to modify JsonObject map which should be immutable"); + testObject.put("foo", JsonValue.FALSE); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonObject.putAll(Map) trying to modify JsonObject map which should be immutable"); + testObject.putAll(testObject); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonObject.clear() trying to modify JsonObject map which should be immutable"); + testObject.clear(); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip UnsupportedOperationException + try { + System.out.println( + "Trip UnsupportedOperationException JsonObject.remove(K) trying to modify JsonObject map which should be immutable"); + testObject.remove("firstName"); + pass = false; + System.err.println("Failed to throw UnsupportedOperationException"); + } catch (UnsupportedOperationException e) { + System.out.println("Got expected UnsupportedOperationException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObject.getBoolean(String) when no mapping exists for name."); + boolean value = testObject.getBoolean("foo"); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObject.getInt(String) when no mapping exists for name."); + int value = testObject.getInt("foo"); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObject.getString(String) when no mapping exists for name."); + String value = testObject.getString("foo"); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObject.isNull(String) when no mapping exists for name."); + boolean value = testObject.isNull("foo"); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonObjectExceptionTests Failed"); + } + + /* + * @testName: jsonObjectNullNameValueExceptionTests + * + * @assertion_ids: JSONP:JAVADOC:561; JSONP:JAVADOC:562; JSONP:JAVADOC:563; + * JSONP:JAVADOC:564; JSONP:JAVADOC:565; JSONP:JAVADOC:566; JSONP:JAVADOC:567; + * JSONP:JAVADOC:568; JSONP:JAVADOC:569; JSONP:JAVADOC:570; JSONP:JAVADOC:571; + * + * @test_Strategy: Test JSON NPE exception conditions when attempting to add a + * specified name or value that is null. + */ + @Test + public void jsonObjectNullNameValueExceptionTests() throws Fault { + boolean pass = true; + JsonObjectBuilder job = Json.createObjectBuilder(); + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, JsonValue) when name is null."); + job.add(null, JsonValue.TRUE); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, JsonValue) when value is null."); + job.add("name", (JsonValue) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, String) when name is null."); + job.add(null, "value"); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, String) when value is null."); + job.add("name", (String) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, BigInteger) when name is null."); + job.add(null, new BigInteger("123456789")); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, BigInteger) when value is null."); + job.add("name", (BigInteger) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, BigDecimal) when name is null."); + job.add(null, new BigDecimal("123456789")); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, BigDecimal) when value is null."); + job.add("name", (BigDecimal) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, int) when name is null."); + job.add(null, 123456789); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, long) when name is null."); + job.add(null, 123456789L); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, double) when name is null."); + job.add(null, 123456.789); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObject.add(String, boolean) when name is null."); + job.add(null, true); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObject.addNull(String) when name is null."); + job.addNull(null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, JsonObjectBuilder) when name is null."); + job.add(null, Json.createObjectBuilder()); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonObjectBuilder.add(String, JsonObjectBuilder) when value is null."); + job.add("name", (JsonObjectBuilder) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonArrayBuilder.add(String, JsonArrayBuilder) when name is null."); + job.add(null, Json.createArrayBuilder()); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NullPointerException + try { + System.out.println( + "Trip NullPointerException for JsonArrayBuilder.add(String, JsonArrayBuilder) when value is null."); + job.add("name", (JsonArrayBuilder) null); + pass = false; + System.err.println("Failed to throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonObjectNullNameValueExceptionTests Failed"); + } + + /* + * @testName: jsonCreateObjectBuilder11Test + * + * @assertion_ids: JSONP:JAVADOC:577; JSONP:JAVADOC:578; JSONP:JAVADOC:656; + * JSONP:JAVADOC:657; + * + * @test_Strategy: Tests JsonObjectBuilder API factory methods added in JSON-P + * 1.1. + */ + @Test + public void jsonCreateObjectBuilder11Test() throws Fault { + CreateObjectBuilder createTest = new CreateObjectBuilder(); + final TestResult result = createTest.test(); + result.eval(); + } + + /* + * @testName: jsonObjectBuilder11Test + * + * @assertion_ids: JSONP:JAVADOC:618; JSONP:JAVADOC:619; + * + * @test_Strategy: Tests JsonObjectBuilder API methods added in JSON-P 1.1. + */ + @Test + public void jsonObjectBuilder11Test() throws Fault { + ObjectBuild buildTest = new ObjectBuild(); + final TestResult result = buildTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonobjecttests/CreateObjectBuilder.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonobjecttests/CreateObjectBuilder.java new file mode 100644 index 00000000..f4b370ca --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonobjecttests/CreateObjectBuilder.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonobjecttests; + +import jakarta.jsonp.tck.api.common.TestResult; +import java.util.HashMap; +import java.util.Map; +import jakarta.json.Json; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests: + * {@link JsonObjectBuilder} API factory methods added in JSON-P 1.1.
+ */ +public class CreateObjectBuilder { + + /** + * Test {@link JsonObjectBuilder} factory method added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonObjectBuilder API factory methods added in JSON-P 1.1."); + System.out.println("JsonObjectBuilder API factory methods added in JSON-P 1.1."); + testCreateFromMap(result); + testCreateFromJsonObject(result); + return result; + } + + /** + * Test {@link Json#createObjectBuilder(Map)} method. + * + * @param result + * Test suite result. + */ + private void testCreateFromMap(final TestResult result) { + System.out.println(" - Json#createObjectBuilder(Map)"); + final JsonObject check = createSimpleObjectWithStr(); + Map values = new HashMap<>(2); + values.put(DEF_NAME, DEF_VALUE); + values.put(STR_NAME, STR_VALUE); + final JsonObjectBuilder builder = Json.createObjectBuilder(values); + final JsonObject out = builder.build(); + if (operationFailed(check, out)) { + result.fail("createObjectBuilder(Map)", "Builder output " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Test {@link Json#createObjectBuilder(JsonObject)} method. + * + * @param result + * Test suite result. + */ + private void testCreateFromJsonObject(final TestResult result) { + System.out.println(" - Json#createObjectBuilder(JsonObject)"); + final JsonObject check = createSimpleObjectWithStr(); + final JsonObjectBuilder builder = Json.createObjectBuilder(check); + final JsonObject out = builder.build(); + if (operationFailed(check, out)) { + result.fail("reateObjectBuilder(JsonObject)", "Builder output " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonobjecttests/ObjectBuild.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonobjecttests/ObjectBuild.java new file mode 100644 index 00000000..88f71277 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonobjecttests/ObjectBuild.java @@ -0,0 +1,303 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonobjecttests; + +import jakarta.jsonp.tck.api.common.ObjectBuilder; +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArrayBuilder; +import jakarta.json.JsonObject; +import jakarta.json.JsonObjectBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests for {@link JsonObject} + * and {@link JsonObjectBuilder}. + */ +public class ObjectBuild { + + /** + * {@link JsonArrayBuilder} API remove() methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonObjectBuilder API methods added in JSON-P 1.1."); + System.out.println("JsonObjectBuilder API methods added in JSON-P 1.1."); + testAddString(result); + testAddInt(result); + testAddBool(result); + testAddObject(result); + testAddAllNull(result); + testRemoveString(result); + testRemoveInt(result); + testRemoveBool(result); + testRemoveObject(result); + testRemoveNull(result); + return result; + } + + /** + * Test {@code JsonArrayBuilder addAll(JsonObjectBuilder)} method on + * {@code String} value. + * + * @param result + * Test suite result. + */ + private void testAddString(final TestResult result) { + System.out.println(" - addAll(JsonObjectBuilder) for String"); + final JsonObjectBuilder target = ObjectBuilder + .add(Json.createObjectBuilder(), DEF_NAME, DEF_VALUE); + final JsonObjectBuilder arg = ObjectBuilder.add(Json.createObjectBuilder(), + STR_NAME, STR_VALUE); + final JsonObject check = createSimpleObjectWithStr(); + verifyAddAll(result, check, target, arg); + } + + /** + * Test {@code JsonArrayBuilder addAll(JsonObjectBuilder)} method on + * {@code int} value. + * + * @param result + * Test suite result. + */ + private void testAddInt(final TestResult result) { + System.out.println(" - addAll(JsonObjectBuilder) for int"); + final JsonObjectBuilder target = ObjectBuilder + .add(Json.createObjectBuilder(), DEF_NAME, DEF_VALUE); + final JsonObjectBuilder arg = ObjectBuilder.add(Json.createObjectBuilder(), + INT_NAME, INT_VALUE); + final JsonObject check = createSimpleObjectWithInt(); + verifyAddAll(result, check, target, arg); + } + + /** + * Test {@code JsonArrayBuilder addAll(JsonObjectBuilder)} method on + * {@code boolean} value. + * + * @param result + * Test suite result. + */ + private void testAddBool(final TestResult result) { + System.out.println(" - addAll(JsonObjectBuilder) for boolean"); + final JsonObjectBuilder target = ObjectBuilder + .add(Json.createObjectBuilder(), DEF_NAME, DEF_VALUE); + final JsonObjectBuilder arg = ObjectBuilder.add(Json.createObjectBuilder(), + BOOL_NAME, BOOL_VALUE); + final JsonObject check = createSimpleObjectWithBool(); + verifyAddAll(result, check, target, arg); + } + + /** + * Test {@code JsonArrayBuilder addAll(JsonObjectBuilder)} method on + * {@code JsonObject} value. + * + * @param result + * Test suite result. + */ + private void testAddObject(final TestResult result) { + System.out.println(" - addAll(JsonObjectBuilder) for JsonObject"); + final JsonObjectBuilder target = ObjectBuilder + .add(Json.createObjectBuilder(), DEF_NAME, DEF_VALUE) + .add(DEF_OBJ_NAME, DEF_OBJ_VALUE); + final JsonObjectBuilder arg = ObjectBuilder.add(Json.createObjectBuilder(), + OBJ_NAME, OBJ_VALUE); + final JsonObject check = createCompoundObjectWithObject(); + verifyAddAll(result, check, target, arg); + } + + /** + * Test {@code JsonObjectBuilder addAll(JsonObjectBuilder)} method with + * {@code null} builder argument. + * + * @param result + * Test suite result. + */ + private void testAddAllNull(final TestResult result) { + System.out.println(" - addAll(JsonObjectBuilder) for null builder argument"); + JsonObjectBuilder builder = Json.createObjectBuilder(); + try { + builder.addAll((JsonObjectBuilder) null); + result.fail("addAll(null)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("addAll(null)", + "Calling method with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Test {@code JsonObjectBuilder remove(String)} method on {@code String} + * value. + * + * @param result + * Test suite result. + */ + private void testRemoveString(final TestResult result) { + System.out.println(" - remove(String) for String"); + final JsonObjectBuilder in = ObjectBuilder + .add(Json.createObjectBuilder(), DEF_NAME, DEF_VALUE) + .add(STR_NAME, STR_VALUE); + final JsonObjectBuilder builder = in.remove(STR_NAME); + final JsonObject check = createSimpleObject(); + verifyRemovel(result, check, builder); + } + + /** + * Test {@code JsonObjectBuilder remove(String)} method on {@code int} value. + * + * @param result + * Test suite result. + */ + private void testRemoveInt(final TestResult result) { + System.out.println(" - remove(String) for int"); + final JsonObjectBuilder in = ObjectBuilder + .add(Json.createObjectBuilder(), DEF_NAME, DEF_VALUE) + .add(INT_NAME, INT_VALUE); + final JsonObjectBuilder builder = in.remove(INT_NAME); + final JsonObject check = createSimpleObject(); + verifyRemovel(result, check, builder); + } + + /** + * Test {@code JsonObjectBuilder remove(String)} method on {@code boolean} + * value. + * + * @param result + * Test suite result. + */ + private void testRemoveBool(final TestResult result) { + System.out.println(" - remove(String) for boolean"); + final JsonObjectBuilder in = ObjectBuilder + .add(Json.createObjectBuilder(), DEF_NAME, DEF_VALUE) + .add(BOOL_NAME, BOOL_VALUE); + final JsonObjectBuilder builder = in.remove(BOOL_NAME); + final JsonObject check = createSimpleObject(); + verifyRemovel(result, check, builder); + } + + /** + * Test {@code JsonObjectBuilder remove(String)} method on {@code JsonObject} + * value. + * + * @param result + * Test suite result. + */ + private void testRemoveObject(final TestResult result) { + System.out.println(" - remove(String) for JsonObject"); + final JsonObjectBuilder in = ObjectBuilder + .add(Json.createObjectBuilder(), DEF_NAME, DEF_VALUE) + .add(DEF_OBJ_NAME, DEF_OBJ_VALUE).add(OBJ_NAME, OBJ_VALUE); + final JsonObjectBuilder builder = in.remove(OBJ_NAME); + final JsonObject check = createCompoundObject(); + verifyRemovel(result, check, builder); + } + + /** + * Test {@code JsonObjectBuilder remove(String)} method with {@code null} + * name. + * + * @param result + * Test suite result. + */ + private void testRemoveNull(final TestResult result) { + System.out.println(" - remove(String) for null name argument"); + JsonObjectBuilder builder = Json.createObjectBuilder(); + try { + builder.remove((String) null); + result.fail("remove(null)", + "Calling method with null argument shall throw NullPointerException"); + } catch (NullPointerException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("remove(null)", + "Calling method with null argument shall throw NullPointerException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Test helper: Verify {@code JsonObjectBuilder addAll(JsonObjectBuilder)} + * method on provided builders. + * + * @param result + * Test suite result. + * @param check + * Expected value (used for operation check). + * @param target + * Builder instance used to call {@code addAll(JsonObjectBuilder)} + * method. + * @param arg + * Builder instance passed as an argument. + */ + private void verifyAddAll(final TestResult result, final JsonObject check, + JsonObjectBuilder target, final JsonObjectBuilder arg) { + target.addAll(arg); + final JsonObject out = target.build(); + if (operationFailed(check, out)) { + result.fail("addAll(JsonObjectBuilder)", "Output builder " + + valueToString(out) + " value shall be " + valueToString(check)); + } + } + + /** + * Test helper: Verify {@code JsonObjectBuilder remove(String)} method on + * provided builder. + * + * @param result + * Test suite result. + * @param check + * Expected value (used for operation check). + * @param builder + * Builder instance after {@code JsonObjectBuilder remove(String)} + * method was called. + * @param arg + * Builder instance passed as an argument. + */ + private void verifyRemovel(final TestResult result, final JsonObject check, + JsonObjectBuilder builder) { + final JsonObject out = builder.build(); + if (operationFailed(check, out)) { + result.fail("remove(String)", "Output builder " + valueToString(out) + + " value shall be " + valueToString(check)); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparsereventtests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparsereventtests/ClientTests.java new file mode 100644 index 00000000..2da56f59 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparsereventtests/ClientTests.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonparsereventtests; + +import jakarta.json.stream.*; + +import java.io.*; +import java.util.*; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonValueOfTest + * + * @assertion_ids: JSONP:JAVADOC:128; + * + * @test_Strategy: Test JsonParser.Event.valueOf() API method call with all + * JsonParser.Event types. + * + */ + @Test + public void jsonValueOfTest() throws Fault { + boolean pass = true; + + String eventTypeStrings[] = { "END_ARRAY", "END_OBJECT", "KEY_NAME", + "START_ARRAY", "START_OBJECT", "VALUE_FALSE", "VALUE_NULL", + "VALUE_NUMBER", "VALUE_STRING", "VALUE_TRUE" }; + + for (String eventTypeString : eventTypeStrings) { + JsonParser.Event eventType; + try { + System.out.println( + "Testing enum value for string constant name " + eventTypeString); + eventType = JsonParser.Event.valueOf(eventTypeString); + System.out.println("Got enum type " + eventType + " for enum string constant named " + + eventTypeString); + } catch (Exception e) { + System.err.println("Caught unexpected exception: " + e); + pass = false; + } + + } + + System.out.println("Testing negative test case for NullPointerException"); + try { + JsonParser.Event.valueOf(null); + System.err.println("did not get expected NullPointerException"); + pass = false; + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + System.err.println("Got unexpected exception " + e); + pass = false; + } + + System.out.println("Testing negative test case for IllegalArgumentException"); + try { + JsonParser.Event.valueOf("INVALID"); + System.err.println("did not get expected IllegalArgumentException"); + pass = false; + } catch (IllegalArgumentException e) { + System.out.println("Got expected IllegalArgumentException"); + } catch (Exception e) { + System.err.println("Got unexpected exception " + e); + pass = false; + } + + if (!pass) + throw new Fault("jsonValueOfTest Failed"); + } + + /* + * @testName: jsonValuesTest + * + * @assertion_ids: JSONP:JAVADOC:129; + * + * @test_Strategy: Test JsonParser.Event.values() API method call and verify + * enums returned. + * + */ + @Test + public void jsonValuesTest() throws Fault { + boolean pass = true; + + System.out.println( + "Testing API method JsonParser.Event.values() to return array of enums."); + JsonParser.Event[] values = JsonParser.Event.values(); + + for (JsonParser.Event eventType : values) { + String eventString = JSONP_Util.getEventTypeString(eventType); + if (eventString == null) { + System.err.println("Got no value for enum " + eventType); + pass = false; + } else + System.out.println("Got " + eventString + " for enum " + eventType); + } + + if (!pass) + throw new Fault("jsonValuesTest Failed"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparserfactorytests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparserfactorytests/ClientTests.java new file mode 100644 index 00000000..d8a2b7a5 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparserfactorytests/ClientTests.java @@ -0,0 +1,580 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id: Client.java 66863 2012-07-23 11:26:40Z adf $ + */ +package jakarta.jsonp.tck.api.jsonparserfactorytests; + +import jakarta.json.*; +import jakarta.json.stream.*; +import java.io.*; +import java.nio.charset.Charset; + +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.List; +import java.util.Iterator; +import java.util.Map; +import java.util.ArrayList; + +import jakarta.json.stream.JsonParser.Event.*; +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonParserFactoryTest1 + * + * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:164; + * + * @test_Strategy: Tests the JsonParserFactory API. + * + * JsonParserFactory parserFactory = Json.createParserFactory(Map); + * JsonParser parser1 = parserFactory.createParser(Reader) JsonParser parser2 + * = parserFactory.createParser(Reader) + */ + @Test + public void jsonParserFactoryTest1() throws Fault { + boolean pass = true; + JsonParser parser1 = null; + JsonParser parser2 = null; + JsonParser.Event event = null; + try { + System.out.println("Create JsonParserFactory with a configuration"); + JsonParserFactory parserFactory = Json + .createParserFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = parserFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("--------------------------------------------------"); + System.out.println("TEST CASE [JsonParserFactory.createParser(Reader)]"); + System.out.println("--------------------------------------------------"); + String jsonObjectString = "{\"foo\":\"bar\"}"; + System.out.println("Create 1st JsonParser from the Reader using JsonParserFactory"); + parser1 = parserFactory.createParser(new StringReader(jsonObjectString)); + if (parser1 == null) { + System.err.println("ParserFactory failed to create parser1 from Reader"); + pass = false; + } else { + System.out.println("Parsing " + jsonObjectString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser1, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser1, "foo", "bar"); + JSONP_Util.testEventType(parser1, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + + System.out.println("Create 2nd JsonParser from the Reader using JsonParserFactory"); + parser2 = parserFactory.createParser(new StringReader(jsonObjectString)); + if (parser2 == null) { + System.err.println("ParserFactory failed to create parser2 from Reader"); + pass = false; + } else { + System.out.println("Parsing " + jsonObjectString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser2, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser2, "foo", "bar"); + JSONP_Util.testEventType(parser2, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + + } catch (Exception e) { + throw new Fault("jsonParserFactoryTest1 Failed: ", e); + } finally { + try { + parser1.close(); + parser2.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserFactoryTest1 Failed"); + } + + /* + * @testName: jsonParserFactoryTest2 + * + * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:166; + * + * @test_Strategy: Tests the JsonParserFactory API. + * + * JsonParserFactory parserFactory = Json.createParserFactory(Map); + * JsonParser parser1 = parserFactory.createParser(JsonObject) JsonParser + * parser2 = parserFactory.createParser(JsonObject) + */ + @Test + public void jsonParserFactoryTest2() throws Fault { + boolean pass = true; + JsonParser parser1 = null; + JsonParser parser2 = null; + JsonParser.Event event = null; + try { + System.out.println("Create JsonParserFactory with a configuration"); + JsonParserFactory parserFactory = Json + .createParserFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = parserFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("------------------------------------------------------"); + System.out.println("TEST CASE [JsonParserFactory.createParser(JsonObject)]"); + System.out.println("------------------------------------------------------"); + String jsonObjectString = "{\"foo\":\"bar\"}"; + JsonObject jsonObj = JSONP_Util + .createJsonObjectFromString(jsonObjectString); + System.out.println( + "Create 1st JsonParser from the JsonObject using JsonParserFactory"); + parser1 = parserFactory.createParser(jsonObj); + if (parser1 == null) { + System.err.println("ParserFactory failed to create parser1 from JsonObject"); + pass = false; + } else { + System.out.println("Parsing " + jsonObjectString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser1, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser1, "foo", "bar"); + JSONP_Util.testEventType(parser1, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + + System.out.println( + "Create 2nd JsonParser from the JsonObject using JsonParserFactory"); + parser2 = parserFactory.createParser(jsonObj); + if (parser2 == null) { + System.err.println("ParserFactory failed to create parser2 from JsonObject"); + pass = false; + } else { + System.out.println("Parsing " + jsonObjectString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser2, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser2, "foo", "bar"); + JSONP_Util.testEventType(parser2, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + + } catch (Exception e) { + throw new Fault("jsonParserFactoryTest2 Failed: ", e); + } finally { + try { + parser1.close(); + parser2.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserFactoryTest2 Failed"); + } + + /* + * @testName: jsonParserFactoryTest3 + * + * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:167; + * + * @test_Strategy: Tests the JsonParserFactory API. + * + * JsonParserFactory parserFactory = Json.createParserFactory(Map); + * JsonParser parser1 = parserFactory.createParser(JsonArray) JsonParser + * parser2 = parserFactory.createParser(JsonArray) + */ + @Test + public void jsonParserFactoryTest3() throws Fault { + boolean pass = true; + JsonParser parser1 = null; + JsonParser parser2 = null; + JsonParser.Event event = null; + try { + System.out.println("Create JsonParserFactory with a configuration"); + JsonParserFactory parserFactory = Json + .createParserFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = parserFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("-----------------------------------------------------"); + System.out.println("TEST CASE [JsonParserFactory.createParser(JsonArray)]"); + System.out.println("-----------------------------------------------------"); + String jsonArrayString = "[\"foo\",\"bar\"]"; + JsonArray jsonArr = JSONP_Util.createJsonArrayFromString(jsonArrayString); + System.out.println( + "Create 1st JsonParser from the JsonArray using JsonParserFactory"); + parser1 = parserFactory.createParser(jsonArr); + if (parser1 == null) { + System.err.println("ParserFactory failed to create parser1 from JsonArray"); + pass = false; + } else { + System.out.println("Parsing " + jsonArrayString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser1, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser1, "foo"); + JSONP_Util.testStringValue(parser1, "bar"); + JSONP_Util.testEventType(parser1, JsonParser.Event.END_ARRAY); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + + System.out.println( + "Create 2nd JsonParser from the JsonArray using JsonParserFactory"); + parser2 = parserFactory.createParser(jsonArr); + if (parser2 == null) { + System.err.println("ParserFactory failed to create parser2 from JsonArray"); + pass = false; + } else { + System.out.println("Parsing " + jsonArrayString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser2, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser2, "foo"); + JSONP_Util.testStringValue(parser2, "bar"); + JSONP_Util.testEventType(parser2, JsonParser.Event.END_ARRAY); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + } catch (Exception e) { + throw new Fault("jsonParserFactoryTest3 Failed: ", e); + } finally { + try { + parser1.close(); + parser2.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserFactoryTest3 Failed"); + } + + /* + * @testName: jsonParserFactoryTest4 + * + * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:165; + * + * @test_Strategy: Tests the JsonParserFactory API. + * + * JsonParserFactory parserFactory = Json.createParserFactory(Map); + * JsonParser parser1 = parserFactory.createParser(InputStream) JsonParser + * parser2 = parserFactory.createParser(InputStream) + */ + @Test + public void jsonParserFactoryTest4() throws Fault { + boolean pass = true; + JsonParser parser1 = null; + JsonParser parser2 = null; + JsonParser.Event event = null; + try { + System.out.println("Create JsonParserFactory with a configuration"); + JsonParserFactory parserFactory = Json + .createParserFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = parserFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("-------------------------------------------------------"); + System.out.println("TEST CASE [JsonParserFactory.createParser(InputStream)]"); + System.out.println("-------------------------------------------------------"); + String jsonObjectString = "{\"foo\":\"bar\"}"; + System.out.println( + "Create 1st JsonParser from the InputStream using JsonParserFactory"); + parser1 = parserFactory.createParser(new ByteArrayInputStream( + jsonObjectString.getBytes(JSONP_Util.UTF_8))); + if (parser1 == null) { + System.err.println("ParserFactory failed to create parser1 from InputStream"); + pass = false; + } else { + System.out.println("Parsing " + jsonObjectString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser1, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser1, "foo", "bar"); + JSONP_Util.testEventType(parser1, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + + System.out.println( + "Create 2nd JsonParser from the InputStream using JsonParserFactory"); + parser2 = parserFactory.createParser(new ByteArrayInputStream( + jsonObjectString.getBytes(JSONP_Util.UTF_8))); + if (parser2 == null) { + System.err.println("ParserFactory failed to create parser2 from InputStream"); + pass = false; + } else { + System.out.println("Parsing " + jsonObjectString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser2, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser2, "foo", "bar"); + JSONP_Util.testEventType(parser2, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + + } catch (Exception e) { + throw new Fault("jsonParserFactoryTest4 Failed: ", e); + } finally { + try { + parser1.close(); + parser2.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserFactoryTest4 Failed"); + } + + /* + * @testName: jsonParserFactoryTest5 + * + * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:201; + * + * @test_Strategy: Tests the JsonParserFactory API. + * + * JsonParserFactory parserFactory = Json.createParserFactory(Map); + * JsonParser parser1 = parserFactory.createParser(InputStream, Charset) + * JsonParser parser2 = parserFactory.createParser(InputStream, Charset) + */ + @Test + public void jsonParserFactoryTest5() throws Fault { + boolean pass = true; + JsonParser parser1 = null; + JsonParser parser2 = null; + JsonParser.Event event = null; + try { + System.out.println("Create JsonParserFactory with a configuration"); + JsonParserFactory parserFactory = Json + .createParserFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = parserFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println( + "----------------------------------------------------------------"); + System.out.println( + "TEST CASE [JsonParserFactory.createParser(InputStream, Charset)]"); + System.out.println( + "----------------------------------------------------------------"); + String jsonObjectString = "{\"foo\":\"bar\"}"; + System.out.println( + "Create 1st JsonParser from the InputStream using JsonParserFactory"); + parser1 = parserFactory.createParser( + new ByteArrayInputStream(jsonObjectString.getBytes(JSONP_Util.UTF_8)), + JSONP_Util.UTF_8); + if (parser1 == null) { + System.err.println("ParserFactory failed to create parser1 from InputStream"); + pass = false; + } else { + System.out.println("Parsing " + jsonObjectString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser1, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser1, "foo", "bar"); + JSONP_Util.testEventType(parser1, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + + System.out.println( + "Create 2nd JsonParser from the InputStream using JsonParserFactory"); + parser2 = parserFactory.createParser( + new ByteArrayInputStream(jsonObjectString.getBytes(JSONP_Util.UTF_8)), + JSONP_Util.UTF_8); + if (parser2 == null) { + System.err.println("ParserFactory failed to create parser2 from InputStream"); + pass = false; + } else { + System.out.println("Parsing " + jsonObjectString); + System.out.println("Verify that JSON Parser Events/Data matches"); + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser2, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser2, "foo", "bar"); + JSONP_Util.testEventType(parser2, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } + + } catch (Exception e) { + throw new Fault("jsonParserFactoryTest5 Failed: ", e); + } finally { + try { + parser1.close(); + parser2.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserFactoryTest5 Failed"); + } + + /* + * @testName: jsonParserFactoryTest6 + * + * @assertion_ids: JSONP:JAVADOC:417; JSONP:JAVADOC:164; JSONP:JAVADOC:428; + * + * @test_Strategy: Tests the JsonParserFactory API. + * + * JsonParserFactory parserFactory = Json.createParserFactory(Map); + * Map config = JsonParserFactory.getConfigInUse(); + * + * Test for the following 2 scenarios: 1) no supported provider property + * (empty config) 2) non supported provider property + */ + @Test + public void jsonParserFactoryTest6() throws Fault { + boolean pass = true; + JsonParserFactory parserFactory; + Map config; + try { + System.out.println("----------------------------------------------"); + System.out.println("Test scenario1: no supported provider property"); + System.out.println("----------------------------------------------"); + System.out.println("Create JsonParserFactory with Map with EMPTY config"); + parserFactory = Json.createParserFactory(JSONP_Util.getEmptyConfig()); + config = parserFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("-----------------------------------------------"); + System.out.println("Test scenario2: non supported provider property"); + System.out.println("-----------------------------------------------"); + System.out.println("Create JsonParserFactory with Map with FOO config"); + parserFactory = Json.createParserFactory(JSONP_Util.getFooConfig()); + config = parserFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonParserFactoryTest6 Failed: ", e); + } + if (!pass) + throw new Fault("jsonParserFactoryTest6 Failed"); + } + + /* + * @testName: jsonParserFactoryExceptionTest + * + * @assertion_ids: JSONP:JAVADOC:225; + * + * @test_Strategy: Test JsonParserFactory exception conditions. Trip the + * following exception due to unknown encoding or i/o error: + * + * jakarta.json.JsonException + */ + @Test + public void jsonParserFactoryExceptionTest() throws Fault { + boolean pass = true; + + // Tests JsonParserFactory.createParser(InputStream) for JsonException if + // i/o error + try { + System.out.println( + "Tests JsonParserFactory.createParser(InputStream) for JsonException if i/o error."); + JsonParserFactory parserFactory = Json + .createParserFactory(JSONP_Util.getEmptyConfig()); + MyBufferedInputStream mbi = new MyBufferedInputStream( + JSONP_Util.getInputStreamFromString("{}"), true); + JsonParser parser = parserFactory.createParser(mbi); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Tests JsonParserFactory.createParser(InputStream) for JsonException if + // unknown encoding + try { + System.out.println( + "Tests JsonParserFactory.createParser(InputStream) for JsonException if unknown encoding."); + JsonParserFactory parserFactory = Json + .createParserFactory(JSONP_Util.getEmptyConfig()); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectUnknownEncoding.json"); + JsonParser parser = parserFactory.createParser(is); + System.out.println("parser=" + parser); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonParserFactoryExceptionTest Failed"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparsertests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparsertests/ClientTests.java new file mode 100644 index 00000000..c1a3f0e5 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparsertests/ClientTests.java @@ -0,0 +1,1908 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonparsertests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +import java.io.*; +import java.math.BigDecimal; +import java.util.NoSuchElementException; +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.json.*; +import jakarta.json.stream.*; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* + * Utitity method to parse various JsonObjectUTF encoded files + */ + private boolean parseAndVerify_JsonObjectUTF(JsonParser parser) + throws Exception { + boolean pass = true; + + try { + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser, "stringName", "stringValue"); + JSONP_Util.testKeyStartObjectValue(parser, "objectName"); + JSONP_Util.testKeyStringValue(parser, "foo", "bar"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testKeyStartArrayValue(parser, "arrayName"); + JSONP_Util.testIntegerValue(parser, 1); + JSONP_Util.testIntegerValue(parser, 2); + JSONP_Util.testIntegerValue(parser, 3); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } catch (Exception e) { + throw e; + } + return pass; + } + + /* + * Utitity method to parse JsonObjectWithAllTypesOfData + */ + private boolean parseAndVerify_JsonObjectWithAllTypesOfData(JsonParser parser) + throws Exception { + boolean pass = true; + + try { + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser, "emptyString", ""); + JSONP_Util.testKeyStartArrayValue(parser, "emptyArray"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testKeyStartObjectValue(parser, "emptyObject"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testKeyStringValue(parser, "string", "string"); + JSONP_Util.testKeyIntegerValue(parser, "number", 100); + JSONP_Util.testKeyTrueValue(parser, "true"); + JSONP_Util.testKeyFalseValue(parser, "false"); + JSONP_Util.testKeyNullValue(parser, "null"); + JSONP_Util.testKeyStartObjectValue(parser, "object"); + JSONP_Util.testKeyStringValue(parser, "emptyString", ""); + JSONP_Util.testKeyStartArrayValue(parser, "emptyArray"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testKeyStartObjectValue(parser, "emptyObject"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testKeyStringValue(parser, "string", "string"); + JSONP_Util.testKeyIntegerValue(parser, "number", 100); + JSONP_Util.testKeyTrueValue(parser, "true"); + JSONP_Util.testKeyFalseValue(parser, "false"); + JSONP_Util.testKeyNullValue(parser, "null"); + JSONP_Util.testKeyStartObjectValue(parser, "object"); + JSONP_Util.testKeyStringValue(parser, "name", "value"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testKeyStartArrayValue(parser, "array"); + JSONP_Util.testStringValue(parser, "one"); + JSONP_Util.testStringValue(parser, "two"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testKeyStartArrayValue(parser, "array"); + JSONP_Util.testStringValue(parser, "string"); + JSONP_Util.testIntegerValue(parser, 100); + JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); + JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); + JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser, "name", "value"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser, "one"); + JSONP_Util.testStringValue(parser, "two"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testKeyIntegerValue(parser, "intPositive", 100); + JSONP_Util.testKeyIntegerValue(parser, "intNegative", -100); + JSONP_Util.testKeyLongValue(parser, "longMax", 9223372036854775807L); + JSONP_Util.testKeyLongValue(parser, "longMin", -9223372036854775808L); + JSONP_Util.testKeyDoubleValue(parser, "fracPositive", (double) 0.5); + JSONP_Util.testKeyDoubleValue(parser, "fracNegative", (double) -0.5); + JSONP_Util.testKeyDoubleValue(parser, "expPositive1", (double) 7e3); + JSONP_Util.testKeyDoubleValue(parser, "expPositive2", (double) 7e+3); + JSONP_Util.testKeyDoubleValue(parser, "expPositive3", (double) 9E3); + JSONP_Util.testKeyDoubleValue(parser, "expPositive4", (double) 9E+3); + JSONP_Util.testKeyDoubleValue(parser, "expNegative1", (double) 7e-3); + JSONP_Util.testKeyDoubleValue(parser, "expNegative2", (double) 7E-3); + JSONP_Util.testKeyStringValue(parser, "asciiChars", + JSONP_Data.asciiCharacters); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } catch (Exception e) { + throw e; + } + return pass; + } + + /* + * Utitity method to parse JsonObjectWithLotsOfNestedObjectsData + */ + private boolean parseAndVerify_JsonObjectWithLotsOfNestedObjectsData( + JsonParser parser) throws Exception { + boolean pass = true; + + try { + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + for (int i = 1; i < 31; i++) { + JSONP_Util.testKeyStartObjectValue(parser, "nested" + i); + JSONP_Util.testKeyStringValue(parser, "name" + i, "value" + i); + } + for (int i = 1; i < 31; i++) { + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + } + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } catch (Exception e) { + throw e; + } + return pass; + } + + /* + * Utitity method to parse JsonArrayWithLotsOfNestedObjectsData + */ + private boolean parseAndVerify_JsonArrayWithLotsOfNestedObjectsData( + JsonParser parser) throws Exception { + boolean pass = true; + + try { + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser, "name1", "value1"); + for (int i = 2; i < 31; i++) { + JSONP_Util.testKeyStartObjectValue(parser, "nested" + i); + JSONP_Util.testKeyStringValue(parser, "name" + i, "value" + i); + } + for (int i = 2; i < 31; i++) { + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + } + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } catch (Exception e) { + throw e; + } + return pass; + } + + /* + * Utitity method to parse JsonArrayWithLotsOfNestedArraysData + */ + private boolean parseAndVerify_JsonArrayWithLotsOfNestedArraysData( + JsonParser parser) throws Exception { + boolean pass = true; + + try { + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser, "name1"); + JSONP_Util.testStringValue(parser, "value1"); + for (int i = 2; i < 31; i++) { + JSONP_Util.testStringValue(parser, "nested" + i); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser, "name" + i); + JSONP_Util.testStringValue(parser, "value" + i); + } + for (int i = 2; i < 31; i++) { + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + } + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } catch (Exception e) { + throw e; + } + return pass; + } + + /* + * Utitity method to parse JsonArrayWithMultipleArraysData + */ + private boolean parseAndVerify_JsonArrayWithMultipleArraysData( + JsonParser parser) throws Exception { + boolean pass = true; + + try { + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser, "string"); + JSONP_Util.testIntegerValue(parser, 100); + JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); + JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); + JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser, "object", "object"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser, "one"); + JSONP_Util.testStringValue(parser, "two"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testIntegerValue(parser, 100); + JSONP_Util.testDoubleValue(parser, (double) 7e7); + JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); + JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); + JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser, "object2", "object2"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } catch (Exception e) { + throw e; + } + return pass; + } + + /* + * Utitity method to parse JsonArrayWithAllTypesOfData + */ + private boolean parseAndVerify_JsonArrayWithAllTypesOfData(JsonParser parser) + throws Exception { + boolean pass = true; + + try { + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser, ""); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testStringValue(parser, "string"); + JSONP_Util.testIntegerValue(parser, 100); + JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); + JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); + JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser, "emptyString", ""); + JSONP_Util.testKeyStartArrayValue(parser, "emptyArray"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testKeyStartObjectValue(parser, "emptyObject"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testKeyStringValue(parser, "string", "string"); + JSONP_Util.testKeyIntegerValue(parser, "number", 100); + JSONP_Util.testKeyTrueValue(parser, "true"); + JSONP_Util.testKeyFalseValue(parser, "false"); + JSONP_Util.testKeyNullValue(parser, "null"); + JSONP_Util.testKeyStartObjectValue(parser, "object"); + JSONP_Util.testKeyStringValue(parser, "name", "value"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testKeyStartArrayValue(parser, "array"); + JSONP_Util.testStringValue(parser, "one"); + JSONP_Util.testStringValue(parser, "two"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser, "string"); + JSONP_Util.testIntegerValue(parser, 100); + JSONP_Util.testTrueValue(parser, JsonParser.Event.VALUE_TRUE); + JSONP_Util.testFalseValue(parser, JsonParser.Event.VALUE_FALSE); + JSONP_Util.testNullValue(parser, JsonParser.Event.VALUE_NULL); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStringValue(parser, "name", "value"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.testEventType(parser, JsonParser.Event.START_ARRAY); + JSONP_Util.testStringValue(parser, "one"); + JSONP_Util.testStringValue(parser, "two"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.testIntegerValue(parser, 100); + JSONP_Util.testIntegerValue(parser, -100); + JSONP_Util.testLongValue(parser, 9223372036854775807L); + JSONP_Util.testLongValue(parser, -9223372036854775808L); + JSONP_Util.testDoubleValue(parser, (double) 0.5); + JSONP_Util.testDoubleValue(parser, (double) -0.5); + JSONP_Util.testDoubleValue(parser, (double) 7e3); + JSONP_Util.testDoubleValue(parser, (double) 7e+3); + JSONP_Util.testDoubleValue(parser, (double) 9E3); + JSONP_Util.testDoubleValue(parser, (double) 9E+3); + JSONP_Util.testDoubleValue(parser, (double) 7e-3); + JSONP_Util.testDoubleValue(parser, (double) 7E-3); + JSONP_Util.testStringValue(parser, JSONP_Data.asciiCharacters); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } catch (Exception e) { + throw e; + } + return pass; + } + + private boolean parseAndVerify_JsonHelloWorld(JsonParser parser) + throws Exception { + boolean pass = true; + + try { + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyStartObjectValue(parser, "greetingObj"); + JSONP_Util.dumpLocation(parser); + JSONP_Util.testKeyStringValue(parser, "hello", "world"); + JSONP_Util.dumpLocation(parser); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.dumpLocation(parser); + JSONP_Util.testKeyStartArrayValue(parser, "greetingArr"); + JSONP_Util.dumpLocation(parser); + JSONP_Util.testStringValue(parser, "hello"); + JSONP_Util.dumpLocation(parser); + JSONP_Util.testStringValue(parser, "world"); + JSONP_Util.dumpLocation(parser); + JSONP_Util.testEventType(parser, JsonParser.Event.END_ARRAY); + JSONP_Util.dumpLocation(parser); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + JSONP_Util.dumpLocation(parser); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + } catch (Exception e) { + throw e; + } + return pass; + } + + /* Tests */ + + /* + * @testName: jsonParserTest1 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; + * JSONP:JAVADOC:133; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonObject defined in "JSONP_Data.jsonObjectWithAllTypesOfData". Creates + * the JsonParser via the API: + * + * JsonParser parser = Json.createParser(Reader) + */ + @Test + public void jsonParserTest1() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println("-------------------------------------"); + System.out.println("TEST CASE [Json.createParser(Reader)]"); + System.out.println("-------------------------------------"); + System.out.println("Create Reader from (JSONP_Data.jsonObjectWithAllTypesOfData)"); + StringReader reader = new StringReader( + JSONP_Data.jsonObjectWithAllTypesOfData); + System.out.println("Create JsonParser from the Reader"); + parser = Json.createParser(reader); + System.out.println( + "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithAllTypesOfData)"); + pass = parseAndVerify_JsonObjectWithAllTypesOfData(parser); + } catch (Exception e) { + throw new Fault("jsonParserTest1 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest1 Failed"); + } + + /* + * @testName: jsonParserTest2 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; + * JSONP:JAVADOC:417; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:166; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonObject defined in "JSONP_Data.jsonObjectWithAllTypesOfData". Creates + * the JsonParser via the API: + * + * JsonParser parser = + * Json.createParserFactory(Map).createParser(JsonObject) + */ + @Test + public void jsonParserTest2() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "----------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(JsonObject)]"); + System.out.println( + "----------------------------------------------------------------------------"); + System.out.println( + "Create JsonObject from (JSONP_Data.jsonObjectWithAllTypesOfData)"); + JsonObject jsonObj = JSONP_Util + .createJsonObjectFromString(JSONP_Data.jsonObjectWithAllTypesOfData); + JSONP_Util.dumpJsonObject(jsonObj); + System.out.println("Create JsonParser from the JsonObject"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(jsonObj); + System.out.println("parser=" + parser); + System.out.println( + "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithAllTypesOfData)"); + pass = parseAndVerify_JsonObjectWithAllTypesOfData(parser); + } catch (Exception e) { + throw new Fault("jsonParserTest2 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest2 Failed"); + } + + /* + * @testName: jsonParserTest3 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:133; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonObject defined in "JSONP_Data.jsonObjectWithLotsOfNestedObjectsData". + * Creates the JsonParser via the API: + * + * JsonParser parser = Json.createParser(Reader) + */ + @Test + public void jsonParserTest3() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println("-------------------------------------------"); + System.out.println("TEST CASE [Json.createParser(Reader) again]"); + System.out.println("-------------------------------------------"); + System.out.println( + "Create Reader from (JSONP_Data.jsonObjectWithLotsOfNestedObjectsData)"); + StringReader reader = new StringReader( + JSONP_Data.jsonObjectWithLotsOfNestedObjectsData); + System.out.println("Create JsonParser from the Reader"); + parser = Json.createParser(reader); + System.out.println( + "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithLotsOfNestedObjectsData)"); + pass = parseAndVerify_JsonObjectWithLotsOfNestedObjectsData(parser); + } catch (Exception e) { + throw new Fault("jsonParserTest3 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest3 Failed"); + } + + /* + * @testName: jsonParserTest4 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:166; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonObject defined in "JSONP_Data.jsonObjectithLotsOfNestedObjectsData". + * Creates the JsonParser via the API: + * + * JsonParser parser = + * Json.createParserFactory(Map).createParser(JsonObject) + */ + @Test + public void jsonParserTest4() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "-----------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(JsonObject object) again]"); + System.out.println( + "-----------------------------------------------------------------------------------------"); + System.out.println( + "Create JsonObject from (JSONP_Data.jsonObjectWithLotsOfNestedObjectsData)"); + JsonObject jsonObj = JSONP_Util.createJsonObjectFromString( + JSONP_Data.jsonObjectWithLotsOfNestedObjectsData); + JSONP_Util.dumpJsonObject(jsonObj); + System.out.println("Create JsonParser from the JsonObject"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(jsonObj); + System.out.println( + "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithLotsOfNestedObjectsData)"); + pass = parseAndVerify_JsonObjectWithLotsOfNestedObjectsData(parser); + } catch (Exception e) { + throw new Fault("jsonParserTest4 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest4 Failed"); + } + + /* + * @testName: jsonParserTest5 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; + * JSONP:JAVADOC:417; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:167; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonArray defined in "JSONP_Data.jsonArrayWithMultipleArraysData". Creates + * the JsonParser via the API: + * + * JsonParser parser = + * Json.createParserFactory(Map).createParser(JsonArray) + */ + @Test + public void jsonParserTest5() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "---------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(JsonArray)]"); + System.out.println( + "---------------------------------------------------------------------------"); + System.out.println( + "Create JsonArray from (JSONP_Data.jsonArrayWithMultipleArraysData)"); + JsonArray jsonArr = JSONP_Util.createJsonArrayFromString( + JSONP_Data.jsonArrayWithMultipleArraysData); + JSONP_Util.dumpJsonArray(jsonArr); + System.out.println("Create JsonParser from the JsonArray"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(jsonArr); + System.out.println( + "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonArrayWithMultipleArraysData)"); + pass = parseAndVerify_JsonArrayWithMultipleArraysData(parser); + } catch (Exception e) { + throw new Fault("jsonParserTest5 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest5 Failed"); + } + + /* + * @testName: jsonParserTest6 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; + * JSONP:JAVADOC:172; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonArray defined in resource file "jsonArrayWithAllTypesOfData.json". + * + * Creates the JsonParser via the API: + * + * JsonParser parser = Json.createParser(InputStream) + */ + @Test + public void jsonParserTest6() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println("------------------------------------------"); + System.out.println("TEST CASE [Json.createParser(InputStream)]"); + System.out.println("------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonArrayWithAllTypesOfData.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonArrayWithAllTypesOfData.json"); + System.out.println("Create JsonParser from the InputStream"); + parser = Json.createParser(istream); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonArrayWithAllTypesOfData.json)"); + pass = parseAndVerify_JsonArrayWithAllTypesOfData(parser); + } catch (Exception e) { + throw new Fault("jsonParserTest6 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest6 Failed"); + } + + /* + * @testName: jsonParserTest7 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; + * JSONP:JAVADOC:417; JSONP:JAVADOC:164; JSONP:JAVADOC:235; JSONP:JAVADOC:237; + * JSONP:JAVADOC:239; JSONP:JAVADOC:375; JSONP:JAVADOC:376; + * + * @test_Strategy: Tests the JsonParser parser with a configuration. Verifies + * PARSING of the JsonObject defined in + * "JSONP_Data.jsonObjectWithAllTypesOfData". Creates the JsonParser via the + * following API + * + * JsonParser parser = Json.createParserFactory(Map).createParser(Reader) + */ + @Test + public void jsonParserTest7() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "-------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(Reader)]"); + System.out.println( + "-------------------------------------------------------------------------"); + System.out.println("Create a Reader from (JSONP_Data.jsonObjectWithAllTypesOfData)"); + StringReader reader = new StringReader( + JSONP_Data.jsonObjectWithAllTypesOfData); + System.out.println("Create JsonParser using Reader and a configuration"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(reader); + System.out.println("Call JsonParser.toString() to print the JsonObject"); + parser.toString(); + System.out.println( + "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonObjectWithAllTypesOfData)"); + if (!parseAndVerify_JsonObjectWithAllTypesOfData(parser)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonParserTest7 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest7 Failed"); + } + + /* + * @testName: jsonParserTest8 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; + * JSONP:JAVADOC:167; JSONP:JAVADOC:375; JSONP:JAVADOC:376; + * + * @test_Strategy: Tests the JsonParser parser with a configuration. Verifies + * PARSING of the JsonArray defined in + * "JSONP_Data.jsonArrayWithLotsOfNestedObjectsData". Creates the JsonParser + * via the following API + * + * JsonParser parser = Json.createParserFactory(Map).createParser(JsonArray) + */ + @Test + public void jsonParserTest8() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "----------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(JsonArray)]"); + System.out.println( + "----------------------------------------------------------------------------"); + System.out.println( + "Create a JsonArray from (JSONP_Data.jsonArrayWithLotsOfNestedObjectsData)"); + JsonArray jsonArr = JSONP_Util.createJsonArrayFromString( + JSONP_Data.jsonArrayWithLotsOfNestedObjectsData); + JSONP_Util.dumpJsonArray(jsonArr); + System.out.println("Create JsonParser using JsonArray and a configuration"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(jsonArr); + System.out.println("Call JsonParser.toString() to print the JsonObject"); + parser.toString(); + System.out.println( + "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonArrayWithLotsOfNestedObjectsData)"); + if (!parseAndVerify_JsonArrayWithLotsOfNestedObjectsData(parser)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonParserTest8 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest8 Failed"); + } + + /* + * @testName: jsonParserTest9 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; + * JSONP:JAVADOC:417; JSONP:JAVADOC:167; JSONP:JAVADOC:235; JSONP:JAVADOC:237; + * JSONP:JAVADOC:239; JSONP:JAVADOC:375; JSONP:JAVADOC:376; + * + * @test_Strategy: Tests the JsonParser parser with an empty configuration. + * Verifies PARSING of the JsonArray defined in + * "JSONP_Data.jsonArrayWithMultipleArraysData". Creates the JsonParser via + * the following API + * + * JsonParser parser = Json.createParserFactory(Map).createParser(JsonArray) + */ + @Test + public void jsonParserTest9() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "----------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(JsonArray)]"); + System.out.println( + "----------------------------------------------------------------------------"); + System.out.println( + "Create JsonArray from (JSONP_Data.jsonArrayWithMultipleArraysData)"); + JsonArray jsonArr = JSONP_Util.createJsonArrayFromString( + JSONP_Data.jsonArrayWithMultipleArraysData); + JSONP_Util.dumpJsonArray(jsonArr); + System.out.println("Create JsonParser using JsonArray and a configuration"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(jsonArr); + System.out.println("Call JsonParser.toString() to print the JsonArray"); + parser.toString(); + System.out.println( + "Verify that JSON Parser Events/Data matches (JSONP_Data.jsonArrayWithMultipleArraysData)"); + if (!parseAndVerify_JsonArrayWithMultipleArraysData(parser)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonParserTest9 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest9 Failed"); + } + + /* + * @testName: jsonParserTest10 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; + * JSONP:JAVADOC:165; JSONP:JAVADOC:375; JSONP:JAVADOC:376; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonObject defined in resource file + * "jsonObjectWithLotsOfNestedObjectsData.json". Creates the JsonParser via + * the following API + * + * JsonParser parser = Json.createParserFactory(Map).createParser(InputStream) + */ + @Test + public void jsonParserTest10() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream)]"); + System.out.println( + "------------------------------------------------------------------------------"); + System.out.println("Create JsonParser using InputStream and a configuration"); + InputStream istream = JSONP_Util.getInputStreamFromResource( + "jsonObjectWithLotsOfNestedObjectsData.json"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream); + System.out.println("Call JsonParser.toString() to print the JsonObject"); + parser.toString(); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectWithLotsOfNestedObjectsData.json)"); + if (!parseAndVerify_JsonObjectWithLotsOfNestedObjectsData(parser)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonParserTest10 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest10 Failed"); + } + + /* + * @testName: jsonParserTest11 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; + * JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; JSONP:JAVADOC:375; + * JSONP:JAVADOC:376; JSONP:JAVADOC:417; JSONP:JAVADOC:201; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonArray defined in resource file + * "jsonArrayWithAllTypesOfDataUTF16BE.json". Use UTF-16BE encoding. + * + * Creates the JsonParser via the API: + * + * JsonParser parser = + * Json.createParserFactory(Map).createParser(InputStream, Charset) + */ + @Test + public void jsonParserTest11() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "--------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset)]"); + System.out.println( + "--------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonArrayWithAllTypesOfDataUTF16BE.json)"); + InputStream istream = JSONP_Util.getInputStreamFromResource( + "jsonArrayWithAllTypesOfDataUTF16BE.json"); + System.out.println( + "Create JsonParser from the InputStream with character encoding UTF-16BE"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream, JSONP_Util.UTF_16BE); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonArrayWithAllTypesOfDataUTF16BE.json)"); + pass = parseAndVerify_JsonArrayWithAllTypesOfData(parser); + } catch (Exception e) { + throw new Fault("jsonParserTest11 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest11 Failed"); + } + + /* + * @testName: jsonParserTest12 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:201; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonArray defined in resource file + * "jsonArrayWithLotsOfNestedArraysData.json". Use UTF-8 encoding. + * + * Creates the JsonParser via the API: + * + * JsonParser parser = Json.createParserFactory(Map).createParser(InputStream, Charset) + */ + @Test + public void jsonParserTest12() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "---------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset)]"); + System.out.println( + "---------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonArrayWithLotsOfNestedArraysData.json)"); + InputStream istream = JSONP_Util.getInputStreamFromResource( + "jsonArrayWithLotsOfNestedArraysData.json"); + System.out.println( + "Create JsonParser from the InputStream with character encoding UTF-8 and a configuration"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream, JSONP_Util.UTF_8); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonArrayWithLotsOfNestedArraysData.json)"); + if (!parseAndVerify_JsonArrayWithLotsOfNestedArraysData(parser)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonParserTest12 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest12 Failed"); + } + + /* + * @testName: jsonParserTest13 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; + * JSONP:JAVADOC:201; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonObject defined in UTF-16LE encoding resource file + * "jsonObjectWithAllTypesOfDataUTF16LE.json". + * + * Creates the JsonParser via the API: + * + * JsonParser parser = Json.createParserFactory(Map).createParser(InputStream, Charset) + */ + @Test + public void jsonParserTest13() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "---------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset)]"); + System.out.println( + "---------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectWithAllTypesOfDataUTF16LE.json)"); + InputStream istream = JSONP_Util.getInputStreamFromResource( + "jsonObjectWithAllTypesOfDataUTF16LE.json"); + System.out.println("Create JsonParser from the InputStream using UTF-16LE encoding"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream, JSONP_Util.UTF_16LE); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectWithAllTypesOfDataUTF16LE.json)"); + pass = parseAndVerify_JsonObjectWithAllTypesOfData(parser); + } catch (Exception e) { + throw new Fault("jsonParserTest13 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest13 Failed"); + } + + /* + * @testName: jsonParserTest14 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:172; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:477; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonObject defined in resource file "jsonHelloWorld.json.json". + * + * Creates the JsonParser via the API: + * + * JsonParser parser = Json.createParser(InputStream) + */ + @Test + public void jsonParserTest14() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println("------------------------------------------"); + System.out.println("TEST CASE [Json.createParser(InputStream)]"); + System.out.println("------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonHelloWorld.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonHelloWorld.json"); + System.out.println("Create JsonParser from the InputStream"); + parser = Json.createParser(istream); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonHelloWorld.json)"); + pass = parseAndVerify_JsonHelloWorld(parser); + } catch (Exception e) { + throw new Fault("jsonParserTest14 Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("jsonParserTest14 Failed"); + } + + /* + * @testName: parseUTFEncodedTests + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:122; JSONP:JAVADOC:417; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; JSONP:JAVADOC:201; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonObject defined in resource files: + * + * jsonObjectEncodingUTF8.json jsonObjectEncodingUTF16.json + * jsonObjectEncodingUTF16LE.json jsonObjectEncodingUTF16BE.json + * jsonObjectEncodingUTF32LE.json jsonObjectEncodingUTF32BE.json + * + * Creates the JsonParser via the API: + * + * JsonParser parser = + * Json.createParserFactory(Map).createParser(InputStream, Charset) + * + * For each supported encoding supported by JSON RFC parse the JsonObject and + * verify we get the expected results. The Charset encoding is passed in as an + * argument for each encoding type tested. + */ + @Test + public void parseUTFEncodedTests() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "-----------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-8]"); + System.out.println( + "-----------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF8.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF8.json"); + System.out.println( + "Create JsonParser from the InputStream with character encoding UTF-8"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream, JSONP_Util.UTF_8); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF8.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-8 encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-16]"); + System.out.println( + "------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16.json"); + System.out.println( + "Create JsonParser from the InputStream with character encoding UTF-16"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream, JSONP_Util.UTF_16); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-16 encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-16LE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16LE.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16LE.json"); + System.out.println( + "Create JsonParser from the InputStream with character encoding UTF-16LE"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream, JSONP_Util.UTF_16LE); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16LE.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-16LE encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-16BE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16BE.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16BE.json"); + System.out.println( + "Create JsonParser from the InputStream with character encoding UTF-16BE"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream, JSONP_Util.UTF_16BE); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16BE.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-16BE encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-32LE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF32LE.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF32LE.json"); + System.out.println( + "Create JsonParser from the InputStream with character encoding UTF-32LE"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream, JSONP_Util.UTF_32LE); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF32LE.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-32LE encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "-------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParserFactory(Map).createParser(InputStream, Charset) as UTF-32BE]"); + System.out.println( + "-------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF32BE.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF32BE.json"); + System.out.println( + "Create JsonParser from the InputStream with character encoding UTF-32BE"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(istream, JSONP_Util.UTF_32BE); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF32BE.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-32BE encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("parseUTFEncodedTests Failed"); + } + + /* + * @testName: parseUTFEncodedTests2 + * + * @assertion_ids: JSONP:JAVADOC:117; JSONP:JAVADOC:120; JSONP:JAVADOC:122; + * JSONP:JAVADOC:172; JSONP:JAVADOC:235; JSONP:JAVADOC:237; JSONP:JAVADOC:239; + * JSONP:JAVADOC:375; JSONP:JAVADOC:376; + * + * @test_Strategy: Tests the JsonParser parser. Verifies PARSING of the + * JsonObject defined in resource files and auto-detecting the encoding: + * + * jsonObjectEncodingUTF8.json jsonObjectEncodingUTF16LE.json + * jsonObjectEncodingUTF16BE.json jsonObjectEncodingUTF32LE.json + * jsonObjectEncodingUTF32BE.json + * + * Creates the JsonParser via the API: + * + * JsonParser parser = Json.createParser(InputStream) + * + * For each supported encoding supported by JSON RFC the above should + * auto-detect the encoding and verify we get the expected results. + */ + @Test + public void parseUTFEncodedTests2() throws Fault { + boolean pass = true; + JsonParser parser = null; + JsonParser.Event event = null; + try { + System.out.println( + "-------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-8]"); + System.out.println( + "-------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF8.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF8.json"); + System.out.println( + "Create JsonParser from the InputStream and auto-detect character encoding UTF-8"); + parser = Json.createParser(istream); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF8.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-8 encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "----------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-16LE]"); + System.out.println( + "----------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16LE.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16LE.json"); + System.out.println( + "Create JsonParser from the InputStream and auto-detect character encoding UTF-16LE"); + parser = Json.createParser(istream); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16LE.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-16LE encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "----------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-16BE]"); + System.out.println( + "----------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16BE.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16BE.json"); + System.out.println( + "Create JsonParser from the InputStream and auto-detect character encoding UTF-16BE"); + parser = Json.createParser(istream); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF16BE.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-16BE encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "----------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-32LE]"); + System.out.println( + "----------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF32LE.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF32LE.json"); + System.out.println( + "Create JsonParser from the InputStream and auto-detect character encoding UTF-32LE"); + parser = Json.createParser(istream); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF32LE.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-32LE encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "----------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createParser(InputStream) and auto-detect as UTF-32BE]"); + System.out.println( + "----------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF32BE.json)"); + InputStream istream = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF32BE.json"); + System.out.println( + "Create JsonParser from the InputStream and auto-detect character encoding UTF-32BE"); + parser = Json.createParser(istream); + System.out.println( + "Verify that JSON Parser Events/Data matches (jsonObjectEncodingUTF32BE.json)"); + if (!parseAndVerify_JsonObjectUTF(parser)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing parsing of UTF-32BE encoding: " + e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + + if (!pass) + throw new Fault("parseUTFEncodedTests2 Failed"); + } + + /* + * @testName: jsonParserIsIntegralNumberTest + * + * @assertion_ids: JSONP:JAVADOC:120; JSONP:JAVADOC:133; JSONP:JAVADOC:375; + * JSONP:JAVADOC:376; + * + * @test_Strategy: Test JsonParser.isIntegralNumber() method. + */ + @Test + public void jsonParserIsIntegralNumberTest() throws Fault { + boolean pass = true; + JsonParser parser = null; + String jsonTestString = "[123, 12345.45]"; + try { + System.out.println("Create JsonParser"); + parser = Json.createParser(new StringReader(jsonTestString)); + // INTEGRAL NUMBER TEST + JsonParser.Event event = JSONP_Util.getNextSpecificParserEvent(parser, + JsonParser.Event.VALUE_NUMBER); // e=JsonParser.Event.VALUE_NUMBER + JSONP_Util.dumpEventType(event); + if (!JSONP_Util.assertEqualsJsonNumberType(parser.isIntegralNumber(), + JSONP_Util.INTEGRAL)) + pass = false; + else { + if (!JSONP_Util.assertEquals(123, parser.getInt())) + pass = false; + } + // NON_INTEGRAL NUMBER TEST + event = JSONP_Util.getNextSpecificParserEvent(parser, + JsonParser.Event.VALUE_NUMBER); // e=JsonParser.Event.VALUE_NUMBER + JSONP_Util.dumpEventType(event); + if (!JSONP_Util.assertEqualsJsonNumberType(parser.isIntegralNumber(), + JSONP_Util.NON_INTEGRAL)) + pass = false; + else { + if (!JSONP_Util.assertEquals(12345.45, + parser.getBigDecimal().doubleValue())) + pass = false; + } + + } catch (Exception e) { + throw new Fault("jsonParserIsIntegralNumberTest Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + + if (!pass) + throw new Fault("jsonParserIsIntegralNumberTest Failed"); + } + + private boolean tripIllegalStateException(JsonParser parser, + JsonParser.Event event) { + boolean pass = true; + + // Check in case event is null + if (event == null) { + System.err.println("event is null - unexpected."); + return false; + } + System.out.println("Event=" + JSONP_Util.getEventTypeString(event)); + System.out.println("Testing call to JsonParser.getString()"); + if (event != JsonParser.Event.VALUE_STRING + && event != JsonParser.Event.VALUE_NUMBER + && event != JsonParser.Event.KEY_NAME) { + try { + System.out.println("Trip IllegalStateException by calling JsonParser.getString()"); + String string = parser.getString(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + } else { + System.out.println("No testing for IllegalStateException for this scenario."); + } + + System.out.println("Testing call to JsonParser.isIntegralNumber()"); + if (event != JsonParser.Event.VALUE_NUMBER) { + try { + System.out.println( + "Trip IllegalStateException by calling JsonParser.isIntegralNumber()"); + boolean numberType = parser.isIntegralNumber(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + } else { + System.out.println("No testing for IllegalStateException for this scenario."); + } + + System.out.println("Testing call to JsonParser.getBigDecimal()"); + if (event != JsonParser.Event.VALUE_NUMBER) { + try { + System.out.println( + "Trip IllegalStateException by calling JsonParser.getBigDecimal()"); + BigDecimal number = parser.getBigDecimal(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + } else { + System.out.println("No testing for IllegalStateException for this scenario."); + } + + System.out.println("Testing call to JsonParser.getInt()"); + if (event != JsonParser.Event.VALUE_NUMBER) { + try { + System.out.println("Trip IllegalStateException by calling JsonParser.getInt()"); + int number = parser.getInt(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + } else { + System.out.println("No testing for IllegalStateException for this scenario."); + } + + System.out.println("Testing call to JsonParser.getLong()"); + if (event != JsonParser.Event.VALUE_NUMBER) { + try { + System.out.println("Trip IllegalStateException by calling JsonParser.getLong()"); + long number = parser.getLong(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + } else { + System.out.println("No testing for IllegalStateException for this scenario."); + } + return pass; + } + + /* + * @testName: jsonParserIllegalExceptionTests + * + * @assertion_ids: JSONP:JAVADOC:121; JSONP:JAVADOC:123; JSONP:JAVADOC:236; + * JSONP:JAVADOC:238; JSONP:JAVADOC:240; + * + * @test_Strategy: Test JsonParser exception conditions. Trip the following + * exceptions: + * + * java.lang.IllegalStateException + */ + @Test + public void jsonParserIllegalExceptionTests() throws Fault { + boolean pass = true; + JsonParser parser = null; + String jsonTestString = "[\"string\",100,false,null,true,{\"foo\":\"bar\"}]"; + try { + System.out.println("Create JsonParser"); + parser = Json.createParserFactory(JSONP_Util.getEmptyConfig()) + .createParser(new StringReader(jsonTestString)); + JsonParser.Event event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.START_ARRAY */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_STRING */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_NUMBER */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_FALSE */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_NULL */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_TRUE */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.START_OBJECT */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.KEY_NAME */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.VALUE_STRING */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.END_OBJECT */ + if (!tripIllegalStateException(parser, event)) + pass = false; + event = JSONP_Util + .getNextParserEvent(parser); /* e=JsonParser.Event.END_ARRAY */ + if (!tripIllegalStateException(parser, event)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonParserIllegalExceptionTests Failed: ", e); + } finally { + try { + parser.close(); + } catch (Exception e) { + } + } + + if (!pass) + throw new Fault("jsonParserIllegalExceptionTests Failed"); + } + + /* + * @testName: jsonParserIOErrorTests + * + * @assertion_ids: JSONP:JAVADOC:207; JSONP:JAVADOC:389; JSONP:JAVADOC:415; + * + * @test_Strategy: Tests for JsonException for testable i/o errors. + * + */ + @SuppressWarnings("ConvertToTryWithResources") + @Test + public void jsonParserIOErrorTests() throws Fault { + boolean pass = true; + + String jsonText = "{\"name1\":\"value1\",\"name2\":\"value2\"}"; + + // Trip JsonException if there is an i/o error on + // Json.createParser(InputStream) + try { + System.out.println( + "Trip JsonException if there is an i/o error on Json.createParser(InputStream)."); + System.out.println("Parsing " + jsonText); + InputStream is = JSONP_Util.getInputStreamFromString(jsonText); + MyBufferedInputStream mbi = new MyBufferedInputStream(is, true); + System.out.println("Calling Json.createParser(InputStream)"); + JsonParser parser = Json.createParser(mbi); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonException if there is an i/o error on JsonParser.next() + try { + System.out.println( + "Trip JsonException if there is an i/o error on JsonParser.next()."); + System.out.println("Parsing " + jsonText); + InputStream is = JSONP_Util.getInputStreamFromString(jsonText); + MyBufferedInputStream mbi = new MyBufferedInputStream(is, true); + JsonParser parser = Json.createParser(mbi); + System.out.println("Calling JsonParser.next()"); + parser.next(); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonException if there is an i/o error on JsonParser.close() + try { + System.out.println( + "Trip JsonException if there is an i/o error on JsonParser.close()."); + System.out.println("Parsing " + jsonText); + InputStream is = JSONP_Util.getInputStreamFromString(jsonText); + MyBufferedInputStream mbi = new MyBufferedInputStream(is); + JsonParser parser = Json.createParser(mbi); + mbi.setThrowIOException(true); + System.out.println("Calling JsonParser.close()"); + parser.close(); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonParserIOErrorTests Failed"); + } + + /* + * @testName: jsonParserExceptionTests + * + * @assertion_ids: JSONP:JAVADOC:390; JSONP:JAVADOC:391; + * + * @test_Strategy: Tests for the following exception test cases: + * + * JsonParsingException - if incorrect JSON is encountered while advancing + * parser to next state NoSuchElementException - if there are no more parsing + * states + * + */ + @Test + public void jsonParserExceptionTests() throws Fault { + boolean pass = true; + + // Trip JsonParsingException for JsonParser.next() if incorrect JSON is + // encountered + try { + System.out.println( + "Trip JsonParsingException for JsonParser.next() if incorrect JSON is encountered"); + InputStream is = JSONP_Util.getInputStreamFromString("}{"); + JsonParser parser = Json.createParser(is); + parser.next(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip NoSuchElementException for JsonParser.next() if no more parsing + // states + try { + System.out.println( + "Trip NoSuchElementException for JsonParser.next() if no more parsing states"); + InputStream is = JSONP_Util.getInputStreamFromString("{}"); + JsonParser parser = Json.createParser(is); + parser.next(); // Event -> START_OBJECT { + parser.next(); // Event -> END_OBJECT } + parser.next(); // Event -> NoSuchElementException should be thrown + System.err.println("Did not get expected NoSuchElementException"); + pass = false; + } catch (NoSuchElementException e) { + System.out.println("Caught expected NoSuchElementException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonParserExceptionTests Failed"); + } + + /* + * @testName: invalidLiteralNamesTest + * + * @assertion_ids: JSONP:JAVADOC:133; JSONP:JAVADOC:390; + * + * @test_Strategy: This test trips various JsonParsingException conditions + * when parsing an uppercase literal name that must be lowercase per JSON RFC + * for the literal values (true, false or null). + * + */ + @Test + public void invalidLiteralNamesTest() throws Fault { + boolean pass = true; + + // Trip JsonParsingException for JsonParser.next() if invalid liternal TRUE + // instead of true + try { + System.out.println( + "Trip JsonParsingException for JsonParser.next() if invalid liternal TRUE instead of true."); + System.out.println("Reading " + "[TRUE]"); + JsonParser parser = Json.createParser(new StringReader("[TRUE]")); + parser.next(); // Event -> START_OBJECT { + parser.next(); // Event -> JsonParsingException (invalid literal TRUE) + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonParsingException for JsonParser.next() if invalid liternal FALSE + // instead of false + try { + System.out.println( + "Trip JsonParsingException for JsonParser.next() if invalid liternal FALSE instead of false."); + System.out.println("Reading " + "[FALSE]"); + JsonParser parser = Json.createParser(new StringReader("[FALSE]")); + parser.next(); // Event -> START_OBJECT { + parser.next(); // Event -> JsonParsingException (invalid literal FALSE) + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonParsingException for JsonParser.next() if invalid liternal NULL + // instead of null + try { + System.out.println( + "Trip JsonParsingException for JsonParser.next() if invalid liternal NULL instead of null."); + System.out.println("Reading " + "[NULL]"); + JsonParser parser = Json.createParser(new StringReader("[NULL]")); + parser.next(); // Event -> START_OBJECT { + parser.next(); // Event -> JsonParsingException (invalid literal NULL) + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("invalidLiteralNamesTest Failed"); + } + + /* + * @testName: jsonParser11Test + * + * @assertion_ids: JSONP:JAVADOC:673; JSONP:JAVADOC:674; JSONP:JAVADOC:675; + * JSONP:JAVADOC:676; JSONP:JAVADOC:677; JSONP:JAVADOC:678; JSONP:JAVADOC:679; + * JSONP:JAVADOC:680; JSONP:JAVADOC:583; JSONP:JAVADOC:584; JSONP:JAVADOC:585; + * JSONP:JAVADOC:586; JSONP:JAVADOC:587; JSONP:JAVADOC:588; JSONP:JAVADOC:662; + * JSONP:JAVADOC:663; JSONP:JAVADOC:664; JSONP:JAVADOC:665; JSONP:JAVADOC:666; + * JSONP:JAVADOC:667; + * + * @test_Strategy: Tests JsonParser API methods added in JSON-P 1.1. + */ + @Test + public void jsonParser11Test() throws Fault { + Parser parserTest = new Parser(); + final TestResult result = parserTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparsertests/Parser.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparsertests/Parser.java new file mode 100644 index 00000000..3e5e988e --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonparsertests/Parser.java @@ -0,0 +1,670 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonparsertests; + +import jakarta.jsonp.tck.api.common.TestResult; +import java.io.StringReader; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.stream.Stream; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonException; +import jakarta.json.JsonObject; +import jakarta.json.JsonStructure; +import jakarta.json.JsonValue; +import jakarta.json.stream.JsonParser; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests: {@link JsonParser} API + * methods added in JSON-P 1.1. + */ +public class Parser { + + /** Tests input data with various JsonValue instances. */ + private static final JsonValue[] VALUES = new JsonValue[] { + toJsonValue(STR_VALUE), // Non JsonObject with String + toJsonValue(INT_VALUE), // Non JsonObject with int + toJsonValue(LNG_VALUE), // Non JsonObject with long + toJsonValue(DBL_VALUE), // Non JsonObject with double + toJsonValue(BOOL_VALUE), // Non JsonObject with boolean + toJsonValue(BDC_VALUE), // Non JsonObject with BigDecimal + toJsonValue(BIN_VALUE), // Non JsonObject with BigInteger + createSimpleObjectStr(), // JsonObject with String + createSimpleObjectInt(), // JsonObject with int + createSimpleObjectBool(), // JsonObject with boolean + createSimpleObjectObject(), // JsonObject with JsonObject + createEmptyArrayWithStr(), // JsonArray with String + createEmptyArrayWithInt(), // JsonArray with int + createEmptyArrayWithBool(), // JsonArray with boolean + createEmptyArrayWithObject() // JsonArray with JsonObject + }; + + // /** Tests input data with simple JsonValue instances. */ + // private static final JsonValue[] SIMPLE_VALUES = new JsonValue[] { + // toJsonValue(STR_VALUE), // Non JsonObject with String + // toJsonValue(INT_VALUE), // Non JsonObject with int + // toJsonValue(LNG_VALUE), // Non JsonObject with long + // toJsonValue(BOOL_VALUE), // Non JsonObject with boolean + // toJsonValue(BDC_VALUE), // Non JsonObject with BigDecimal + // toJsonValue(BIN_VALUE) // Non JsonObject with BigInteger + // }; + + /** Tests input data with compound JsonValue instances (object or array). */ + private static final JsonStructure[] COMPOUND_VALUES = new JsonStructure[] { + createSimpleObjectStr(), // JsonObject with String + createSimpleObjectInt(), // JsonObject with int + createSimpleObjectBool(), // JsonObject with boolean + createSimpleObjectObject(), // JsonObject with JsonObject + createEmptyArrayWithStr(), // JsonArray with String + createEmptyArrayWithInt(), // JsonArray with int + createEmptyArrayWithBool(), // JsonArray with boolean + createEmptyArrayWithObject() // JsonArray with JsonObject + }; + + /** Tests input data with empty JsonObject and JsonArray instances. */ + private static final JsonStructure[] EMPTY_VALUES = new JsonStructure[] { + createEmptyObject(), // Empty JsonObject + createEmptyArray() // Empty JsonArray + }; + + /** Tests input data with JsonObject instances. */ + private static final JsonObject[] OBJ_VALUES = new JsonObject[] { + createSimpleObjectStr(), // JsonObject with String + createSimpleObjectInt(), // JsonObject with int + createSimpleObjectBool(), // JsonObject with boolean + createSimpleObjectObject(), // JsonObject with JsonObject + createSimpleObjectWithStr() // JsonObject with default value (String) and + // another String + + }; + + /** Tests input data with non JsonObject instances. */ + private static final JsonValue[] NON_OBJ_VALUES = new JsonValue[] { + toJsonValue(STR_VALUE), // Non JsonObject with String + toJsonValue(INT_VALUE), // Non JsonObject with int + toJsonValue(LNG_VALUE), // Non JsonObject with long + toJsonValue(DBL_VALUE), // Non JsonObject with double + toJsonValue(BOOL_VALUE), // Non JsonObject with boolean + toJsonValue(BDC_VALUE), // Non JsonObject with BigDecimal + toJsonValue(BIN_VALUE), // Non JsonObject with BigInteger + createEmptyArrayWithStr(), // JsonArray with String + createEmptyArrayWithInt(), // JsonArray with int + createEmptyArrayWithBool(), // JsonArray with boolean + createEmptyArrayWithObject() // JsonArray with JsonObject + }; + + /** Tests input data with JsonArray instances. */ + private static final JsonArray[] ARRAY_VALUES = new JsonArray[] { + createEmptyArrayWithStr(), // JsonArray with String + createEmptyArrayWithInt(), // JsonArray with int + createEmptyArrayWithBool(), // JsonArray with boolean + createEmptyArrayWithObject() // JsonArray with JsonObject + }; + + /** Tests input data with non JsonArray instances. */ + private static final JsonValue[] NON_ARRAY_VALUES = new JsonValue[] { + toJsonValue(STR_VALUE), // Non JsonObject with String + toJsonValue(INT_VALUE), // Non JsonObject with int + toJsonValue(LNG_VALUE), // Non JsonObject with long + toJsonValue(DBL_VALUE), // Non JsonObject with double + toJsonValue(BOOL_VALUE), // Non JsonObject with boolean + toJsonValue(BDC_VALUE), // Non JsonObject with BigDecimal + toJsonValue(BIN_VALUE), // Non JsonObject with BigInteger + createSimpleObjectStr(), // JsonObject with String + createSimpleObjectInt(), // JsonObject with int + createSimpleObjectBool(), // JsonObject with boolean + createSimpleObjectObject() // JsonObject with JsonObject + }; + + /** + * Creates an instance of {@link JsonParser} API methods added in JSON-P 1.1 + * test. + */ + Parser() { + super(); + } + + /** + * Test {@link JsonParser} API methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonParser API methods added in JSON-P 1.1."); + System.out.println("JsonParser API methods added in JSON-P 1.1."); + testGetObject(result); + testGetNonObject(result); + testGetArray(result); + testGetNonArray(result); + testGetValue(result); + testGetIllegalValue(result); + testGetObjectStream(result); + testGetNonObjectStream(result); + testGetArrayStream(result); + testGetNonArrayStream(result); + testGetValueStream(result); + testGetCompoundValueStream(result); + testSkipArray(result); + testSkipNonArray(result); + testSkipObject(result); + testSkipNonObject(result); + return result; + } + + /** + * Test {@code JsonParser getObject()} method on JSON object values. + */ + private void testGetObject(final TestResult result) { + for (JsonObject value : OBJ_VALUES) { + final String data = jsonData(value); + System.out.println(" - getObject() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + JsonObject out = parser.getObject(); + if (operationFailed(value, out)) { + result.fail("getObject()", "Output value " + valueToString(out) + + " shall be " + valueToString(value)); + } + } catch (JsonException ex) { + System.out.println("Caught JsonException: " + ex.getLocalizedMessage()); + result.fail("getObject()", + "Caught JsonException: " + ex.getLocalizedMessage()); + } + } + } + + /** + * Test {@code JsonParser getObject()} method on non JSON object values. + */ + private void testGetNonObject(final TestResult result) { + for (JsonValue value : NON_OBJ_VALUES) { + final String data = jsonData(value); + System.out.println(" - getObject() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + parser.getObject(); + result.fail("getObject()", + "Calling method on non object value shall throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println(" Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("getObject()", + "Calling method on non object value shall throw IllegalStateException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonParser getArray()} method on JSON array values. + */ + private void testGetArray(final TestResult result) { + for (JsonArray value : ARRAY_VALUES) { + final String data = jsonData(value); + System.out.println(" - getArray() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + JsonArray out = parser.getArray(); + if (operationFailed(value, out)) { + result.fail("getArray()", "Output value " + valueToString(out) + + " shall be " + valueToString(value)); + } + } catch (JsonException ex) { + System.out.println("Caught JsonException: " + ex.getLocalizedMessage()); + result.fail("getArray()", + "Caught JsonException: " + ex.getLocalizedMessage()); + } + } + } + + /** + * Test {@code JsonParser getArray()} method on non JSON object values. + */ + private void testGetNonArray(final TestResult result) { + for (JsonValue value : NON_ARRAY_VALUES) { + final String data = jsonData(value); + System.out.println(" - getArray() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + parser.getArray(); + result.fail("getArray()", + "Calling method on non array value shall throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println(" Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("getArray()", + "Calling method on non array value shall throw IllegalStateException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonParser getValue()} method on common JSON values. + */ + private void testGetValue(final TestResult result) { + for (JsonValue value : VALUES) { + final String data = jsonData(value); + System.out.println(" - getValue() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + JsonValue out = parser.getValue(); + if (operationFailed(value, out)) { + result.fail("getValue()", "Output value " + valueToString(out) + + " shall be " + valueToString(value)); + } + } catch (JsonException ex) { + System.out.println("Caught JsonException: " + ex.getLocalizedMessage()); + result.fail("getValue()", + "Caught JsonException: " + ex.getLocalizedMessage()); + } + } + } + + /** + * Test {@code JsonParser getValue()} method on END_OBJECT and END_ARRAY + * lexical elements. + */ + private void testGetIllegalValue(final TestResult result) { + for (JsonValue value : EMPTY_VALUES) { + final String data = jsonData(value); + System.out.println(" - getValue() on 2nd lexical element of " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); // Skip to START ELEMENT + parser.next(); // Skip to END ELEMENT + parser.getValue(); + result.fail("getValue()", + "Calling method on END_OBJECT and END_ARRAY lexical elements shall throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println(" Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("getValue()", + "Calling method on END_OBJECT and END_ARRAY lexical elements shall throw IllegalStateException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonParser getObjectStream()} method on JSON object values. + */ + private void testGetObjectStream(final TestResult result) { + for (JsonObject value : OBJ_VALUES) { + final String data = jsonData(value); + System.out.println(" - getObjectStream() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + Stream> out = parser.getObjectStream(); + if (operationFailed(value, out)) { + result.fail("getObjectStream()", + "Output Stream shall contain " + valueToString(value)); + } + } catch (JsonException ex) { + System.out.println("Caught JsonException: " + ex.getLocalizedMessage()); + result.fail("getObjectStream()", + "Caught JsonException: " + ex.getLocalizedMessage()); + } + } + } + + /** + * Test {@code JsonParser getObjectStream()} method on non JSON object values. + */ + private void testGetNonObjectStream(final TestResult result) { + for (JsonValue value : NON_OBJ_VALUES) { + final String data = jsonData(value); + System.out.println(" - getObjectStream() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + parser.getObjectStream(); + result.fail("getObjectStream()", + "Calling method on non object value shall throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println(" Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("getObjectStream()", + "Calling method on non object value shall throw IllegalStateException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonParser getArrayStream()} method on JSON array values. + */ + private void testGetArrayStream(final TestResult result) { + for (JsonArray value : ARRAY_VALUES) { + final String data = jsonData(value); + System.out.println(" - getArrayStream() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + Stream out = parser.getArrayStream(); + if (operationFailed(value, out)) { + result.fail("getArrayStream()", + "Output Stream shall contain " + valueToString(value)); + } + } catch (JsonException ex) { + System.out.println("Caught JsonException: " + ex.getLocalizedMessage()); + result.fail("getArrayStream()", + "Caught JsonException: " + ex.getLocalizedMessage()); + } + } + } + + /** + * Test {@code JsonParser getArrayStream()} method on non JSON array values. + */ + private void testGetNonArrayStream(final TestResult result) { + for (JsonValue value : NON_ARRAY_VALUES) { + final String data = jsonData(value); + System.out.println(" - getArrayStream() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + parser.getArrayStream(); + result.fail("getArrayStream()", + "Calling method on non array value shall throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println(" Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("getArrayStream()", + "Calling method on non array value shall throw IllegalStateException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonParser getValueStream()} method on simple JSON values in + * document root. + */ + private void testGetValueStream(final TestResult result) { + for (final JsonValue value : VALUES) { + final String data = jsonData(value); + System.out.println(" - getValueStream() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + final Stream outStream = parser.getValueStream(); + int count = 0; + for (final Iterator i = outStream.iterator(); i.hasNext();) { + final JsonValue out = i.next(); + if (operationFailed(value, out)) { + result.fail("getValueStream()", "Output Stream value " + + valueToString(out) + " shall be " + valueToString(value)); + } + count++; + } + if (count != 1) { + System.out.println(" Output Stream contains " + + Integer.toString(count) + " values, not 1"); + result.fail("getValueStream()", + "Output Stream does not contain exactly 1 JSON value"); + } + } + } + } + + /** + * Test {@code JsonParser getValueStream()} method inside compound JSON values + * in document root. + */ + private void testGetCompoundValueStream(final TestResult result) { + for (final JsonValue value : COMPOUND_VALUES) { + final String data = jsonData(value); + System.out.println(" - getValueStream() inside " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + parser.getValueStream(); + result.fail("getValueStream()", + "Calling method on non object value shall throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println(" Expected exception: " + e.getMessage()); + } catch (Throwable t) { + result.fail("getValueStream()", + "Calling method on non object value shall throw IllegalStateException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonParser skipArray()} method inside JSON array values. + * Expected result: Parser shall advance to the end of the stream after + * skipping an array which is the only value in the stream. + */ + private void testSkipArray(final TestResult result) { + for (final JsonArray value : ARRAY_VALUES) { + final String data = jsonData(value); + System.out.println(" - skipArray() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + parser.skipArray(); + if (parser.hasNext()) { + result.fail("skipArray()", + "Parser did not davance to the end of the array"); + } + } catch (Throwable t) { + System.out.println( + " " + t.getClass().getSimpleName() + ": " + t.getMessage()); + result.fail("skipArray()", + t.getClass().getSimpleName() + ": " + t.getMessage()); + } + } + } + + /** + * Test {@code JsonParser skipArray()} method outside JSON array values. + * Expected result: Parser shall not advance anywhere when called outside an + * array. Whole value shall match after {@code skipArray()} call because + * nothing shall happen in it. + */ + private void testSkipNonArray(final TestResult result) { + for (final JsonValue value : NON_ARRAY_VALUES) { + final String data = jsonData(value); + System.out.println(" - skipArray() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + parser.skipArray(); + final JsonValue out = parser.getValue(); + if (operationFailed(value, out)) { + result.fail("skipArray()", + "Output value " + valueToString(out) + " shall be " + + valueToString(value) + " even after skipArray()"); + } + } catch (Throwable t) { + System.out.println( + " " + t.getClass().getSimpleName() + ": " + t.getMessage()); + result.fail("skipArray()", + t.getClass().getSimpleName() + ": " + t.getMessage()); + } + } + } + + /** + * Test {@code JsonParser skipObject()} method inside JSON object values. + * Expected result: Parser shall advance to the end of the stream after + * skipping an object which is the only value in the stream. + */ + private void testSkipObject(final TestResult result) { + for (final JsonObject value : OBJ_VALUES) { + final String data = jsonData(value); + System.out.println(" - skipObject() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + parser.skipObject(); + if (parser.hasNext()) { + result.fail("skipObject()", + "Parser did not davance to the end of the object"); + } + } catch (Throwable t) { + System.out.println( + " " + t.getClass().getSimpleName() + ": " + t.getMessage()); + result.fail("skipObject()", + t.getClass().getSimpleName() + ": " + t.getMessage()); + } + } + } + + /** + * Test {@code JsonParser skipObject()} method outside JSON object values. + * Expected result: Parser shall not advance anywhere when called outside an + * object. Whole value shall match after {@code skipObject()} call because + * nothing shall happen in it. + */ + private void testSkipNonObject(final TestResult result) { + for (final JsonValue value : NON_OBJ_VALUES) { + final String data = jsonData(value); + System.out.println(" - skipObject() on " + data); + final StringReader strReader = new StringReader(data); + try (final JsonParser parser = Json.createParser(strReader)) { + parser.next(); + parser.skipObject(); + final JsonValue out = parser.getValue(); + if (operationFailed(value, out)) { + result.fail("skipObject()", + "Output value " + valueToString(out) + " shall be " + + valueToString(value) + " even after skipObject()"); + } + } catch (Throwable t) { + System.out.println( + " " + t.getClass().getSimpleName() + ": " + t.getMessage()); + result.fail("skipObject()", + t.getClass().getSimpleName() + ": " + t.getMessage()); + } + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + System.out.println(" Checking " + valueToString(out)); + return out == null || !assertEquals(check, out); + } + + /** + * Operation result check. + * + * @param check + * Expected Stream content. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonObject check, + final Stream> out) { + // Operation failed for null. + if (out == null) { + System.out.println(" Output is null"); + return true; + } + final Set keys = new HashSet<>(check.size()); + // Clone key Set + for (final String key : check.keySet()) { + keys.add(key); + } + for (final Iterator> i = out.iterator(); i + .hasNext();) { + final Map.Entry item = i.next(); + final JsonValue checkValue = check.get(item.getKey()); + System.out.println(" Checking " + valueToString(item.getValue())); + // Operation failed if values with the same key are not equal. + if (!item.getValue().equals(checkValue)) { + System.out.println(" check: " + valueToString(checkValue) + + " stream: " + valueToString(checkValue)); + return true; + } + keys.remove(item.getKey()); + } + // Operation failed if some unmatched keys remain in the set. + return !keys.isEmpty(); + } + + /** + * Operation result check. + * + * @param check + * Expected Stream content. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonArray check, + final Stream out) { + // Operation failed for null. + if (out == null) { + System.out.println(" Output is null"); + return true; + } + final Iterator ci = check.iterator(); + final Iterator oi = out.iterator(); + // To exit cycle, at least one of iterators does not have next value. + while (ci.hasNext() && oi.hasNext()) { + final JsonValue checkValue = ci.next(); + final JsonValue outValue = oi.next(); + System.out.println(" Checking " + valueToString(outValue)); + if (!checkValue.equals(outValue)) { + System.out.println(" check: " + valueToString(checkValue) + + " stream: " + valueToString(checkValue)); + return true; + } + } + // Check still has values, something was missing in output. + if (ci.hasNext()) { + System.out.println(" Output contains less values than expected"); + return true; + } + // Output still has values, it contains more than expected. + if (oi.hasNext()) { + System.out.println(" Output contains more values than expected"); + return true; + } + return false; + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonreaderfactorytests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonreaderfactorytests/ClientTests.java new file mode 100644 index 00000000..ccb99bb3 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonreaderfactorytests/ClientTests.java @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonreaderfactorytests; + + +import jakarta.json.*; +import jakarta.json.stream.*; + +import java.io.*; +import java.nio.charset.Charset; + +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.List; +import java.util.Iterator; +import java.util.Map; +import java.util.ArrayList; + +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonReaderFactoryTest1 + * + * @assertion_ids: JSONP:JAVADOC:419; JSONP:JAVADOC:449; JSONP:JAVADOC:185; + * JSONP:JAVADOC:459; + * + * @test_Strategy: Tests the JsonReaderFactory API. + * + * JsonReaderFactory readerFactory = Json.createReaderFactory(Map); + * JsonReader reader1 = readerFactory.createReader(Reader) JsonReader reader2 + * = readerFactory.createReader(Reader) + */ + @Test + public void jsonReaderFactoryTest1() throws Fault { + boolean pass = true; + JsonReader reader1 = null; + JsonReader reader2 = null; + JsonObject jsonObject = null; + String jsonObjectText = "{\"foo\":\"bar\"}"; + try { + System.out.println("Create JsonReaderFactory with Map with EMPTY config"); + JsonReaderFactory readerFactory = Json + .createReaderFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = readerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + System.out.println("--------------------------------------------------"); + System.out.println("TEST CASE [JsonReaderFactory.createReader(Reader)]"); + System.out.println("--------------------------------------------------"); + System.out.println("Create 1st JsonReader using JsonReaderFactory"); + reader1 = readerFactory.createReader(new StringReader(jsonObjectText)); + if (reader1 == null) { + System.err.println("ReaderFactory failed to create reader1"); + pass = false; + } else { + jsonObject = reader1.readObject(); + reader1.close(); + + if (!JSONP_Util.assertEquals(jsonObject.size(), 1) + || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) + pass = false; + } + + System.out.println("Create 2nd JsonReader using JsonReaderFactory"); + reader2 = readerFactory.createReader(new StringReader(jsonObjectText)); + if (reader2 == null) { + System.err.println("ReaderFactory failed to create reader2"); + pass = false; + } else { + jsonObject = reader2.readObject(); + reader2.close(); + + if (!JSONP_Util.assertEquals(jsonObject.size(), 1) + || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) + pass = false; + } + + } catch (Exception e) { + throw new Fault("jsonReaderFactoryTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonReaderFactoryTest1 Failed"); + } + + /* + * @testName: jsonReaderFactoryTest2 + * + * @assertion_ids: JSONP:JAVADOC:420; JSONP:JAVADOC:449; JSONP:JAVADOC:185; + * JSONP:JAVADOC:459; + * + * @test_Strategy: Tests the JsonReaderFactory API. + * + * JsonReaderFactory readerFactory = Json.createReaderFactory(Map); + * JsonReader reader1 = readerFactory.createReader(InputStream, Charset) + * JsonReader reader2 = readerFactory.createReader(InputStream, Charset) + * + * Create reader with both UTF-8 and UTF-16BE. + */ + @Test + public void jsonReaderFactoryTest2() throws Fault { + boolean pass = true; + JsonReader reader1 = null; + JsonReader reader2 = null; + JsonObject jsonObject = null; + String jsonObjectText = "{\"foo\":\"bar\"}"; + try { + System.out.println("Create JsonReaderFactory with Map with EMPTY config"); + JsonReaderFactory readerFactory = Json + .createReaderFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = readerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println( + "----------------------------------------------------------------"); + System.out.println( + "TEST CASE [JsonReaderFactory.createReader(InputStream, Charset)]"); + System.out.println( + "----------------------------------------------------------------"); + System.out.println( + "Create 1st JsonReader using JsonReaderFactory with UTF-8 encoding"); + InputStream is1 = JSONP_Util.getInputStreamFromString(jsonObjectText); + reader1 = readerFactory.createReader(is1, JSONP_Util.UTF_8); + if (reader1 == null) { + System.err.println("ReaderFactory failed to create reader1"); + pass = false; + } else { + jsonObject = reader1.readObject(); + reader1.close(); + + if (!JSONP_Util.assertEquals(jsonObject.size(), 1) + || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) + pass = false; + } + + System.out.println( + "Create 2nd JsonReader using JsonReaderFactory with UTF-8 encoding"); + InputStream is2 = JSONP_Util.getInputStreamFromString(jsonObjectText); + reader2 = readerFactory.createReader(is2, JSONP_Util.UTF_8); + if (reader2 == null) { + System.err.println("ReaderFactory failed to create reader2"); + pass = false; + } else { + jsonObject = reader2.readObject(); + reader2.close(); + + if (!JSONP_Util.assertEquals(jsonObject.size(), 1) + || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) + pass = false; + } + + } catch (Exception e) { + throw new Fault("jsonReaderFactoryTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonReaderFactoryTest2 Failed"); + } + + /* + * @testName: jsonReaderFactoryTest3 + * + * @assertion_ids: JSONP:JAVADOC:429; JSONP:JAVADOC:449; JSONP:JAVADOC:185; + * JSONP:JAVADOC:459; + * + * @test_Strategy: Tests the JsonReaderFactory API. + * + * JsonReaderFactory readerFactory = Json.createReaderFactory(Map); + * JsonReader reader1 = readerFactory.createReader(InputStream) JsonReader + * reader2 = readerFactory.createReader(InputStream) + */ + @Test + public void jsonReaderFactoryTest3() throws Fault { + boolean pass = true; + JsonReader reader1 = null; + JsonReader reader2 = null; + JsonObject jsonObject = null; + String jsonObjectText = "{\"foo\":\"bar\"}"; + try { + System.out.println("Create JsonReaderFactory with Map with EMPTY config"); + JsonReaderFactory readerFactory = Json + .createReaderFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = readerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("-------------------------------------------------------"); + System.out.println("TEST CASE [JsonReaderFactory.createReader(InputStream)]"); + System.out.println("-------------------------------------------------------"); + System.out.println("Create 1st JsonReader using JsonReaderFactory"); + InputStream is1 = JSONP_Util.getInputStreamFromString(jsonObjectText); + reader1 = readerFactory.createReader(is1); + if (reader1 == null) { + System.err.println("ReaderFactory failed to create reader1"); + pass = false; + } else { + jsonObject = reader1.readObject(); + reader1.close(); + + if (!JSONP_Util.assertEquals(jsonObject.size(), 1) + || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) + pass = false; + } + + System.out.println("Create 2nd JsonReader using JsonReaderFactory"); + InputStream is2 = JSONP_Util.getInputStreamFromString(jsonObjectText); + reader2 = readerFactory.createReader(is2); + if (reader2 == null) { + System.err.println("ReaderFactory failed to create reader2"); + pass = false; + } else { + jsonObject = reader2.readObject(); + reader2.close(); + + if (!JSONP_Util.assertEquals(jsonObject.size(), 1) + || !JSONP_Util.assertEquals(jsonObject.getString("foo"), "bar")) + pass = false; + } + + } catch (Exception e) { + throw new Fault("jsonReaderFactoryTest3 Failed: ", e); + } + if (!pass) + throw new Fault("jsonReaderFactoryTest3 Failed"); + } + + /* + * @testName: jsonReaderFactoryTest4 + * + * @assertion_ids: JSONP:JAVADOC:449; JSONP:JAVADOC:459; + * + * @test_Strategy: Tests the JsonReaderFactory API. + * + * JsonReaderFactory readerFactory = Json.createReaderFactory(Map); + * Map config = JsonReaderFactory.getConfigInUse(); + * + * Test for the following 3 scenarios: 1) no supported provider property + * (empty config) 2) non supported provider property + */ + @Test + public void jsonReaderFactoryTest4() throws Fault { + boolean pass = true; + JsonReaderFactory readerFactory; + Map config; + try { + System.out.println("----------------------------------------------"); + System.out.println("Test scenario1: no supported provider property"); + System.out.println("----------------------------------------------"); + System.out.println("Create JsonReaderFactory with Map with EMPTY config"); + readerFactory = Json.createReaderFactory(JSONP_Util.getEmptyConfig()); + config = readerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("-----------------------------------------------"); + System.out.println("Test scenario2: non supported provider property"); + System.out.println("-----------------------------------------------"); + System.out.println("Create JsonReaderFactory with Map with FOO config"); + readerFactory = Json.createReaderFactory(JSONP_Util.getFooConfig()); + config = readerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonReaderFactoryTest4 Failed: ", e); + } + if (!pass) + throw new Fault("jsonReaderFactoryTest4 Failed"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonreadertests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonreadertests/ClientTests.java new file mode 100644 index 00000000..8a1b9880 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonreadertests/ClientTests.java @@ -0,0 +1,3232 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonreadertests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +import java.io.*; +import java.util.*; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.json.*; +import jakarta.json.stream.*; + +// $Id$ +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Utility Methods */ + + /* + * compareJsonObjectForUTFEncodedTests + */ + private boolean compareJsonObjectForUTFEncodedTests(JsonObject jsonObject) { + boolean pass = true; + System.out.println("Comparing JsonObject values to expected results."); + String expString = "stringValue"; + String actString = jsonObject.getJsonString("stringName").getString(); + if (!JSONP_Util.assertEquals(expString, actString)) + pass = false; + JsonObject actObject = jsonObject.getJsonObject("objectName"); + expString = "bar"; + actString = actObject.getJsonString("foo").getString(); + if (!JSONP_Util.assertEquals(expString, actString)) + pass = false; + JsonArray actArray = jsonObject.getJsonArray("arrayName"); + if (!JSONP_Util.assertEquals(1, actArray.getJsonNumber(0).intValue()) + || !JSONP_Util.assertEquals(2, actArray.getJsonNumber(1).intValue()) + || !JSONP_Util.assertEquals(3, actArray.getJsonNumber(2).intValue())) + pass = false; + return pass; + } + + /* Tests */ + + /* + * @testName: readEmptyArrayTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; + * + * @test_Strategy: Test read of an empty array "[]" from stream. Use + * JsonReader.readArray() API call. + * + */ + @Test + public void readEmptyArrayTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + String expJsonText = "[]"; + System.out.println("Testing read of " + expJsonText); + reader = Json.createReader(new StringReader(expJsonText)); + JsonArray array = reader.readArray(); + pass = JSONP_Util.assertEqualsEmptyArrayList(array); + } catch (Exception e) { + throw new Fault("readEmptyArrayTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readEmptyArrayTest Failed"); + } + + /* + * @testName: readEscapeCharsInArrayTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; + * + * @test_Strategy: Test read of an array from a resource file with special + * chars in data. Use JsonReader.readArray() API call. Test scenario: Read + * string of JSON text containing a JSON array from resource file with + * following data: [ "popeye\"\\\/\b\f\n\r\tolive" ] + * + * These characters are backslash escape'd as follows: \" \\ \/ \b \f \n \r \t + * + * Create a JsonWriter to write above JsonArray to a string of JSON text. + * Re-read JsonWriter text back into a JsonArray Compare expected JSON array + * with actual JSON array for equality. + * + */ + @Test + public void readEscapeCharsInArrayTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + String resourceFile = "jsonArrayWithEscapeCharsData.json"; + String expString = "popeye" + JSONP_Data.escapeCharsAsString + "olive"; + try { + + System.out.println("Reading contents of resource file " + resourceFile); + String readerContents = JSONP_Util + .getContentsOfResourceAsString(resourceFile); + System.out.println("readerContents=" + readerContents); + + System.out.println("Testing read of resource contents: " + readerContents); + reader = Json.createReader(new StringReader(readerContents)); + JsonArray expJsonArray = reader.readArray(); + + System.out.println("Dump of expJsonArray"); + JSONP_Util.dumpJsonArray(expJsonArray); + + System.out.println("Comparing JsonArray values with expected results."); + String actString = expJsonArray.getJsonString(0).getString(); + if (!JSONP_Util.assertEquals(expString, actString)) + pass = false; + + System.out.println("Write the JsonArray 'expJsonArray' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeArray(expJsonArray); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String writerContents = sWriter.toString(); + + System.out.println("Create actJsonArray from read of writer contents: " + + writerContents); + reader = Json.createReader(new StringReader(writerContents)); + JsonArray actJsonArray = reader.readArray(); + + System.out.println("Dump of actJsonArray"); + JSONP_Util.dumpJsonArray(actJsonArray); + + System.out.println("Compare expJsonArray and actJsonArray for equality"); + if (!JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray)) + pass = false; + } catch (Exception e) { + throw new Fault("readEscapeCharsInArrayTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readEscapeCharsInArrayTest Failed"); + } + + /* + * @testName: readEscapeUnicodeCharsInArrayTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; + * + * @test_Strategy: Test read of an array with unicode chars escaped and not + * escaped. Use JsonReader.readArray() API call. Test scenario: Read string of + * JSON text containing a JSON array with the following data: [ + * "\\u0000\u00ff\\uff00\uffff" ] + * + * Notice unicode \u0000 and \uff00 is escaped but \u00ff and \uffff is not. + * + * Compare expected JSON String with actual JSON String for equality. + * + */ + @Test + public void readEscapeUnicodeCharsInArrayTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + String unicodeTextString = "[\"\\u0000\u00ff\\uff00\uffff\"]"; + String expResult = "\u0000\u00ff\uff00\uffff"; + try { + System.out.println("Reading array of escaped and non escaped unicode chars."); + reader = Json.createReader(new StringReader(unicodeTextString)); + JsonArray array = reader.readArray(); + String actResult = array.getJsonString(0).getString(); + pass = JSONP_Util.assertEquals(expResult, actResult); + } catch (Exception e) { + throw new Fault("readEscapeUnicodeCharsInArrayTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readEscapeUnicodeCharsInArrayTest Failed"); + } + + /* + * @testName: readEscapeUnicodeControlCharsInArrayTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; + * + * @test_Strategy: Test read of an array with unicode control chars escaped. + * Use JsonReader.readArray() API call. Test scenario: Read string of JSON + * text containing unicode control chars escaped as a Json Array. + * + * Compare expected JSON String with actual JSON String for equality. + * + */ + @Test + public void readEscapeUnicodeControlCharsInArrayTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + String unicodeTextString = "[\"" + JSONP_Data.unicodeControlCharsEscaped + + "\"]"; + String expResult = JSONP_Data.unicodeControlCharsNonEscaped; + try { + System.out.println("Reading array of escaped and non escaped unicode chars."); + reader = Json.createReader(new StringReader(unicodeTextString)); + JsonArray array = reader.readArray(); + String actResult = array.getJsonString(0).getString(); + pass = JSONP_Util.assertEquals(expResult, actResult); + } catch (Exception e) { + throw new Fault("readEscapeUnicodeControlCharsInArrayTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readEscapeUnicodeControlCharsInArrayTest Failed"); + } + + /* + * @testName: readEmptyObjectTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; + * + * @test_Strategy: Test read of an empty object "{}" from stream. Use + * JsonReader.readObject() API call. + * + */ + @Test + public void readEmptyObjectTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + String expJsonText = "{}"; + System.out.println("Testing read of " + expJsonText); + reader = Json.createReader(new StringReader(expJsonText)); + JsonObject object = reader.readObject(); + pass = JSONP_Util.assertEqualsEmptyObjectMap(object); + } catch (Exception e) { + throw new Fault("readEmptyObjectTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readEmptyObjectTest Failed"); + } + + /* + * @testName: readEscapeCharsInObjectTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; + * + * @test_Strategy: Test read of an object from a resource file with special + * chars in data. Use JsonReader.readObject() API call. Test scenario: Read + * string of JSON text containing a JSON object from resource file with + * following data: { "specialChars" : "popeye\"\\\/\b\f\n\r\tolive" } + * + * These characters are backslash escape'd as follows: \" \\ \/ \b \f \n \r \t + * + * Create a JsonWriter to write above JsonObject to a string of JSON text. + * Re-read JsonWriter text back into a JsonObject Compare expected JSON object + * with actual JSON object for equality. + * + */ + @Test + public void readEscapeCharsInObjectTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + String resourceFile = "jsonObjectWithEscapeCharsData.json"; + String expString = "popeye" + JSONP_Data.escapeCharsAsString + "olive"; + try { + + System.out.println("Reading contents of resource file " + resourceFile); + String readerContents = JSONP_Util + .getContentsOfResourceAsString(resourceFile); + System.out.println("readerContents=" + readerContents); + + System.out.println("Testing read of resource contents: " + readerContents); + reader = Json.createReader(new StringReader(readerContents)); + JsonObject expJsonObject = reader.readObject(); + + System.out.println("Dump of expJsonObject"); + JSONP_Util.dumpJsonObject(expJsonObject); + + System.out.println("Comparing JsonArray values with expected results."); + String actString = expJsonObject.getJsonString("escapeChars").getString(); + if (!JSONP_Util.assertEquals(expString, actString)) + pass = false; + + System.out.println("Write the JsonObject 'expJsonObject' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeObject(expJsonObject); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String writerContents = sWriter.toString(); + + System.out.println("Create actJsonObject from read of writer contents: " + + writerContents); + reader = Json.createReader(new StringReader(writerContents)); + JsonObject actJsonObject = reader.readObject(); + + System.out.println("Dump of actJsonObject"); + JSONP_Util.dumpJsonObject(actJsonObject); + + System.out.println("Compare expJsonObject and actJsonObject for equality"); + if (!JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject)) + pass = false; + } catch (Exception e) { + throw new Fault("readEscapeCharsInObjectTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readEscapeCharsInObjectTest Failed"); + } + + /* + * @testName: readEscapeUnicodeCharsInObjectTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; + * + * @test_Strategy: Test read of an object with unicode chars escaped and not + * escaped. Use JsonReader.readObject() API call. Test scenario: Read string + * of JSON text containing a JSON object with the following data: { + * "unicodechars":"\\u0000\u00ff\\uff00\uffff" ] + * + * Notice unicode \u0000 and \uff00 is escaped but \u00ff and \uffff is not. + * + * Compare expected JSON String with actual JSON String for equality. + * + */ + @Test + public void readEscapeUnicodeCharsInObjectTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + String unicodeTextString = "{\"unicodechars\":\"\\u0000\u00ff\\uff00\uffff\"}"; + String expResult = "\u0000\u00ff\uff00\uffff"; + try { + System.out.println("Reading object of escaped and non escaped unicode chars."); + reader = Json.createReader(new StringReader(unicodeTextString)); + JsonObject object = reader.readObject(); + String actResult = object.getJsonString("unicodechars").getString(); + pass = JSONP_Util.assertEquals(expResult, actResult); + } catch (Exception e) { + throw new Fault("readEscapeUnicodeCharsInObjectTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readEscapeUnicodeCharsInObjectTest Failed"); + } + + /* + * @testName: readEscapeUnicodeControlCharsInObjectTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; + * + * @test_Strategy: Test read of an array with unicode control chars escaped. + * Use JsonReader.readObject() API call. Test scenario: Read string of JSON + * text containing unicode control chars escaped as a Json Object. + * + * Compare expected JSON String with actual JSON String for equality. + * + */ + @Test + public void readEscapeUnicodeControlCharsInObjectTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + String unicodeTextString = "{\"unicodechars\":\"" + + JSONP_Data.unicodeControlCharsEscaped + "\"}"; + String expResult = JSONP_Data.unicodeControlCharsNonEscaped; + try { + System.out.println("Reading array of escaped and non escaped unicode chars."); + reader = Json.createReader(new StringReader(unicodeTextString)); + JsonObject object = reader.readObject(); + String actResult = object.getJsonString("unicodechars").getString(); + pass = JSONP_Util.assertEquals(expResult, actResult); + } catch (Exception e) { + throw new Fault("readEscapeUnicodeControlCharsInObjectTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readEscapeUnicodeControlCharsInObjectTest Failed"); + } + + /* + * @testName: readArrayTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; + * + * @test_Strategy: Test read of an array containing various types from stream. + * Use JsonReader.readArray() API call. [true, false, null, "booyah", + * 2147483647, 9223372036854775807, 1.7976931348623157E308, + * [true,false,null,"bingo",-2147483648,-9223372036854775808,4.9E-324], + * {"true":true,"false":false,"null":null,"bonga":"boo","int":1,"double":10.4} + * ] Test scenario: Read string of JSON text above consisting of a JSON array + * into a JsonArray object. Create an expected List of JsonArray values for + * use in test comparison. Compare expected list of JsonArray values with + * actual list for equality. + * + */ + @Test + public void readArrayTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + String jsonText = "[true,false,null,\"booyah\",2147483647,9223372036854775807,1.7976931348623157E308," + + "[true,false,null,\"bingo\",-2147483648,-9223372036854775808,4.9E-324]," + + "{\"true\":true,\"false\":false,\"null\":null,\"bonga\":\"boo\",\"int\":1," + + "\"double\":10.4}]"; + + System.out.println("Create the expected list of JsonArray values"); + List expList = new ArrayList<>(); + expList.add(JsonValue.TRUE); + expList.add(JsonValue.FALSE); + expList.add(JsonValue.NULL); + expList.add(JSONP_Util.createJsonString("booyah")); + expList.add(JSONP_Util.createJsonNumber(Integer.MAX_VALUE)); + expList.add(JSONP_Util.createJsonNumber(Long.MAX_VALUE)); + expList.add(JSONP_Util.createJsonNumber(Double.MAX_VALUE)); + JsonArray array = Json.createArrayBuilder().add(JsonValue.TRUE) + .add(JsonValue.FALSE).add(JsonValue.NULL).add("bingo") + .add(Integer.MIN_VALUE).add(Long.MIN_VALUE).add(Double.MIN_VALUE) + .build(); + JsonObject object = Json.createObjectBuilder().add("true", JsonValue.TRUE) + .add("false", JsonValue.FALSE).add("null", JsonValue.NULL) + .add("bonga", "boo").add("int", 1).add("double", 10.4).build(); + expList.add(array); + expList.add(object); + + System.out.println("Testing read of " + jsonText); + reader = Json.createReader(new StringReader(jsonText)); + JsonArray myJsonArray = reader.readArray(); + + List actList = myJsonArray; + System.out.println( + "Compare actual list of JsonArray values with expected list of JsonArray values"); + pass = JSONP_Util.assertEqualsList(expList, actList); + } catch (Exception e) { + throw new Fault("readArrayTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readArrayTest Failed"); + } + + /* + * @testName: readArrayTest2 + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:184; + * JSONP:JAVADOC:178; + * + * @test_Strategy: Test read of an array containing various types from stream. + * Use JsonReader.readArray() API call. [true, false, null, "booyah", + * 2147483647, 9223372036854775807, 1.7976931348623157E308, + * [true,false,null,"bingo",-2147483648,-9223372036854775808,4.9E-324], + * {"true":true,"false":false,"null":null,"bonga":"boo","int":1,"double":10.4} + * ] Test Scenario: Create an expected JsonArray of the above JSON array for + * use in test comparison. Create a JsonWriter to write the above JsonArray to + * a string of JSON text. Next call JsonReader to read the JSON text from the + * JsonWriter to a JsonArray object. Compare expected JsonArray object with + * actual JsonArray object for equality. + * + */ + @Test + public void readArrayTest2() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + System.out.println("Create the expected list of JsonArray values"); + JsonArray expJsonArray = Json.createArrayBuilder().add(JsonValue.TRUE) + .add(JsonValue.FALSE).add(JsonValue.NULL).add("booyah") + .add(Integer.MAX_VALUE).add(Long.MAX_VALUE).add(Double.MAX_VALUE) + .add(Json.createArrayBuilder().add(JsonValue.TRUE) + .add(JsonValue.FALSE).add(JsonValue.NULL).add("bingo") + .add(Integer.MIN_VALUE).add(Long.MIN_VALUE).add(Double.MIN_VALUE)) + .add(Json.createObjectBuilder().add("true", JsonValue.TRUE) + .add("false", JsonValue.FALSE).add("null", JsonValue.NULL) + .add("bonga", "boo").add("int", 1).add("double", 10.4)) + .build(); + + System.out.println("Write the JsonArray 'expJsonArray' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeArray(expJsonArray); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String jsonText = sWriter.toString(); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + jsonText); + + System.out.println("Testing read of " + jsonText); + reader = Json.createReader(JSONP_Util.getInputStreamFromString(jsonText)); + JsonArray actJsonArray = reader.readArray(); + + System.out.println("Compare expJsonArray and actJsonArray for equality"); + pass = JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray); + } catch (Exception e) { + throw new Fault("readArrayTest2 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readArrayTest2 Failed"); + } + + /* + * @testName: readArrayTest3 + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:449; JSONP:JAVADOC:184; + * JSONP:JAVADOC:419; + * + * @test_Strategy: Test read of an array containing various types from stream. + * Use JsonReader.readArray() API call. [true, false, null, "booyah", + * 2147483647, 9223372036854775807, + * [true,false,null,"bingo",-2147483648,-9223372036854775808], + * {"true":true,"false":false,"null":null,"bonga":"boo","int":1} ] Test + * scenario: Read string of JSON text above consisting of a JSON array into a + * JsonArray object with an empty configuration. Create a JsonWriter to write + * the above JsonArray to a string of JSON text. Compare expected JSON text + * with actual JSON text for equality. + * + * Tests the following API's: JsonReader = + * Json.createReaderFactory(Map).createReader(Reader) JsonArray + * array = JsonReader.readArray() + * + */ + @Test + public void readArrayTest3() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + String expJsonText = "[true,false,null,\"booyah\",2147483647,9223372036854775807," + + "[true,false,null,\"bingo\",-2147483648,-9223372036854775808]," + + "{\"true\":true,\"false\":false,\"null\":null,\"bonga\":\"boo\",\"int\":1}]"; + + System.out.println("Testing read of " + expJsonText); + reader = Json.createReaderFactory(JSONP_Util.getEmptyConfig()) + .createReader(new StringReader(expJsonText)); + JsonArray myJsonArray = reader.readArray(); + + System.out.println("Write the JsonArray 'myJsonArray' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeArray(myJsonArray); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String actJsonText = sWriter.toString(); + + System.out.println("Compare actual JSON text with expected JSON text"); + pass = JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText); + } catch (Exception e) { + throw new Fault("readArrayTest3 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readArrayTest3 Failed"); + } + + /* + * @testName: readArrayTest4 + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:420; JSONP:JAVADOC:184; + * JSONP:JAVADOC:449; + * + * @test_Strategy: Test read of an array from a resource file with various + * amounts of data. Use JsonReader.readArray() API call. Test scenario: Read + * InputStream of JSON text containing a JSON array from resource file with + * various amounts of data use UTF-8 encoding. Create a JsonWriter to write + * above JsonArray to a string of JSON text. Re-read JsonWriter text back into + * a JsonArray Compare expected JSON array with actual JSON array for + * equality. + * + */ + @Test + public void readArrayTest4() throws Fault { + boolean pass = true; + JsonReader reader = null; + String resourceFile = "jsonArrayWithAllTypesOfData.json"; + try { + System.out.println( + "Read contents of InputStream from resource file: " + resourceFile); + Map config = JSONP_Util.getEmptyConfig(); + reader = Json.createReaderFactory(config).createReader( + JSONP_Util.getInputStreamFromResource(resourceFile), + JSONP_Util.UTF_8); + JsonArray expJsonArray = reader.readArray(); + + System.out.println("Dump of expJsonArray"); + JSONP_Util.dumpJsonArray(expJsonArray); + + System.out.println("Write the JsonArray 'expJsonArray' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeArray(expJsonArray); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String writerContents = sWriter.toString(); + + System.out.println("Create actJsonArray from read of writer contents: " + + writerContents); + reader = Json.createReader(new StringReader(writerContents)); + JsonArray actJsonArray = reader.readArray(); + + System.out.println("Dump of actJsonArray"); + JSONP_Util.dumpJsonArray(actJsonArray); + + System.out.println("Compare expJsonArray and actJsonArray for equality"); + pass = JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray); + } catch (Exception e) { + throw new Fault("readArrayTest4 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readArrayTest4 Failed"); + } + + /* + * @testName: readArrayTest5 + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:181; + * JSONP:JAVADOC:420; JSONP:JAVADOC:449; + * + * @test_Strategy: Test read of an array from a resource file with lots of + * nesting. Use JsonReader.read() API call. Test scenario: Read InputStream of + * JSON text containing a JSON array from resource file with lots of nesting + * use UTF-8 encoding with empty configuration. Create a JsonWriter to write + * above JsonArray to a string of JSON text. Compare expected JSON text with + * actual JSON text for equality. Filter all text output to remove whitespace + * before comparison. + * + * Tests the following API's: JsonReader = + * Json.createReaderFactory(Map).createReader(InputStream, Charset) + * JsonArray array = (JsonArray)JsonReader.read() + * + * + */ + @Test + public void readArrayTest5() throws Fault { + boolean pass = true; + JsonReader reader = null; + String resourceFile = "jsonArrayWithLotsOfNestedObjectsData.json"; + try { + System.out.println("Reading contents of resource file " + resourceFile); + String readerContents = JSONP_Util + .getContentsOfResourceAsString(resourceFile); + System.out.println("readerContents=" + readerContents); + + // Create expected JSON text from resource contents filtered of whitespace + // for comparison + System.out.println("Filter readerContents of whitespace for comparison"); + String expJsonText = JSONP_Util.removeWhitespace(readerContents); + + System.out.println( + "Read contents of InputStream from resource file: " + resourceFile); + reader = Json.createReaderFactory(JSONP_Util.getEmptyConfig()) + .createReader(JSONP_Util.getInputStreamFromResource(resourceFile), + JSONP_Util.UTF_8); + JsonArray myJsonArray = (JsonArray) reader.read(); + + System.out.println("Write the JsonArray 'myJsonArray' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeArray(myJsonArray); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String writerContents = sWriter.toString(); + + System.out.println("Dump contents of the JsonWriter as a String"); + System.out.println("writerContents=" + writerContents); + + System.out.println("Filter writerContents of whitespace for comparison"); + String actJsonText = JSONP_Util.removeWhitespace(writerContents); + + System.out.println("Compare actual JSON text with expected JSON text"); + pass = JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText); + } catch (Exception e) { + throw new Fault("readArrayTest5 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readArrayTest5 Failed"); + } + + /* + * @testName: readArrayEncodingTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:420; JSONP:JAVADOC:449; + * JSONP:JAVADOC:184; + * + * @test_Strategy: Test read of a JsonArray from a resource file using both + * encodings of UTF-8 and UTF-16BE. + * + * Test scenario: For each encoding read the appropriate resource file + * containing a string value. Call JsonArray.getJsonString() to get the value + * of the JsonString. Compare expected string with actual string for equality. + */ + @Test + public void readArrayEncodingTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + String expString = "a\u65e8\u452c\u8b9e\u6589\u5c57\u5217z"; + String resourceFileUTF8 = "jsonArrayUTF8.json"; + String resourceFileUTF16BE = "jsonArrayUTF16BE.json"; + Map config = JSONP_Util.getEmptyConfig(); + try { + System.out.println("Reading contents of resource file using UTF-8 encoding " + + resourceFileUTF8); + InputStream is = JSONP_Util.getInputStreamFromResource(resourceFileUTF8); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_8); + JsonArray jsonArray = reader.readArray(); + System.out.println("Comparing JsonArray values with expected results."); + String actString = jsonArray.getJsonString(0).getString(); + if (!JSONP_Util.assertEquals(expString, actString)) + pass = false; + } catch (Exception e) { + throw new Fault("readArrayEncodingTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + try { + System.out.println("Reading contents of resource file using UTF-16BE encoding " + + resourceFileUTF16BE); + InputStream is = JSONP_Util + .getInputStreamFromResource(resourceFileUTF16BE); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_16BE); + JsonArray jsonArray = reader.readArray(); + System.out.println("Comparing JsonArray values with expected results."); + String actString = jsonArray.getJsonString(0).getString(); + if (!JSONP_Util.assertEquals(expString, actString)) + pass = false; + } catch (Exception e) { + throw new Fault("readArrayEncodingTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readArrayEncodingTest Failed"); + } + + /* + * @testName: readObjectTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:185; + * + * @test_Strategy: Test read of an object containing various types from + * stream. Use JsonReader.readObject() API call. {"true":true, "false":false, + * "null":null, "booyah":"booyah", "int":2147483647, + * "long":9223372036854775807, "double":1.7976931348623157E308, + * "array":[true,false,null,"bingo",-2147483648,-9223372036854775808,4.9E-324] + * , "object":{"true":true,"false":false,"null":null,"bonga":"boo","int":1, + * "double":10.4} } Test scenario: Read string of JSON text above consisting + * of a JSON object into a JsonObject object. Create an expected map of + * JsonObject values for use in test comparison. Compare expected map of + * JsonObject values with actual map for equality. + * + */ + @Test + public void readObjectTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + String expJsonText = "{\"true\":true,\"false\":false,\"null\":null,\"booyah\":\"booyah\",\"int\":2147483647," + + "\"long\":9223372036854775807,\"double\":1.7976931348623157E308," + + "\"array\":[true,false,null,\"bingo\",-2147483648,-9223372036854775808,4.9E-324]," + + "\"object\":{\"true\":true,\"false\":false,\"null\":null,\"bonga\":\"boo\",\"int\":1," + + "\"double\":10.4}}"; + + System.out.println("Create the expected map of JsonObject values"); + Map expMap = new HashMap<>(); + expMap.put("true", JsonValue.TRUE); + expMap.put("false", JsonValue.FALSE); + expMap.put("null", JsonValue.NULL); + expMap.put("booyah", JSONP_Util.createJsonString("booyah")); + expMap.put("int", JSONP_Util.createJsonNumber(Integer.MAX_VALUE)); + expMap.put("long", JSONP_Util.createJsonNumber(Long.MAX_VALUE)); + expMap.put("double", JSONP_Util.createJsonNumber(Double.MAX_VALUE)); + JsonArray array = Json.createArrayBuilder().add(JsonValue.TRUE) + .add(JsonValue.FALSE).add(JsonValue.NULL).add("bingo") + .add(Integer.MIN_VALUE).add(Long.MIN_VALUE).add(Double.MIN_VALUE) + .build(); + JsonObject object = Json.createObjectBuilder().add("true", JsonValue.TRUE) + .add("false", JsonValue.FALSE).add("null", JsonValue.NULL) + .add("bonga", "boo").add("int", 1).add("double", 10.4).build(); + expMap.put("array", array); + expMap.put("object", object); + + System.out.println("Testing read of " + expJsonText); + reader = Json.createReader(new StringReader(expJsonText)); + JsonObject myJsonObject = reader.readObject(); + + Map actMap = myJsonObject; + System.out.println( + "Compare actual map of JsonObject values with expected map of JsonObject values"); + pass = JSONP_Util.assertEqualsMap(expMap, actMap); + } catch (Exception e) { + throw new Fault("readObjectTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readObjectTest Failed"); + } + + /* + * @testName: readObjectTest2 + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:178; JSONP:JAVADOC:185; + * + * @test_Strategy: Test read of an object containing various types from + * stream. Use JsonReader.readObject() API call. {"true":true, "false":false, + * "null":null, "booyah":"booyah", "int":2147483647, + * "long":9223372036854775807, "double":1.7976931348623157E308, + * "array":[true,false,null,"bingo",-2147483648,-9223372036854775808,4.9E-324] + * , "object":{"true":true,"false":false,"null":null,"bonga":"boo","int":1, + * "double":10.4} } Test Scenario: Create an expected JsonObject of the above + * JSON object for use in test comparison. Create a JsonWriter to write the + * above JsonObject to a string of JSON text. Next call JsonReader to read the + * JSON text from the JsonWriter to a JsonObject object. Compare expected + * JsonObject object with actual JsonObject object for equality. + * + */ + @Test + public void readObjectTest2() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + System.out.println("Create the expected list of JsonObject values"); + JsonObject expJsonObject = Json.createObjectBuilder() + .add("true", JsonValue.TRUE).add("false", JsonValue.FALSE) + .add("null", JsonValue.NULL).add("booyah", "booyah") + .add("int", Integer.MAX_VALUE).add("long", Long.MAX_VALUE) + .add("double", Double.MAX_VALUE) + .add("array", + Json.createArrayBuilder().add(JsonValue.TRUE).add(JsonValue.FALSE) + .add(JsonValue.NULL).add("bingo").add(Integer.MIN_VALUE) + .add(Long.MIN_VALUE).add(Double.MIN_VALUE)) + .add("object", + Json.createObjectBuilder().add("true", JsonValue.TRUE) + .add("false", JsonValue.FALSE).add("null", JsonValue.NULL) + .add("bonga", "boo").add("int", 1).add("double", 10.4)) + .build(); + + System.out.println("Write the JsonObject 'expJsonObject' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeObject(expJsonObject); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String jsonText = sWriter.toString(); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + jsonText); + + System.out.println("Testing read of " + jsonText); + reader = Json.createReader(JSONP_Util.getInputStreamFromString(jsonText)); + JsonObject actJsonObject = reader.readObject(); + + System.out.println("Compare expJsonObject and actJsonObject for equality"); + pass = JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject); + } catch (Exception e) { + throw new Fault("readObjectTest2 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readObjectTest2 Failed"); + } + + /* + * @testName: readObjectTest3 + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:185; JSONP:JAVADOC:419; + * JSONP:JAVADOC:449; + * + * @test_Strategy: Test read of an object containing various types from + * stream. Use JsonReader.readObject() API call. {"true":true, "false":false, + * "null":null, "booyah":"booyah", "int":2147483647, + * "long":9223372036854775807, + * "array":[true,false,null,"bingo",-2147483648,-9223372036854775808], + * "object":{"true":true,"false":false,"null":null,"bonga":"boo","int":1} } + * Test scenario: Read string of JSON text above consisting of a JSON object + * into a JsonObject object with an empty configuration. Create a JsonWriter + * to write the above JsonObject to a string of JSON text. Compare expected + * JSON text with actual JSON text for equality. + * + * Tests the following API's: JsonReader = + * Json.createReaderFactory(Map).createReader(Reader) JsonObject + * object = JsonReader.readObject() + * + * + */ + @Test + public void readObjectTest3() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + String expJsonText = "{\"true\":true,\"false\":false,\"null\":null,\"booyah\":\"booyah\",\"int\":2147483647,\"long\":9223372036854775807," + + "\"array\":[true,false,null,\"bingo\",-2147483648,-9223372036854775808]," + + "\"object\":{\"true\":true,\"false\":false,\"null\":null,\"bonga\":\"boo\",\"int\":1}}"; + + System.out.println("Testing read of " + expJsonText); + reader = Json.createReaderFactory(JSONP_Util.getEmptyConfig()) + .createReader(new StringReader(expJsonText)); + JsonObject myJsonObject = reader.readObject(); + + System.out.println("Write the JsonObject 'myJsonObject' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeObject(myJsonObject); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String actJsonText = sWriter.toString(); + + System.out.println("Compare actual JSON text with expected JSON text"); + pass = JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText); + } catch (Exception e) { + throw new Fault("readObjectTest3 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readObjectTest3 Failed"); + } + + /* + * @testName: readObjectTest4 + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:420; + * JSONP:JAVADOC:449; + * + * @test_Strategy: Test read of an object from a resource file with various + * amounts of data. Use JsonReader.readObject() API call. Test scenario: Read + * InputStream of JSON text containing a JSON object from resource file with + * various amounts of data use UTF-8 encoding. Create a JsonWriter to write + * above JsonObject to a string of JSON text. Re-read JsonWriter text back + * into a JsonObject Compare expected JSON object with actual JSON object for + * equality. + * + */ + @Test + public void readObjectTest4() throws Fault { + boolean pass = true; + JsonReader reader = null; + String resourceFile = "jsonObjectWithAllTypesOfData.json"; + try { + System.out.println( + "Read contents of InputStream from resource file: " + resourceFile); + Map config = JSONP_Util.getEmptyConfig(); + reader = Json.createReaderFactory(config).createReader( + JSONP_Util.getInputStreamFromResource(resourceFile), + JSONP_Util.UTF_8); + JsonObject expJsonObject = reader.readObject(); + + System.out.println("Dump of expJsonObject"); + JSONP_Util.dumpJsonObject(expJsonObject); + + System.out.println("Write the JsonObject 'expJsonObject' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeObject(expJsonObject); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String writerContents = sWriter.toString(); + + System.out.println("Create actJsonObject from read of writer contents: " + + writerContents); + reader = Json.createReader(new StringReader(writerContents)); + JsonObject actJsonObject = reader.readObject(); + + System.out.println("Dump of actJsonObject"); + JSONP_Util.dumpJsonObject(actJsonObject); + + System.out.println("Compare expJsonObject and actJsonObject for equality"); + pass = JSONP_Util.assertEqualsJsonObjects(expJsonObject, actJsonObject); + } catch (Exception e) { + throw new Fault("readObjectTest4 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readObjectTest4 Failed"); + } + + /* + * @testName: readObjectTest5 + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:181; + * JSONP:JAVADOC:420; JSONP:JAVADOC:449; + * + * @test_Strategy: Test read of an object from a resource file with lots of + * nesting. Use JsonReader.read() API call. Test scenario: Read InputStream of + * JSON text containing a JSON object from resource file with lots of nesting + * use UTF-8 encoding with empty configuration. Create a JsonWriter to write + * above JsonObject to a string of JSON text. Compare expected JSON text with + * actual JSON text for equality. Filter all text output to remove whitespace + * before comparison. + * + * Tests the following API's: JsonReader = + * Json.createReaderFactory(Map).createReader(InputStream, Charset) + * JsonReader.read() JsonObject object = (JsonObject)JsonReader.read() + * + * + */ + @Test + public void readObjectTest5() throws Fault { + boolean pass = true; + JsonReader reader = null; + String resourceFile = "jsonObjectWithLotsOfNestedObjectsData.json"; + try { + System.out.println("Reading contents of resource file " + resourceFile); + String readerContents = JSONP_Util + .getContentsOfResourceAsString(resourceFile); + System.out.println("readerContents=" + readerContents); + + // Create expected JSON text from resource contents filtered of whitespace + // for comparison + System.out.println("Filter readerContents of whitespace for comparison"); + String expJsonText = JSONP_Util.removeWhitespace(readerContents); + + System.out.println( + "Read contents of InputStream from resource file: " + resourceFile); + reader = Json.createReaderFactory(JSONP_Util.getEmptyConfig()) + .createReader(JSONP_Util.getInputStreamFromResource(resourceFile), + JSONP_Util.UTF_8); + JsonObject myJsonObject = (JsonObject) reader.read(); + + System.out.println("Write the JsonObject 'myJsonObject' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeObject(myJsonObject); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String writerContents = sWriter.toString(); + + System.out.println("Dump contents of the JsonWriter as a String"); + System.out.println("writerContents=" + writerContents); + + System.out.println("Filter writerContents of whitespace for comparison"); + String actJsonText = JSONP_Util.removeWhitespace(writerContents); + + System.out.println("Compare actual JSON text with expected JSON text"); + pass = JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText); + } catch (Exception e) { + throw new Fault("readObjectTest5 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readObjectTest5 Failed"); + } + + /* + * @testName: readObjectEncodingTest + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:420; JSONP:JAVADOC:185; + * JSONP:JAVADOC:449; + * + * @test_Strategy: Test read of a JsonObject from a resource file using both + * encodings of UTF-8 and UTF-16LE. + * + * Test scenario: For each encoding read the appropriate resource file + * containing a string value. Call JsonObject.getJsonString() to get the value + * of the JsonString. Compare expected string with actual string for equality. + */ + @Test + public void readObjectEncodingTest() throws Fault { + boolean pass = true; + JsonReader reader = null; + String expString = "a\u65e8\u452c\u8b9e\u6589\u5c57\u5217z"; + String resourceFileUTF8 = "jsonObjectUTF8.json"; + String resourceFileUTF16LE = "jsonObjectUTF16LE.json"; + try { + System.out.println("Reading contents of resource file using UTF-8 encoding " + + resourceFileUTF8); + InputStream is = JSONP_Util.getInputStreamFromResource(resourceFileUTF8); + Map config = JSONP_Util.getEmptyConfig(); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_8); + JsonObject jsonObject = reader.readObject(); + System.out.println("Comparing JsonObject values with expected results."); + String actString = jsonObject.getJsonString("unicodeChars").getString(); + if (!JSONP_Util.assertEquals(expString, actString)) + pass = false; + } catch (Exception e) { + throw new Fault("readObjectEncodingTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + try { + System.out.println("Reading contents of resource file using UTF-16LE encoding " + + resourceFileUTF16LE); + InputStream is = JSONP_Util + .getInputStreamFromResource(resourceFileUTF16LE); + Map config = JSONP_Util.getEmptyConfig(); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_16LE); + JsonObject jsonObject = reader.readObject(); + System.out.println("Comparing JsonObject values with expected results."); + String actString = jsonObject.getJsonString("unicodeChars").getString(); + if (!JSONP_Util.assertEquals(expString, actString)) + pass = false; + } catch (Exception e) { + throw new Fault("readObjectEncodingTest Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("readObjectEncodingTest Failed"); + } + + /* + * @testName: readUTFEncodedTests + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:420; JSONP:JAVADOC:185; + * JSONP:JAVADOC:449; + * + * @test_Strategy: Tests the JsonReader reader. Verifies READING of the + * JsonObject defined in resource files: + * + * jsonObjectEncodingUTF8.json jsonObjectEncodingUTF16.json + * jsonObjectEncodingUTF16LE.json jsonObjectEncodingUTF16BE.json + * jsonObjectEncodingUTF32LE.json jsonObjectEncodingUTF32BE.json + * + * Creates the JsonReader via the API: + * + * JsonReader reader = + * Json.createReaderFactory(Map).createReader(InputStream, Charset) + * + * For each supported encoding supported by JSON RFC read the JsonObject and + * verify we get the expected results. The Charset encoding is passed in as + * argument for each encoding type read. + */ + @Test + public void readUTFEncodedTests() throws Fault { + boolean pass = true; + JsonReader reader = null; + Map config = JSONP_Util.getEmptyConfig(); + try { + System.out.println( + "-----------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-8]"); + System.out.println( + "-----------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF8.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF8.json"); + System.out.println( + "Create JsonReader from the InputStream with character encoding UTF-8"); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_8); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-8 encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-16]"); + System.out.println( + "------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16.json"); + System.out.println( + "Create JsonReader from the InputStream with character encoding UTF-16"); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_16); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-16 encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-16LE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16LE.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16LE.json"); + System.out.println( + "Create JsonReader from the InputStream with character encoding UTF-16LE"); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_16LE); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-16LE encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-16BE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16BE.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16BE.json"); + System.out.println( + "Create JsonReader from the InputStream with character encoding UTF-16BE"); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_16BE); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-16BE encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-32LE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF32LE.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF32LE.json"); + System.out.println( + "Create JsonReader from the InputStream with character encoding UTF-32LE"); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_32LE); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-32LE encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createReaderFactory(Map).createReader(InputStream, Charset) as UTF-32BE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF32BE.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF32BE.json"); + System.out.println( + "Create JsonReader from the InputStream with character encoding UTF-32BE"); + reader = Json.createReaderFactory(config).createReader(is, + JSONP_Util.UTF_32BE); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-32BE encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("readUTFEncodedTests Failed"); + } + + /* + * @testName: readUTFEncodedTests2 + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:178; JSONP:JAVADOC:185; + * + * @test_Strategy: Tests the JsonReader reader. Verifies READING of the + * JsonObject defined in resource files: + * + * jsonObjectEncodingUTF8.json jsonObjectEncodingUTF16LE.json + * jsonObjectEncodingUTF16BE.json jsonObjectEncodingUTF32LE.json + * jsonObjectEncodingUTF32BE.json + * + * Creates the JsonReader via the API: + * + * JsonReader reader = Json.createReader(InputStream istream) + * + * For each supported encoding supported by JSON RFC read the JsonObject and + * verify we get the expected results. The character encoding of the stream is + * auto-detected and determined as per the RFC. + */ + @Test + public void readUTFEncodedTests2() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + System.out.println("---------------------------------------------------"); + System.out.println("TEST CASE [Json.createReader(InputStream) as UTF-8]"); + System.out.println("---------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF8.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF8.json"); + System.out.println( + "Create JsonReader from the InputStream and auto-detect character encoding UTF-8"); + reader = Json.createReader(is); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-8 encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + try { + System.out.println("------------------------------------------------------"); + System.out.println("TEST CASE [Json.createReader(InputStream) as UTF-16LE]"); + System.out.println("------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16LE.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16LE.json"); + System.out.println( + "Create JsonReader from the InputStream and auto-detect character encoding UTF-16LE"); + reader = Json.createReader(is); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-16LE encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + try { + System.out.println("------------------------------------------------------"); + System.out.println("TEST CASE [Json.createReader(InputStream) as UTF-16BE]"); + System.out.println("------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF16BE.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF16BE.json"); + System.out.println( + "Create JsonReader from the InputStream and auto-detect character encoding UTF-16BE"); + reader = Json.createReader(is); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-16BE encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + try { + System.out.println("------------------------------------------------------"); + System.out.println("TEST CASE [Json.createReader(InputStream) as UTF-32LE]"); + System.out.println("------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF32LE.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF32LE.json"); + System.out.println( + "Create JsonReader from the InputStream and auto-detect character encoding UTF-32LE"); + reader = Json.createReader(is); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-32LE encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + try { + System.out.println("------------------------------------------------------"); + System.out.println("TEST CASE [Json.createReader(InputStream) as UTF-32BE]"); + System.out.println("------------------------------------------------------"); + System.out.println( + "Get InputStream from data file as resource (jsonObjectEncodingUTF32BE.json)"); + InputStream is = JSONP_Util + .getInputStreamFromResource("jsonObjectEncodingUTF32BE.json"); + System.out.println( + "Create JsonReader from the InputStream and auto-detect character encoding UTF-32BE"); + reader = Json.createReader(is); + JsonObject jsonObject = reader.readObject(); + if (!compareJsonObjectForUTFEncodedTests(jsonObject)) + pass = false; + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing reading of UTF-32BE encoding: " + e); + } finally { + try { + if (reader != null) + reader.close(); + } catch (Exception e) { + } + } + if (!pass) + throw new Fault("readUTFEncodedTests2 Failed"); + } + + /* + * @testName: negativeObjectTests + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:413; + * + * @test_Strategy: Test various Json Syntax Errors when reading a JsonObject. + * The tests trip various JsonParsingException/JsonException conditions when + * reading an object. + * + */ + @Test + public void negativeObjectTests() throws Fault { + boolean pass = true; + JsonReader reader = null; + + // Not an object [] + + try { + System.out.println("Testing for not an object '[]'"); + reader = Json.createReader(new StringReader("[]")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonException"); + } catch (JsonException e) { + System.out.println("Got expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Trip JsonParsingException for JsonReader.readObject() if incorrect + // representation for object + try { + System.out.println( + "Trip JsonParsingException for JsonReader.read() if incorrect representation for object."); + System.out.println("Reading " + "{\"name\":\"value\",1,2,3}"); + reader = Json + .createReader(new StringReader("{\"name\":\"value\",1,2,3}")); + JsonObject jsonObject = reader.readObject(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Missing [ + + try { + System.out.println("Testing for missing '['"); + reader = Json.createReader(new StringReader("{1,2]}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing ] + + try { + System.out.println("Testing for missing ']'"); + reader = Json.createReader(new StringReader("{[1,2}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing { + + try { + System.out.println("Testing for missing '{'"); + reader = Json.createReader(new StringReader("}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing } + + try { + System.out.println("Testing for missing '}'"); + reader = Json.createReader(new StringReader("{")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between array elements test case 1 + + try { + System.out.println("Testing for missing ',' between array elements test case 1"); + reader = Json.createReader(new StringReader("{[5\"foo\"]}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between array elements test case 2 + + try { + System.out.println("Testing for missing ',' between array elements test case 2"); + reader = Json.createReader(new StringReader("{[5{}]}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between object elements test case 1 + + try { + System.out.println("Testing for missing ',' between object elements test case 1"); + reader = Json.createReader(new StringReader("{\"foo\":\"bar\"5}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between object elements test case 2 + + try { + System.out.println("Testing for missing ',' between object elements test case 2"); + reader = Json.createReader(new StringReader("{\"one\":1[]}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing key name in object element + + try { + System.out.println("Testing for missing key name in object element"); + reader = Json.createReader(new StringReader("{:\"bar\"}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing value name in object element + + try { + System.out.println("Testing for missing value name in object element"); + reader = Json.createReader(new StringReader("{\"foo\":}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing double quote on a name + + try { + System.out.println("Test for missing double quote on a name"); + reader = Json.createReader(new StringReader("{name\" : \"value\"}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing double quote on a value + + try { + System.out.println("Test for missing double quote on a value"); + reader = Json.createReader(new StringReader("{\"name\" : value\"}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 1 + + try { + System.out.println("Incorrect digit value -foo"); + reader = Json.createReader(new StringReader("{\"number\" : -foo}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 2 + + try { + System.out.println("Incorrect digit value +foo"); + reader = Json.createReader(new StringReader("{\"number\" : +foo}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 3 + + try { + System.out.println("Incorrect digit value -784foo"); + reader = Json.createReader(new StringReader("{\"number\" : -784foo}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 4 + + try { + System.out.println("Incorrect digit value +784foo"); + reader = Json.createReader(new StringReader("{\"number\" : +784foo}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 5 + + try { + System.out.println("Incorrect digit value 0.1E5E5"); + reader = Json.createReader(new StringReader("{\"number\" : 0.1E5E5}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 6 + + try { + System.out.println("Incorrect digit value 0.F10"); + reader = Json.createReader(new StringReader("{\"number\" : 0.F10}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 7 + + try { + System.out.println("Incorrect digit value string"); + reader = Json.createReader(new StringReader("{\"number\" : string}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 8 (hex numbers invalid per JSON RFC) + + try { + System.out.println("Incorrect digit value hex numbers invalid per JSON RFC"); + reader = Json.createReader(new StringReader("{\"number\" : 0x137a}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 9 (octal numbers invalid per JSON RFC) + + try { + System.out.println("Incorrect digit value octal numbers invalid per JSON RFC"); + reader = Json.createReader(new StringReader("{\"number\" : 0137}")); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + if (!pass) + throw new Fault("negativeObjectTests Failed"); + } + + /* + * @testName: negativeArrayTests + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:412; + * + * @test_Strategy: Test various Json Syntax Errors when reading a JsonArray. + * The tests trip various JsonParsingException/JsonException conditions when + * reading an array. + * + */ + @Test + public void negativeArrayTests() throws Fault { + boolean pass = true; + JsonReader reader = null; + + // Not an array {} + + try { + System.out.println("Testing for not an array '{}'"); + reader = Json.createReader(new StringReader("{}")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonException"); + } catch (JsonException e) { + System.out.println("Got expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Trip JsonParsingException for JsonReader.readArray() if incorrect + // representation for array + try { + System.out.println( + "Trip JsonParsingException for JsonReader.readArray() if incorrect representation for array."); + System.out.println("Reading " + "[foo,10,\"name\":\"value\"]"); + reader = Json + .createReader(new StringReader("[foo,10,\"name\":\"value\"]")); + JsonArray jsonArray = reader.readArray(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Missing [ + + try { + System.out.println("Testing for missing '['"); + reader = Json.createReader(new StringReader("]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing ] + + try { + System.out.println("Testing for missing ']'"); + reader = Json.createReader(new StringReader("[")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing { + + try { + System.out.println("Testing for missing '{'"); + reader = Json.createReader(new StringReader("[1,\"name\":\"value\"}]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing } + + try { + System.out.println("Testing for missing '}'"); + reader = Json.createReader(new StringReader("[1,{\"name\":\"value\"]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between array elements test case 1 + + try { + System.out.println("Testing for missing ',' between array elements test case 1"); + reader = Json.createReader(new StringReader("[5\"foo\"]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between array elements test case 2 + + try { + System.out.println("Testing for missing ',' between array elements test case 2"); + reader = Json.createReader(new StringReader("[5{}]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between object elements test case 1 + + try { + System.out.println("Testing for missing ',' between object elements test case 1"); + reader = Json.createReader(new StringReader("[{\"foo\":\"bar\"5}]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between object elements test case 2 + + try { + System.out.println("Testing for missing ',' between object elements test case 2"); + reader = Json.createReader(new StringReader("[{\"one\":1[]}]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing key name in object element + + try { + System.out.println("Testing for missing key name in object element"); + reader = Json.createReader(new StringReader("[{:\"bar\"}]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing value name in object element + + try { + System.out.println("Testing for missing value name in object element"); + reader = Json.createReader(new StringReader("[{\"foo\":}]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing double quote on a name + + try { + System.out.println("Test for missing double quote on a name"); + reader = Json.createReader(new StringReader("[{name\" : \"value\"}]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing double quote on a value + + try { + System.out.println("Test for missing double quote on a value"); + reader = Json.createReader(new StringReader("[{\"name\" : value\"}]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 1 + + try { + System.out.println("Incorrect digit value -foo"); + reader = Json.createReader(new StringReader("[-foo]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 2 + + try { + System.out.println("Incorrect digit value +foo"); + reader = Json.createReader(new StringReader("[+foo]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 3 + + try { + System.out.println("Incorrect digit value -784foo"); + reader = Json.createReader(new StringReader("[-784foo]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 4 + + try { + System.out.println("Incorrect digit value +784foo"); + reader = Json.createReader(new StringReader("[+784foo]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 5 + + try { + System.out.println("Incorrect digit value 0.1E5E5"); + reader = Json.createReader(new StringReader("[0.1E5E5]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 6 + + try { + System.out.println("Incorrect digit value 0.F10"); + reader = Json.createReader(new StringReader("[0.F10]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 7 + + try { + System.out.println("Incorrect digit value string"); + reader = Json.createReader(new StringReader("[string]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 8 (hex numbers invalid per JSON RFC) + + try { + System.out.println("Incorrect digit value hex numbers invalid per JSON RFC"); + reader = Json.createReader(new StringReader("[0x137a]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 9 (octal numbers invalid per JSON RFC) + + try { + System.out.println("Incorrect digit value octal numbers invalid per JSON RFC"); + reader = Json.createReader(new StringReader("[0137]")); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + if (!pass) + throw new Fault("negativeArrayTests Failed"); + } + + /* + * @testName: illegalStateExceptionTests + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:218; + * JSONP:JAVADOC:220; JSONP:JAVADOC:183; + * + * @test_Strategy: Test IllegalStateException test conditions. + * + */ + @Test + public void illegalStateExceptionTests() throws Fault { + boolean pass = true; + JsonReader reader = null; + + // IllegalStateException if reader.close() called before reader.read() + try { + reader = Json.createReader(new StringReader("{}")); + reader.close(); + System.out.println( + "Calling reader.read() after reader.close() is called is illegal."); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // IllegalStateException if reader.read() called after reader.readObject() + try { + reader = Json.createReader(new StringReader("{}")); + JsonObject value = reader.readObject(); + System.out.println( + "Calling reader.readObject() after reader.readObject() was called is illegal."); + value = (JsonObject) reader.read(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // IllegalStateException if reader.read() called after reader.readArray() + try { + reader = Json.createReader(new StringReader("[]")); + JsonArray value = reader.readArray(); + System.out.println( + "Calling reader.read() after reader.readArray() was called is illegal."); + value = (JsonArray) reader.read(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // IllegalStateException if reader.close() called before reader.readObject() + try { + reader = Json.createReader(new StringReader("{}")); + reader.close(); + System.out.println( + "Calling reader.readObject() after reader.close() is called is illegal."); + JsonObject value = reader.readObject(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // IllegalStateException if reader.readObject() called after + // reader.readObject() + try { + reader = Json.createReader(new StringReader("{}")); + JsonObject value = reader.readObject(); + System.out.println( + "Calling reader.readObject() after reader.readObject() was called is illegal."); + value = reader.readObject(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // IllegalStateException if reader.readArray() called after + // reader.readObject() + try { + reader = Json.createReader(new StringReader("{}")); + JsonObject obj = reader.readObject(); + System.out.println( + "Calling reader.readArray() after reader.readObject() was called is illegal."); + JsonArray arr = reader.readArray(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // IllegalStateException if reader.close() called before reader.readArray() + try { + reader = Json.createReader(new StringReader("[]")); + reader.close(); + System.out.println( + "Calling reader.readArray() after reader.close() is called is illegal."); + JsonArray value = reader.readArray(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // IllegalStateException if reader.readArray() called after + // reader.readArray() + try { + reader = Json.createReader(new StringReader("[]")); + JsonArray value = reader.readArray(); + System.out.println( + "Calling reader.readArray() after reader.readArray() was called is illegal."); + value = reader.readArray(); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // IllegalStateException if reader.readObject() called after + // reader.readArray() + try { + reader = Json.createReader(new StringReader("[]")); + JsonArray arr = reader.readArray(); + System.out.println( + "Calling reader.readObject() after reader.readArray() was called is illegal."); + JsonObject obj = reader.readObject(); + pass = false; + System.out.println("obj=" + obj); + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + if (!pass) + throw new Fault("illegalStateExceptionTests Failed"); + } + + /* + * @testName: negativeJsonStructureTests + * + * @assertion_ids: JSONP:JAVADOC:96; JSONP:JAVADOC:97; JSONP:JAVADOC:411; + * + * @test_Strategy: Test various Json Syntax Errors when reading a + * JsonStructure. The tests trip various JsonParsingException conditions when + * doing a read. + * + */ + @Test + public void negativeJsonStructureTests() throws Fault { + boolean pass = true; + JsonReader reader = null; + + // Trip JsonParsingException for JsonReader.read() if incorrect + // representation for array + try { + System.out.println( + "Trip JsonParsingException for JsonReader.read() if incorrect representation for array."); + System.out.println("Reading " + "[foo,10,\"name\":\"value\"]"); + reader = Json + .createReader(new StringReader("[foo,10,\"name\":\"value\"]")); + JsonStructure jsonStructure = reader.read(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonParsingException for JsonReader.read() if incorrect + // representation for object + try { + System.out.println( + "Trip JsonParsingException for JsonReader.read() if incorrect representation for object."); + System.out.println("Reading " + "{\"name\":\"value\",1,2,3}"); + reader = Json + .createReader(new StringReader("{\"name\":\"value\",1,2,3}")); + JsonStructure jsonStructure = reader.read(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // incorrect representation {] + try { + System.out.println("Testing for incorrect representation '{]'"); + reader = Json.createReader(new StringReader("{]")); + System.out.println( + "Calling reader.read() with incorrect representation should throw JsonParsingException"); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Missing [ + + try { + System.out.println("Testing for missing '['"); + reader = Json.createReader(new StringReader("{1,2]}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing ] + + try { + System.out.println("Testing for missing ']'"); + reader = Json.createReader(new StringReader("{[1,2}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing { + + try { + System.out.println("Testing for missing '{'"); + reader = Json.createReader(new StringReader("}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing } + + try { + System.out.println("Testing for missing '}'"); + reader = Json.createReader(new StringReader("{")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between array elements test case 1 + + try { + System.out.println("Testing for missing ',' between array elements test case 1"); + reader = Json.createReader(new StringReader("{[5\"foo\"]}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between array elements test case 2 + + try { + System.out.println("Testing for missing ',' between array elements test case 2"); + reader = Json.createReader(new StringReader("{[5{}]}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between object elements test case 1 + + try { + System.out.println("Testing for missing ',' between object elements test case 1"); + reader = Json.createReader(new StringReader("{\"foo\":\"bar\"5}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing , between object elements test case 2 + + try { + System.out.println("Testing for missing ',' between object elements test case 2"); + reader = Json.createReader(new StringReader("{\"one\":1[]}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing key name in object element + + try { + System.out.println("Testing for missing key name in object element"); + reader = Json.createReader(new StringReader("{:\"bar\"}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing value name in object element + + try { + System.out.println("Testing for missing value name in object element"); + reader = Json.createReader(new StringReader("{\"foo\":}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing double quote on a name + + try { + System.out.println("Test for missing double quote on a name"); + reader = Json.createReader(new StringReader("{name\" : \"value\"}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Missing double quote on a value + + try { + System.out.println("Test for missing double quote on a value"); + reader = Json.createReader(new StringReader("{\"name\" : value\"}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 1 + + try { + System.out.println("Incorrect digit value -foo"); + reader = Json.createReader(new StringReader("{\"number\" : -foo}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 2 + + try { + System.out.println("Incorrect digit value +foo"); + reader = Json.createReader(new StringReader("{\"number\" : +foo}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 3 + + try { + System.out.println("Incorrect digit value -784foo"); + reader = Json.createReader(new StringReader("{\"number\" : -784foo}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 4 + + try { + System.out.println("Incorrect digit value +784foo"); + reader = Json.createReader(new StringReader("{\"number\" : +784foo}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 5 + + try { + System.out.println("Incorrect digit value 0.1E5E5"); + reader = Json.createReader(new StringReader("{\"number\" : 0.1E5E5}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 6 + + try { + System.out.println("Incorrect digit value 0.F10"); + reader = Json.createReader(new StringReader("{\"number\" : 0.F10}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + // Incorrect digit value test case 7 + + try { + System.out.println("Incorrect digit value string"); + reader = Json.createReader(new StringReader("{\"number\" : string}")); + JsonStructure value = reader.read(); + pass = false; + System.err.println("Failed to throw JsonParsingException"); + } catch (JsonParsingException e) { + System.out.println("Got expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (reader != null) + reader.close(); + } + + if (!pass) + throw new Fault("negativeJsonStructureTests Failed"); + } + + /* + * @testName: jsonReaderIOErrorTests + * + * @assertion_ids: JSONP:JAVADOC:182; JSONP:JAVADOC:217; JSONP:JAVADOC:219; + * JSONP:JAVADOC:410; + * + * @test_Strategy: Tests for JsonException for testable i/o errors. + * + */ + @Test + public void jsonReaderIOErrorTests() throws Fault { + boolean pass = true; + + String jsonArrayText = "[\"name1\",\"value1\"]"; + String jsonObjectText = "{\"name1\":\"value1\"}"; + + // Trip JsonException if there is an i/o error on JsonReader.close() + try { + System.out.println( + "Trip JsonException if there is an i/o error on JsonReader.close()."); + System.out.println("Reading object " + jsonObjectText); + InputStream is = JSONP_Util.getInputStreamFromString(jsonObjectText); + MyBufferedInputStream mbi = new MyBufferedInputStream(is); + try (JsonReader reader = Json.createReader(mbi)) { + JsonObject jsonObject = reader.readObject(); + System.out.println("jsonObject=" + jsonObject); + mbi.setThrowIOException(true); + System.out.println("Calling JsonReader.close()"); + mbi.setThrowIOException(true); + } + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonException for JsonReader.read() if i/o error + try { + System.out.println("Trip JsonException for JsonReader.read() if i/o error."); + System.out.println("Reading array " + jsonArrayText); + MyBufferedReader mbr = new MyBufferedReader( + new StringReader(jsonArrayText)); + JsonReader reader = Json.createReader(mbr); + mbr.setThrowIOException(true); + System.out.println("Calling JsonReader.read()"); + JsonStructure jsonStructure = reader.read(); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonException for JsonReader.readArray() if i/o error + try { + System.out.println("Trip JsonException for JsonReader.readArray() if i/o error."); + System.out.println("Reading array " + jsonArrayText); + MyBufferedReader mbr = new MyBufferedReader( + new StringReader(jsonArrayText)); + JsonReader reader = Json.createReader(mbr); + mbr.setThrowIOException(true); + System.out.println("Calling JsonReader.readArray()"); + JsonArray jsonArray = reader.readArray(); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonException for JsonReader.readObject() if i/o error + try { + System.out.println("Trip JsonException for JsonReader.read() if i/o error."); + System.out.println("Reading object " + jsonObjectText); + MyBufferedReader mbr = new MyBufferedReader( + new StringReader(jsonObjectText)); + JsonReader reader = Json.createReader(mbr); + mbr.setThrowIOException(true); + System.out.println("Calling JsonReader.readObject()"); + JsonObject jsonObject = reader.readObject(); + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonReaderIOErrorTests Failed"); + } + + /* + * @testName: invalidLiteralNamesTest + * + * @assertion_ids: JSONP:JAVADOC:97; JSONP:JAVADOC:411; + * + * @test_Strategy: This test trips various JsonParsingException conditions + * when reading an uppercase literal name that must be lowercase per JSON RFC + * for the literal values (true, false or null). + * + */ + @Test + public void invalidLiteralNamesTest() throws Fault { + boolean pass = true; + JsonReader reader; + + // Trip JsonParsingException for JsonReader.read() if invalid liternal TRUE + // instead of true + try { + System.out.println( + "Trip JsonParsingException for JsonReader.read() if invalid liternal TRUE instead of true."); + System.out.println("Reading " + "[TRUE]"); + reader = Json.createReader(new StringReader("[TRUE]")); + JsonStructure jsonStructure = reader.read(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonParsingException for JsonReader.read() if invalid liternal FALSE + // instead of false + try { + System.out.println( + "Trip JsonParsingException for JsonReader.read() if invalid liternal FALSE instead of false."); + System.out.println("Reading " + "[FALSE]"); + reader = Json.createReader(new StringReader("[FALSE]")); + JsonStructure jsonStructure = reader.read(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonParsingException for JsonReader.read() if invalid liternal NULL + // instead of null + try { + System.out.println( + "Trip JsonParsingException for JsonReader.read() if invalid liternal NULL instead of null."); + System.out.println("Reading " + "[NULL]"); + reader = Json.createReader(new StringReader("[NULL]")); + JsonStructure jsonStructure = reader.read(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonParsingException for JsonReader.read() if invalid liternal TRUE + // instead of true + try { + System.out.println( + "Trip JsonParsingException for JsonReader.read() if invalid liternal TRUE instead of true."); + System.out.println("Reading " + "{\"true\":TRUE}"); + reader = Json.createReader(new StringReader("{\"true\":TRUE}")); + JsonStructure jsonStructure = reader.read(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonParsingException for JsonReader.read() if invalid liternal FALSE + // instead of false + try { + System.out.println( + "Trip JsonParsingException for JsonReader.read() if invalid liternal FALSE instead of false."); + System.out.println("Reading " + "{\"false\":FALSE}"); + reader = Json.createReader(new StringReader("{\"false\":FALSE}")); + JsonStructure jsonStructure = reader.read(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonParsingException for JsonReader.read() if invalid liternal NULL + // instead of null + try { + System.out.println( + "Trip JsonParsingException for JsonReader.read() if invalid liternal NULL instead of null."); + System.out.println("Reading " + "{\"null\":NULL}"); + reader = Json.createReader(new StringReader("{\"null\":NULL}")); + JsonStructure jsonStructure = reader.read(); + System.err.println("Did not get expected JsonParsingException"); + pass = false; + } catch (JsonParsingException e) { + System.out.println("Caught expected JsonParsingException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("invalidLiteralNamesTest Failed"); + } + + /* + * @testName: jsonReader11Test + * + * @assertion_ids: JSONP:JAVADOC:646; JSONP:JAVADOC:583; JSONP:JAVADOC:584; + * JSONP:JAVADOC:585; JSONP:JAVADOC:586; JSONP:JAVADOC:587; JSONP:JAVADOC:588; + * JSONP:JAVADOC:662; JSONP:JAVADOC:663; JSONP:JAVADOC:664; JSONP:JAVADOC:665; + * JSONP:JAVADOC:666; JSONP:JAVADOC:667; + * + * @test_Strategy: Tests JsonReader API methods added in JSON-P 1.1. + */ + @Test + public void jsonReader11Test() throws Fault { + Reader readerTest = new Reader(); + final TestResult result = readerTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonreadertests/Reader.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonreadertests/Reader.java new file mode 100644 index 00000000..e400ca25 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonreadertests/Reader.java @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonreadertests; + +import jakarta.jsonp.tck.api.common.JsonValueType; +import jakarta.jsonp.tck.api.common.SimpleValues; +import jakarta.jsonp.tck.api.common.TestResult; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringReader; +import jakarta.json.Json; +import jakarta.json.JsonException; +import jakarta.json.JsonReader; +import jakarta.json.JsonValue; +import jakarta.json.stream.JsonParsingException; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests for {@link JsonReader}. + */ +public class Reader { + + /** Tests input data. */ + private static final Object[] VALUES = new Object[] { OBJ_VALUE, // readValue() + // for + // JsonObject + createEmptyArrayWithStr(), // readValue() for simple JsonArray + STR_VALUE, // readValue() for String + INT_VALUE, // readValue() for int + LNG_VALUE, // readValue() for long + DBL_VALUE, // readValue() for double + BIN_VALUE, // readValue() for BigInteger + BDC_VALUE, // readValue() for BigDecimal + BOOL_VALUE, // readValue() for boolean + null // readValue() for null + }; + + /** + * Creates an instance of JavaScript Object Notation (JSON) compatibility + * tests for {@link JsonReader}. + */ + Reader() { + super(); + } + + /** + * {@link JsonReader} API methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonReader API methods added in JSON-P 1.1."); + System.out.println("JsonReader API methods added in JSON-P 1.1."); + testReadValue(result); + testDoubleReadValue(result); + testIOExceptionOnReadValue(result); + testReadInvalidValue(result); + return result; + } + + /** + * Test {@code JsonValue readValue()} method on all child types stored in + * source data. + * + * @param result + * Test suite result. + */ + private void testReadValue(final TestResult result) { + for (Object value : VALUES) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println(" - readValue() for " + typeName + " in source data"); + final JsonValue jsonValue = SimpleValues.toJsonValue(value); + final String data = JsonValueType.toStringValue(value); + System.out.println(" - Data: " + data); + final StringReader strReader = new StringReader(data); + JsonValue outValue = null; + try (final JsonReader reader = Json.createReader(strReader)) { + outValue = reader.readValue(); + } catch (JsonException ex) { + System.out.println("Caught JsonException: " + ex.getLocalizedMessage()); + result.fail("readValue()", + "Caught JsonException: " + ex.getLocalizedMessage()); + } + if (operationFailed(jsonValue, outValue)) { + result.fail("readValue()", "Reader output " + valueToString(outValue) + + " value shall be " + valueToString(jsonValue)); + } + } + } + + /** + * Test {@code JsonValue readValue()} method with duplicated {@code JsonValue} + * read call. Second call is expected to throw {@code IllegalStateException} + * exception. + * + * @param result + * Test suite result. + */ + private void testDoubleReadValue(final TestResult result) { + for (Object value : VALUES) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println( + " - duplicate readValue() for " + typeName + " in source data"); + final String data = JsonValueType.toStringValue(value); + final StringReader strReader = new StringReader(data); + try (final JsonReader reader = Json.createReader(strReader)) { + // 1st attempt to read the data shall pass + reader.readValue(); + try { + // 2nd attempt to read the data shall throw IllegalStateException + reader.readValue(); + result.fail("readValue()", + "Duplicate call of readValue() shall throw IllegalStateException"); + } catch (IllegalStateException ex) { + System.out.println(" - Expected exception: " + ex.getMessage()); + } catch (Throwable t) { + result.fail("readValue()", + "Duplicate call of readValue() shall throw IllegalStateException, not " + + t.getClass().getSimpleName()); + } + } catch (JsonException ex) { + System.out.println("Caught JsonException: " + ex.getLocalizedMessage()); + result.fail("readValue()", + "Caught JsonException: " + ex.getLocalizedMessage()); + } + } + } + + /** + * Test {@code JsonValue readValue()} method with read call that causes + * IOException. IOException shall be encapsulated in JsonException. + * + * @param result + * Test suite result. + */ + @SuppressWarnings("ConvertToTryWithResources") + private void testIOExceptionOnReadValue(final TestResult result) { + System.out.println(" - readValue() from already closed file reader"); + File temp = null; + JsonReader reader; + // Close writer before calling write method. + try { + temp = File.createTempFile("testIOExceptionOnReadValue", ".txt"); + System.out.println(" - Temporary file: " + temp.getAbsolutePath()); + try (final FileWriter fileWriter = new FileWriter(temp)) { + fileWriter.write(JsonValueType.toStringValue(DEF_VALUE)); + } + final FileReader fileReader = new FileReader(temp); + reader = Json.createReader(fileReader); + fileReader.close(); + } catch (IOException ex) { + System.out.println("Caught IOException: " + ex.getLocalizedMessage()); + result.fail("write(JsonValue)", + "Caught IOException: " + ex.getLocalizedMessage()); + return; + } finally { + if (temp != null) { + temp.delete(); + } + } + try { + reader.readValue(); + result.fail("readValue()", + "Call of readValue() on already closed file reader shall throw JsonException"); + } catch (JsonException ex) { + System.out.println(" - Expected exception: " + ex.getMessage()); + } catch (Throwable t) { + result.fail("readValue()", + "Call of readValue() on already closed file reader shall throw JsonException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Test {@code JsonValue readValue()} method with read call on invalid JSON + * data. JsonParsingException shall be thrown when reading invalid data. + * + * @param result + * Test suite result. + */ + private void testReadInvalidValue(final TestResult result) { + System.out.println(" - readValue() on invalid JSON data"); + // Invalid JSON: starting an array, closing an object. + final String data = "[" + SimpleValues.toJsonValue(DEF_VALUE) + "}"; + final StringReader strReader = new StringReader(data); + JsonValue outValue = null; + try (final JsonReader reader = Json.createReader(strReader)) { + reader.readValue(); + result.fail("readValue()", + "Call of readValue() on invalid data shall throw JsonParsingException"); + } catch (JsonParsingException ex) { + System.out.println(" - Expected exception: " + ex.getMessage()); + } catch (Throwable t) { + result.fail("readValue()", + "Call of readValue() on invalid data shall throw JsonParsingException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonstreamingtests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonstreamingtests/ClientTests.java new file mode 100644 index 00000000..188e46db --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonstreamingtests/ClientTests.java @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonstreamingtests; + +import jakarta.json.*; +import jakarta.json.stream.*; + +import java.io.*; +import java.util.*; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* + * @testName: streamingTest1 + * + * @assertion_ids: JSONP:JAVADOC:97; JSONP:JAVADOC:106; JSONP:JAVADOC:107; + * JSONP:JAVADOC:184; + * + * @test_Strategy: Test Scenario: Generate stream of Json Text containing a + * JsonArray Compare actual Json Text generated with expected Json Text for + * equality Test passes if both JsonArray comparisons of Json Text are equal. + * + */ + @Test + public void streamingTest1() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + // Set expected result + String expJsonText = "[1,2,3,4,5,6,7,8,9,10]"; + System.out.println("expJsonText=" + expJsonText); + + System.out.println("Generate stream of Json Text containing a JsonArray"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write(1).write(2).write(3).write(4).write(5) + .write(6).write(7).write(8).write(9).write(10).writeEnd(); + generator.close(); + + // Get actual result + String actJsonText = JSONP_Util.removeWhitespace(sWriter.toString()); + System.out.println("actJsonText=" + actJsonText); + + System.out.println("Compare expJsonText and actJsonText for equality"); + pass = JSONP_Util.assertEqualsJsonText(expJsonText, actJsonText); + } catch (Exception e) { + throw new Fault("streamingTest1 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("streamingTest1 Failed"); + } + + /* + * @testName: streamingTest2 + * + * @assertion_ids: JSONP:JAVADOC:97; JSONP:JAVADOC:106; JSONP:JAVADOC:107; + * JSONP:JAVADOC:131; + * + * @test_Strategy: Test Scenario: Generate data containing a JsonArray to a + * Writer stream. Read data from Writer stream containing a JsonArray. Write + * JsonArray out to a Writer stream. Re-read data from Writer stream + * containing a JsonArray. Compare initial JsonArray with subsequent JsonArray + * for equality. Test passes if both JsonArrays are equal. + * + */ + @Test + public void streamingTest2() throws Fault { + boolean pass = true; + JsonReader reader = null; + try { + System.out.println("Generate data containing a JsonArray"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartArray().write(2).write(4).write(6).write(8).write(10) + .writeEnd(); + generator.close(); + + System.out.println("Read data from Writer stream containing a JsonArray"); + reader = Json.createReader(new StringReader(sWriter.toString())); + JsonArray expJsonArray = reader.readArray(); + + System.out.println("Dump of expJsonArray"); + JSONP_Util.dumpJsonArray(expJsonArray); + + System.out.println("Write JsonArray out to a Writer stream"); + sWriter = new StringWriter(); + JsonWriter writer = Json.createWriter(sWriter); + writer.writeArray(expJsonArray); + System.out.println("Close JsonWriter"); + writer.close(); + + System.out.println("Save contents of the JsonWriter as a String"); + String writerContents = sWriter.toString(); + System.out.println("writerContents=" + writerContents); + + System.out.println("Re-read data from Writer stream containing a JsonArray"); + reader = Json.createReader(new StringReader(writerContents)); + JsonArray actJsonArray = reader.readArray(); + + System.out.println("Dump of actJsonArray"); + JSONP_Util.dumpJsonArray(actJsonArray); + + System.out.println("Compare expJsonArray and actJsonArray for equality"); + pass = JSONP_Util.assertEqualsJsonArrays(expJsonArray, actJsonArray); + } catch (Exception e) { + throw new Fault("streamingTest2 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("streamingTest2 Failed"); + } + + /* + * @testName: streamingTest3 + * + * @assertion_ids: JSONP:JAVADOC:97; JSONP:JAVADOC:106; JSONP:JAVADOC:110; + * JSONP:JAVADOC:131; JSONP:JAVADOC:172; + * + * @test_Strategy: Test Scenario: Generate data containing a JsonObject to a + * Write stream. Read data from Writer stream containing a JsonObject. Write + * JsonObject out to a Writer stream. Parse data from Writer stream containing + * a JsonObject stream. Test passes if parsing JsonObject events are correct. + * + */ + @Test + public void streamingTest3() throws Fault { + boolean pass = true; + JsonReader reader = null; + JsonParser parser = null; + try { + System.out.println("Generate data containing a JsonObject"); + StringWriter sWriter = new StringWriter(); + JsonGenerator generator = Json.createGenerator(sWriter); + generator.writeStartObject().write("two", 2).write("false", false) + .writeEnd(); + generator.close(); + + System.out.println("Read data from Writer stream containing a JsonObject"); + reader = Json.createReader(new StringReader(sWriter.toString())); + JsonObject expJsonObject = reader.readObject(); + + System.out.println("Dump of expJsonObject"); + JSONP_Util.dumpJsonObject(expJsonObject); + + System.out.println("Write JsonObject out to a Writer stream"); + sWriter = new StringWriter(); + JsonWriter writer = Json.createWriter(sWriter); + writer.writeObject(expJsonObject); + System.out.println("Close JsonWriter"); + writer.close(); + + System.out.println("Save contents of the JsonWriter as a String"); + String writerContents = sWriter.toString(); + System.out.println("writerContents=" + writerContents); + + System.out.println("Parse data from Writer stream containing a JsonObject"); + parser = Json + .createParser(JSONP_Util.getInputStreamFromString((writerContents))); + + JSONP_Util.resetParseErrs(); + JSONP_Util.testEventType(parser, JsonParser.Event.START_OBJECT); + JSONP_Util.testKeyIntegerValue(parser, "two", 2); + JSONP_Util.testKeyFalseValue(parser, "false"); + JSONP_Util.testEventType(parser, JsonParser.Event.END_OBJECT); + int parseErrs = JSONP_Util.getParseErrs(); + if (parseErrs != 0) { + System.err.println("There were " + parseErrs + " parser errors that occurred."); + pass = false; + } + + } catch (Exception e) { + throw new Fault("streamingTest3 Failed: ", e); + } finally { + if (reader != null) + reader.close(); + } + if (!pass) + throw new Fault("streamingTest3 Failed"); + } + + /* + * @testName: streamingTest4 + * + * @assertion_ids: JSONP:JAVADOC:178; JSONP:JAVADOC:187; JSONP:JAVADOC:110; + * JSONP:JAVADOC:168; + * + * @test_Strategy: Test Scenario: Generate data containing a JsonObject to an + * OutputStream. Compare expected JSON text from what was generated. Read data + * from InputStream containing a JsonObject. Write JsonObject again out to an + * OutputStream. Compare again expected JSON text from what was generated. + * Test passes if JSON text comparisons are correct. + * + */ + @Test + public void streamingTest4() throws Fault { + boolean pass = true; + JsonReader reader = null; + JsonParser parser = null; + String expJsonText = "{\"two\":2,\"false\":false}"; + try { + System.out.println("Generate data containing a JsonObject to an OutputStream"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonGenerator generator = Json.createGenerator(baos); + generator.writeStartObject().write("two", 2).write("false", false) + .writeEnd(); + baos.close(); + generator.close(); + + System.out.println("Compare JSON text generated to what is expected."); + if (!JSONP_Util.assertEqualsJsonText(expJsonText, + JSONP_Util.removeWhitespace(baos.toString("UTF-8")))) + pass = false; + + System.out.println("Read data from InputStream containing a JsonObject"); + reader = Json.createReader( + JSONP_Util.getInputStreamFromString(baos.toString("UTF-8"))); + JsonObject expJsonObject = reader.readObject(); + System.out.println("Close JsonReader"); + reader.close(); + + System.out.println("Dump of expJsonObject"); + JSONP_Util.dumpJsonObject(expJsonObject); + + System.out.println("Write JsonObject back out to an OutputStream"); + baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriter(baos); + writer.writeObject(expJsonObject); + System.out.println("Close JsonWriter"); + baos.close(); + writer.close(); + + System.out.println("Save contents of the JsonWriter as a String"); + String writerContents = baos.toString("UTF-8"); + System.out.println("writerContents=" + writerContents); + + System.out.println("Compare again JSON text generated to what is expected."); + if (!JSONP_Util.assertEqualsJsonText(expJsonText, + JSONP_Util.removeWhitespace(writerContents))) + pass = false; + + } catch (Exception e) { + throw new Fault("streamingTest4 Failed: ", e); + } + + if (!pass) + throw new Fault("streamingTest4 Failed"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonstringtests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonstringtests/ClientTests.java new file mode 100644 index 00000000..06672ca2 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonstringtests/ClientTests.java @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonstringtests; + +import jakarta.json.*; +import jakarta.json.stream.*; + +import java.io.*; + +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.List; +import java.util.Iterator; +import java.util.ArrayList; +import java.math.BigDecimal; +import java.math.BigInteger; + +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonStringEqualsTest + * + * @assertion_ids: JSONP:JAVADOC:254; + * + * @test_Strategy: Tests JsonString equals method. Create 2 equal JsonStrings + * and compare them for equality and expect true. Create 2 non-equal + * JsonStrings and compare them for equality and expect false. + */ + @Test + public void jsonStringEqualsTest() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonString 1 for testing"); + JsonString string1 = (JsonString) JSONP_Util + .createJsonString("Hello World"); + System.out.println("string1=" + JSONP_Util.toStringJsonString(string1)); + + System.out.println("Create sample JsonString 2 for testing"); + JsonString string2 = JSONP_Util.createJsonString("Hello World"); + System.out.println("string2=" + JSONP_Util.toStringJsonString(string2)); + + System.out.println( + "Call JsonString.equals() to compare 2 equal JsonStrings and expect true"); + if (string1.equals(string2)) { + System.out.println("JsonStrings are equal - expected."); + } else { + pass = false; + System.err.println("JsonStrings are not equal - unexpected."); + } + + System.out.println("Create sample JsonString 1 for testing"); + string1 = JSONP_Util.createJsonString("Hello World"); + System.out.println("string1=" + JSONP_Util.toStringJsonString(string1)); + + System.out.println("Create sample JsonString 2 for testing"); + string2 = JSONP_Util.createJsonString("Hello USA"); + System.out.println("string2=" + JSONP_Util.toStringJsonString(string2)); + + System.out.println( + "Call JsonString.equals() to compare 2 equal JsonStrings and expect false"); + if (!string1.equals(string2)) { + System.out.println("JsonStrings are not equal - expected."); + } else { + pass = false; + System.err.println("JsonStrings are equal - unexpected."); + } + } catch (Exception e) { + throw new Fault("jsonStringEqualsTest Failed: ", e); + } + if (!pass) + throw new Fault("jsonStringEqualsTest Failed"); + } + + /* + * @testName: jsonStringHashCodeTest + * + * @assertion_ids: JSONP:JAVADOC:255; + * + * @test_Strategy: Tests JsonString equals method. Create 2 equal JsonStrings + * and compare them for hashcode and expect true. Create 2 non-equal + * JsonStrings and compare them for hashcode and expect false. + */ + @Test + public void jsonStringHashCodeTest() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonString 1 for testing"); + JsonString string1 = JSONP_Util.createJsonString("Hello World"); + System.out.println("string1=" + JSONP_Util.toStringJsonString(string1)); + System.out.println("string1.hashCode()=" + string1.hashCode()); + + System.out.println("Create sample JsonString 2 for testing"); + JsonString string2 = JSONP_Util.createJsonString("Hello World"); + System.out.println("string2=" + JSONP_Util.toStringJsonString(string2)); + System.out.println("string2.hashCode()=" + string2.hashCode()); + + System.out.println( + "Call JsonString.hashCode() to compare 2 equal JsonStrings and expect true"); + if (string1.hashCode() == string2.hashCode()) { + System.out.println("JsonStrings hashCode are equal - expected."); + } else { + pass = false; + System.err.println("JsonStrings hashCode are not equal - unexpected."); + } + + System.out.println("Create sample JsonString 1 for testing"); + string1 = JSONP_Util.createJsonString("Hello World"); + System.out.println("string1=" + JSONP_Util.toStringJsonString(string1)); + System.out.println("string1.hashCode()=" + string1.hashCode()); + + System.out.println("Create sample JsonString 2 for testing"); + string2 = JSONP_Util.createJsonString("Hello USA"); + System.out.println("string2=" + JSONP_Util.toStringJsonString(string2)); + System.out.println("string2.hashCode()=" + string2.hashCode()); + + System.out.println( + "Call JsonString.hashCode() to compare 2 equal JsonStrings and expect false"); + if (string1.hashCode() != string2.hashCode()) { + System.out.println("JsonStrings hashCode are not equal - expected."); + } else { + pass = false; + System.err.println("JsonStrings hashCode are equal - unexpected."); + } + } catch (Exception e) { + throw new Fault("jsonStringHashCodeTest Failed: ", e); + } + if (!pass) + throw new Fault("jsonStringHashCodeTest Failed"); + } + + /* + * @testName: jsonStringGetCharsTest + * + * @assertion_ids: JSONP:JAVADOC:383; + * + * @test_Strategy: Tests JsonString getChars method. + */ + @Test + public void jsonStringGetCharsTest() throws Fault { + boolean pass = true; + String helloWorld = "Hello World"; + + try { + System.out.println("Create sample JsonString for testing"); + JsonString string = JSONP_Util.createJsonString(helloWorld); + System.out.println("string=" + JSONP_Util.toStringJsonString(string)); + + System.out.println( + "Call JsonString.getChars() to return the char sequence for the JSON string"); + CharSequence cs = string.getChars(); + System.out.println("charSequence=" + cs.toString()); + + System.out.println("Checking char sequence for equality to expected string contents"); + if (!JSONP_Util.assertEquals(helloWorld, cs.toString())) + pass = false; + + System.out.println("Checking char sequence for expected equality to string length"); + if (!JSONP_Util.assertEquals(helloWorld.length(), cs.length())) + pass = false; + } catch (Exception e) { + throw new Fault("jsonStringGetCharsTest Failed: ", e); + } + if (!pass) + throw new Fault("jsonStringGetCharsTest Failed"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonvaluetests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonvaluetests/ClientTests.java new file mode 100644 index 00000000..7f60a54b --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonvaluetests/ClientTests.java @@ -0,0 +1,354 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonvaluetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +import java.util.*; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.json.*; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonValueTypesTest + * + * @assertion_ids: JSONP:JAVADOC:102; + * + * @test_Strategy: Test JsonValue.getValueType() API method call with all + * JsonValue types. + * + */ + @Test + public void jsonValueTypesTest() throws Fault { + boolean pass = true; + try { + + JsonValue.ValueType valueType; + + // Testing JsonValue.FALSE case + System.out.println("Testing getValueType for JsonValue.FALSE value"); + valueType = JsonValue.FALSE.getValueType(); + if (valueType != JsonValue.ValueType.FALSE) { + System.err.println("Expected JSON FALSE value type but got instead " + valueType); + pass = false; + } else + System.out.println("Got expected value type for JSON FALSE value"); + + // Testing JsonValue.TRUE case + System.out.println("Testing getValueType for JsonValue.TRUE value"); + valueType = JsonValue.TRUE.getValueType(); + if (valueType != JsonValue.ValueType.TRUE) { + System.err.println("Expected JSON TRUE value type but got instead " + valueType); + pass = false; + } else + System.out.println("Got expected value type for JSON TRUE value"); + + // Testing JsonValue.NULL case + System.out.println("Testing getValueType for JsonValue.NULL value"); + valueType = JsonValue.NULL.getValueType(); + if (valueType != JsonValue.ValueType.NULL) { + System.err.println("Expected JSON NULL value type but got instead " + valueType); + pass = false; + } else + System.out.println("Got expected value type for JSON NULL value"); + + // Testing JsonValue.String case + System.out.println("Testing getValueType for JsonValue.String value"); + valueType = JSONP_Util.createJsonString("string").getValueType(); + if (valueType != JsonValue.ValueType.STRING) { + System.err.println("Expected JSON STRING value type but got instead " + valueType); + pass = false; + } else + System.out.println("Got expected value type for JSON STRING value"); + + // Testing JsonValue.Number case + System.out.println("Testing getValueType for JsonValue.Number value"); + valueType = JSONP_Util.createJsonNumber(Integer.MAX_VALUE).getValueType(); + if (valueType != JsonValue.ValueType.NUMBER) { + System.err.println("Expected JSON NUMBER value type but got instead " + valueType); + pass = false; + } else + System.out.println("Got expected value type for JSON NUMBER value"); + + // Testing JsonValue.Array case + System.out.println("Testing getValueType for JsonValue.Array value"); + valueType = JSONP_Util.createJsonArrayFromString("[]").getValueType(); + if (valueType != JsonValue.ValueType.ARRAY) { + System.err.println("Expected JSON ARRAY value type but got instead " + valueType); + pass = false; + } else + System.out.println("Got expected value type for JSON ARRAY value"); + + // Testing JsonValue.Object case + System.out.println("Testing getValueType for JsonValue.Object value"); + valueType = JSONP_Util.createJsonObjectFromString("{}").getValueType(); + if (valueType != JsonValue.ValueType.OBJECT) { + System.err.println("Expected JSON OBJECT value type but got instead " + valueType); + pass = false; + } else + System.out.println("Got expected value type for JSON OBJECT value"); + + } catch (Exception e) { + throw new Fault("jsonValueTypesTest Failed: ", e); + } + if (!pass) + throw new Fault("jsonValueTypesTest Failed"); + } + + /* + * @testName: jsonValueOfTest + * + * @assertion_ids: JSONP:JAVADOC:103; + * + * @test_Strategy: Test JsonValue.ValueType.valueOf() API method call with all + * JsonValue types. + * + */ + @Test + public void jsonValueOfTest() throws Fault { + boolean pass = true; + + String valueTypeStrings[] = { "ARRAY", "FALSE", "NULL", "NUMBER", "OBJECT", + "STRING", "TRUE" }; + + for (String valueTypeString : valueTypeStrings) { + JsonValue.ValueType valueType; + try { + System.out.println( + "Testing enum value for string constant name " + valueTypeString); + valueType = JsonValue.ValueType.valueOf(valueTypeString); + System.out.println("Got enum type " + valueType + " for enum string constant named " + + valueTypeString); + } catch (Exception e) { + System.err.println("Caught unexpected exception: " + e); + pass = false; + } + + } + + System.out.println("Testing negative test case for NullPointerException"); + try { + JsonValue.ValueType.valueOf(null); + System.err.println("did not get expected NullPointerException"); + pass = false; + } catch (NullPointerException e) { + System.out.println("Got expected NullPointerException"); + } catch (Exception e) { + System.err.println("Got unexpected exception " + e); + pass = false; + } + + System.out.println("Testing negative test case for IllegalArgumentException"); + try { + JsonValue.ValueType.valueOf("INVALID"); + System.err.println("did not get expected IllegalArgumentException"); + pass = false; + } catch (IllegalArgumentException e) { + System.out.println("Got expected IllegalArgumentException"); + } catch (Exception e) { + System.err.println("Got unexpected exception " + e); + pass = false; + } + + if (!pass) + throw new Fault("jsonValueOfTest Failed"); + } + + /* + * @testName: jsonValuesTest + * + * @assertion_ids: JSONP:JAVADOC:104; + * + * @test_Strategy: Test JsonValue.ValueType.values() API method call and + * verify enums returned. + * + */ + @Test + public void jsonValuesTest() throws Fault { + boolean pass = true; + + System.out.println( + "Testing API method JsonValue.ValueType.values() to return array of enums."); + JsonValue.ValueType[] values = JsonValue.ValueType.values(); + + for (JsonValue.ValueType valueType : values) { + String valueString = JSONP_Util.getValueTypeString(valueType); + if (valueString == null) { + System.err.println("Got no value for enum " + valueType); + pass = false; + } else + System.out.println("Got " + valueString + " for enum " + valueType); + } + + if (!pass) + throw new Fault("jsonValuesTest Failed"); + } + + /* + * @testName: jsonValueToStringTest + * + * @assertion_ids: JSONP:JAVADOC:288; + * + * @test_Strategy: Test JsonValue.toString() API method call with various + * JsonValue types. + * + */ + @Test + public void jsonValueToStringTest() throws Fault { + boolean pass = true; + try { + String stringValue; + JsonValue jsonValue; + + // Testing JsonValue.FALSE case + System.out.println("Testing JsonValue.toString() for JsonValue.FALSE value"); + stringValue = JsonValue.FALSE.toString(); + System.out.println("stringValue=" + stringValue); + if (!stringValue.equals("false")) { + System.err.println("Expected false"); + pass = false; + } else { + System.out.println("Got " + stringValue); + } + + // Testing JsonValue.TRUE case + System.out.println("Testing JsonValue.toString() for JsonValue.TRUE value"); + stringValue = JsonValue.TRUE.toString(); + System.out.println("stringValue=" + stringValue); + if (!stringValue.equals("true")) { + System.err.println("Expected true"); + pass = false; + } else { + System.out.println("Got " + stringValue); + } + + // Testing JsonValue.NULL case + System.out.println("Testing JsonValue.toString() for JsonValue.NULL value"); + stringValue = JsonValue.NULL.toString(); + System.out.println("stringValue=" + stringValue); + if (!stringValue.equals("null")) { + System.err.println("Expected null"); + pass = false; + } else { + System.out.println("Got " + stringValue); + } + + // Testing JsonString case + System.out.println("Testing JsonValue.toString() for JsonString value"); + jsonValue = JSONP_Util.createJsonString("string"); + stringValue = jsonValue.toString(); + System.out.println("stringValue=" + stringValue); + if (!stringValue.equals("\"string\"")) { + System.err.println("Expected \"string\""); + pass = false; + } else { + System.out.println("Got " + stringValue); + } + + // Testing JsonNumber case + System.out.println("Testing JsonValue.toString() for JsonNumber value"); + jsonValue = JSONP_Util.createJsonNumber(10); + stringValue = jsonValue.toString(); + System.out.println("stringValue=" + stringValue); + if (!stringValue.equals("10")) { + System.err.println("Expected 10"); + pass = false; + } else { + System.out.println("Got " + stringValue); + } + + // Testing JsonArray case + System.out.println("Testing JsonValue.toString() for JsonArray value"); + jsonValue = JSONP_Util.createJsonArrayFromString("[]"); + stringValue = jsonValue.toString(); + System.out.println("stringValue=" + stringValue); + if (!stringValue.equals("[]")) { + System.err.println("Expected []"); + pass = false; + } else { + System.out.println("Got " + stringValue); + } + + // Testing JsonObject case + System.out.println("Testing JsonValue.toString() for JsonObject value"); + jsonValue = JSONP_Util.createJsonObjectFromString("{}"); + stringValue = jsonValue.toString(); + System.out.println("stringValue=" + stringValue); + if (!stringValue.equals("{}")) { + System.err.println("Expected {}"); + pass = false; + } else { + System.out.println("Got " + stringValue); + } + + } catch (Exception e) { + throw new Fault("jsonValueToStringTest Failed: ", e); + } + if (!pass) + throw new Fault("jsonValueToStringTest Failed"); + } + + /* + * @testName: jsonValue11Test + * + * @assertion_ids: JSONP:JAVADOC:648; JSONP:JAVADOC:649; + * + * @test_Strategy: Tests JsonValue API methods added in JSON-P 1.1. + */ + @Test + public void jsonValue11Test() throws Fault { + Value valueTest = new Value(); + final TestResult result = valueTest.test(); + result.eval(); + } + + /* + * @testName: jsonStructure11Test + * + * @assertion_ids: JSONP:JAVADOC:647; + * + * @test_Strategy: Tests JsonStructure API methods added in JSON-P 1.1. + */ + @Test + public void jsonStructure11Test() throws Fault { + Structure structTest = new Structure(); + final TestResult result = structTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonvaluetests/Structure.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonvaluetests/Structure.java new file mode 100644 index 00000000..629dd3ef --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonvaluetests/Structure.java @@ -0,0 +1,485 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonvaluetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonException; +import jakarta.json.JsonObject; +import jakarta.json.JsonStructure; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.PointerRFCObject.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests for + * {@link JsonStructure}. RFC 6901 JSON Pointer is being passed to + * {@code JsonValue getValue(String)} method so whole JSON Pointer resolving + * sample is being used to test this method. + */ +public class Structure { + /** + * Creates an instance of JavaScript Object Notation (JSON) compatibility + * tests for {@link JsonStructure}. + */ + Structure() { + super(); + } + + /** + * {@link JsonStructure} API methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonStructure API methods added in JSON-P 1.1."); + System.out.println("JsonStructure API methods added in JSON-P 1.1."); + testResolveWholeDocument(result); + testResolveEmptyName(result); + testResolveSimpleArray(result); + testResolveSimpleArrayItems(result); + testResolvePathWithEncodedSlash(result); + testResolvePathWithSlash(result); + testResolvePathWithPercent(result); + testResolvePathWithCaret(result); + testResolvePathWithVerticalBar(result); + testResolvePathWithBackSlash(result); + testResolvePathWithDoubleQuotes(result); + testResolvePathWithSpace(result); + testResolvePathWithTilde(result); + testResolvePathWithEncodedTilde(result); + testResolvePathWithEncodedTildeOne(result); + testResolveValidNumericIndexInArray(result); + testResolveMemberAfterLastInArray(result); + testResolveNonNumericIndexInArray(result); + return result; + } + + /** + * Test RFC 6901 JSON Pointer resolving for the whole document path using + * {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolveWholeDocument(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = value; + verifyGetValue(result, check, value, RFC_KEY_WHOLE); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "": 0} using + * {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolveEmptyName(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL2); + verifyGetValue(result, check, value, RFC_PTR2); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "foo": ["bar", "baz"]} using + * {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolveSimpleArray(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = RFC_VAL1; + verifyGetValue(result, check, value, RFC_PTR1); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "foo": ["bar", "baz"]} array + * elements using {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolveSimpleArrayItems(final TestResult result) { + final String[] itemPtrs = new String[] { RFC_PTR1_ITEM1, RFC_PTR1_ITEM2 }; + final String[] itemVals = new String[] { RFC_VAL1_ITEM1, RFC_VAL1_ITEM2 }; + final JsonObject value = createRFC6901Object(); + for (int i = 0; i < itemPtrs.length; i++) { + final JsonValue check = Json.createValue(itemVals[i]); + verifyGetValue(result, check, value, itemPtrs[i]); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "a/b": 1} using + * {@code JsonValue getValue(String)}. Character {@code '/'} is encoded as + * {@code "~1"} string. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithEncodedSlash(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL3); + verifyGetValue(result, check, value, RFC_PTR3_ENC); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "a/b": 1} using + * {@code JsonValue getValue(String)}. Character {@code '/'} is not encoded as + * {@code "~1"} string. This results in invalid {@code "/a/b"} path and + * resolving such path must throw an exception. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithSlash(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + verifyGetValueFail(result, value, RFC_PTR3); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "c%d": 2} using + * {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithPercent(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL4); + verifyGetValue(result, check, value, RFC_PTR4); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "e^f": 3} using + * {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithCaret(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL5); + verifyGetValue(result, check, value, RFC_PTR5); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "g|h": 4} using + * {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithVerticalBar(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL6); + verifyGetValue(result, check, value, RFC_PTR6); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "i\\j": 5} using + * {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithBackSlash(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL7); + verifyGetValue(result, check, value, RFC_PTR7); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "k\"l": 6} using + * {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithDoubleQuotes(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL8); + verifyGetValue(result, check, value, RFC_PTR8); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code " ": 7} using + * {@code JsonValue getValue(String)}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithSpace(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL9); + verifyGetValue(result, check, value, RFC_PTR9); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "m~n": 8} without encoding + * using {@code JsonValue getValue(String)}. Passing this test is not + * mandatory. + * {@see RFC 6901: 3. + * Syntax} defines JSON pointer grammar as:
+ * {@code json-pointer = *( "/" reference-token )}
+ * {@code reference-token = *( unescaped / escaped )}
+ * {@code unescaped = %x00-2E / %x30-7D / %x7F-10FFFF}
+ * {@code escaped = "~" ( "0" / "1" )}
+ * Characters {@code '/'} and {@code '~'} are excluded from {@code unescaped}. + * But having {@code '~'} outside escape sequence may be acceptable. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithTilde(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR10 + "\" pointer (optional)"); + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL10); + boolean noError = true; + try { + final JsonValue out = value.getValue(RFC_PTR10); + if (operationFailed(check, out)) { + noError = false; + System.out.println(" - Pointer \"" + RFC_KEY10 + + "\" did not return expected value"); + } + } catch (JsonException e) { + noError = false; + System.out.println(" - Expected exception: " + e.getMessage()); + } + if (noError) { + System.out.println( + " - Pointer resolving accepts '~' outside escape sequence"); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "m~n": 8} using + * {@code JsonValue getValue(String)}. Character {@code '~'} is encoded as + * {@code "~0"} string. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithEncodedTilde(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL10); + verifyGetValue(result, check, value, RFC_KEY10_ENC); + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "o~1p": 9} using + * {@code JsonValue getValue(String)}. String {@code "~1"} is encoded as + * {@code "~01"} String. Proper encoded sequences transformation is described + * in chapter: + * {@code "the string '~01' correctly becomes '~1' after transformation"}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithEncodedTildeOne(final TestResult result) { + final JsonStructure value = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL11); + verifyGetValue(result, check, value, RFC_PTR11_ENC); + } + + /** + * Test RFC 6901 JSON Pointer resolver for existing numeric indexes of an + * array. {@see RFC + * 6901: 4. Evaluation} chapter:
+ * If the currently referenced value is a JSON array, the reference token MUST + * contain either: + *
    + *
  • characters comprised of digits (see ABNF below; note that leading zeros + * are not allowed) that represent an unsigned base-10 integer value, making + * the new referenced value the array element with the zero-based index + * identified by the token
  • + *
+ */ + private void testResolveValidNumericIndexInArray(final TestResult result) { + System.out.println( + " - getValue(String) resolving of pointer containing existing numeric array index"); + final JsonArray[] arraysIn = new JsonArray[] { createSimpleStringArray5(), + createSimpleIntArray5(), createSimpleBoolArray5(), + createSimpleObjectArray5() }; + final JsonValue[] strings = new JsonValue[] { toJsonValue(STR_VALUE_1), + toJsonValue(STR_VALUE_2), toJsonValue(STR_VALUE_3), + toJsonValue(STR_VALUE_4), toJsonValue(STR_VALUE_5) }; + final JsonValue[] ints = new JsonValue[] { toJsonValue(INT_VALUE_1), + toJsonValue(INT_VALUE_2), toJsonValue(INT_VALUE_3), + toJsonValue(INT_VALUE_4), toJsonValue(INT_VALUE_5) }; + final JsonValue[] bools = new JsonValue[] { toJsonValue(BOOL_FALSE), + toJsonValue(BOOL_TRUE), toJsonValue(BOOL_TRUE), toJsonValue(BOOL_FALSE), + toJsonValue(BOOL_TRUE) }; + final JsonValue[] objs = new JsonValue[] { OBJ_VALUE_1, OBJ_VALUE_2, + OBJ_VALUE_3, OBJ_VALUE_4, OBJ_VALUE_5 }; + final JsonValue[][] checks = new JsonValue[][] { strings, ints, bools, + objs }; + // Go trough all array types + for (int i = 0; i < arraysIn.length; i++) { + // Go trough all valid indexes in arrays + for (int j = 0; j < 5; j++) { + final String path = "/" + Integer.toString(j); + try { + final JsonValue out = arraysIn[i].getValue(path); + if (operationFailed(checks[i][j], out)) { + result.fail("getValue(String)", "Failed for \"" + path + "\" path"); + } + } catch (JsonException e) { + result.fail("getValue(String)", "Exception: " + e.getMessage()); + } + } + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for character {@code '-'} marking the + * end of an array. + * {@see RFC 6901: 4. + * Evaluation} chapter:
+ * If the currently referenced value is a JSON array, the reference token MUST + * contain either: + *
    + *
  • exactly the single character "-", making the new referenced value the + * (nonexistent) member after the last array element
  • + *
+ * Note that the use of the "-" character to index an array will always result + * in such an error condition because by definition it refers to a nonexistent + * array element. Thus, applications of JSON Pointer need to specify how that + * character is to be handled, if it is to be useful. + */ + private void testResolveMemberAfterLastInArray(final TestResult result) { + System.out.println(" - getValue(String) resolving of array \"/-\" pointer"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray(), createSimpleIntArray5(), createBoolArray2(), + createSimpleObjectArray5() }; + for (int i = 0; i < arraysIn.length; i++) { + try { + arraysIn[i].getValue("/-"); + result.fail("getValue(String)", "Call of getValue(String) on \"" + "/-" + + "\" shall throw JsonException"); + } catch (JsonException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for invalid index containing non + * numeric characters on array. + * {@see RFC 6901: 4. + * Evaluation} chapter:
+ * {@code array-index = %x30 / ( %x31-39 *(%x30-39) )} grammar rule prohibits + * indexes with anything else than sequence of digits. Index {@code '-'} is + * being checked in another tests. The only exception is path for whole + * document ({@code ""}) which must return the whole array. + */ + private void testResolveNonNumericIndexInArray(final TestResult result) { + System.out.println( + " - getValue(String) resolving of pointer containing non numeric array index"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray(), createSimpleIntArray5(), createBoolArray2(), + createSimpleObjectArray5() }; + final String[] typeNames = new String[] { "empty", "String", "int", + "boolean", "JsonObject" }; + final String wholeDocument = ""; + final String[] paths = new String[] { "/", "/1a", "/b4", "/name" }; + // Go trough all array types + for (int i = 0; i < arraysIn.length; i++) { + try { + final JsonValue wholeOut = arraysIn[i].getValue(wholeDocument); + if (operationFailed(wholeOut, arraysIn[i])) { + result.fail("getValue(String)", "Failed for \"" + wholeDocument + + "\" path on " + typeNames[i] + " array"); + } + } catch (JsonException e) { + result.fail("getValue(String)", "Failed for \"" + wholeDocument + + "\" path on " + typeNames[i] + " array: " + e.getMessage()); + } + for (int j = 0; j < paths.length; j++) { + try { + final JsonValue out = arraysIn[i].getValue(paths[j]); + result.fail("getValue(String)", "Succeeded for \"" + paths[j] + + "\" path on " + typeNames[i] + " array"); + } catch (JsonException e) { + // There are too many combinations to log them. + } + } + } + } + + /** + * Test helper: Verify {@code JsonValue getValue(String)} for given JSON path. + * + * @param result + * Tests result record. + */ + private void verifyGetValue(final TestResult result, final JsonValue check, + final JsonStructure value, final String path) { + System.out.println(" - getValue(String) resolving of \"" + path + "\" pointer"); + try { + final JsonValue out = value.getValue(path); + if (operationFailed(check, out)) { + result.fail("getValue(String)", "Failed for \"" + path + "\" path"); + } + } catch (JsonException e) { + result.fail("getValue(String)", "Exception: " + e.getMessage()); + } + } + + /** + * Test helper: Verify {@code JsonValue getValue(String)} for given JSON path. + * + * @param result + * Tests result record. + */ + private void verifyGetValueFail(final TestResult result, + final JsonStructure value, final String path) { + System.out.println( + " - getValue(String) resolving of invalid \"" + path + "\" pointer"); + try { + value.getValue(path); + result.fail("getValue(String)", "Call of getValue(String) on \"" + path + + "\" shall throw JsonException"); + } catch (JsonException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonvaluetests/Value.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonvaluetests/Value.java new file mode 100644 index 00000000..29e51793 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonvaluetests/Value.java @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonvaluetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests for {@link JsonValue}. + */ +public class Value { + + /** + * Creates an instance of JavaScript Object Notation (JSON) compatibility + * tests for {@link JsonValue}. + */ + Value() { + super(); + } + + /** + * {@link JsonValue} API methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonValue API methods added in JSON-P 1.1."); + System.out.println("JsonValue API methods added in JSON-P 1.1."); + testAsJsonObject(result); + testAsJsonObjectOnNonObject(result); + testAsJsonArray(result); + testAsJsonArrayOnNonArray(result); + return result; + } + + /** + * Test {@code JsonObject asJsonObject()} method on {@code JsonObject} + * instances. + * + * @param result + * Test suite result. + */ + private void testAsJsonObject(final TestResult result) { + System.out.println(" - asJsonObject() on JsonObject instances"); + final JsonObject[] values = { createEmptyObject(), createSimpleObjectStr(), + createSimpleObjectInt(), createSimpleObjectBool(), + createSimpleObjectObject(), createCompoundObject() }; + for (final JsonObject objValue : values) { + final JsonValue value = objValue; + final JsonObject out = objValue.asJsonObject(); + if (operationFailed(objValue, out)) { + result.fail("asJsonObject()", "Output " + valueToString(out) + + " value shall be " + valueToString(objValue)); + } + } + } + + /** + * Test {@code JsonObject asJsonObject()} method on non {@code JsonObject} + * instances. + * + * @param result + * Test suite result. + */ + private void testAsJsonObjectOnNonObject(final TestResult result) { + System.out.println(" - asJsonObject() on non JsonObject instances"); + final JsonValue[] values = { createEmptyArrayWithStr(), + createEmptyArrayWithInt(), createEmptyArrayWithBool(), + createEmptyArrayWithObject(), toJsonValue(STR_VALUE), + toJsonValue(INT_VALUE), toJsonValue(LNG_VALUE), toJsonValue(DBL_VALUE), + toJsonValue(BIN_VALUE), toJsonValue(BDC_VALUE), toJsonValue(BOOL_VALUE), + toJsonValue(null) }; + for (final JsonValue value : values) { + try { + value.asJsonObject(); + result.fail("asJsonObject()", + "Call of asJsonObject() on non JsonObject instance shall throw ClassCastException"); + } catch (ClassCastException ex) { + System.out.println(" - Expected exception: " + ex.getMessage()); + } catch (Throwable t) { + result.fail("asJsonObject()", + "Call of asJsonObject() on non JsonObject instance shall throw ClassCastException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Test {@code JsonObject asJsonArray()} method on {@code JsonArray} + * instances. + * + * @param result + * Test suite result. + */ + private void testAsJsonArray(final TestResult result) { + System.out.println(" - asJsonArray() on JsonArray instances"); + final JsonArray[] values = { createEmptyArray(), createEmptyArrayWithStr(), + createEmptyArrayWithInt(), createEmptyArrayWithBool(), + createEmptyArrayWithObject(), createSimpleStringArray5(), + createSimpleIntArray5(), createSimpleBoolArray5(), + createSimpleObjectArray5() }; + for (final JsonArray objValue : values) { + final JsonValue value = objValue; + final JsonArray out = objValue.asJsonArray(); + if (operationFailed(objValue, out)) { + result.fail("asJsonArray()", "Output " + valueToString(out) + + " value shall be " + valueToString(objValue)); + } + } + } + + /** + * Test {@code JsonObject asJsonArray()} method on non {@code JsonArray} + * instances. + * + * @param result + * Test suite result. + */ + private void testAsJsonArrayOnNonArray(final TestResult result) { + System.out.println(" - asJsonArray() on non JsonArray instances"); + final JsonValue[] values = { createSimpleObjectStr(), + createSimpleObjectInt(), createSimpleObjectBool(), + createSimpleObjectObject(), createCompoundObject(), + toJsonValue(STR_VALUE), toJsonValue(INT_VALUE), toJsonValue(LNG_VALUE), + toJsonValue(DBL_VALUE), toJsonValue(BIN_VALUE), toJsonValue(BDC_VALUE), + toJsonValue(BOOL_VALUE), toJsonValue(null) }; + for (final JsonValue value : values) { + try { + value.asJsonArray(); + result.fail("asJsonArray()", + "Call of asJsonArray() on non JsonArray instance shall throw ClassCastException"); + } catch (ClassCastException ex) { + System.out.println(" - Expected exception: " + ex.getMessage()); + } catch (Throwable t) { + result.fail("asJsonArray()", + "Call of asJsonArray() on non JsonArray instance shall throw ClassCastException, not " + + t.getClass().getSimpleName()); + } + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonwriterfactorytests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonwriterfactorytests/ClientTests.java new file mode 100644 index 00000000..875bbe1a --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonwriterfactorytests/ClientTests.java @@ -0,0 +1,324 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +/* + * $Id$ + */ +package jakarta.jsonp.tck.api.jsonwriterfactorytests; + +import jakarta.json.*; +import jakarta.json.stream.*; + +import java.io.*; +import java.nio.charset.Charset; + +import java.util.Properties; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.util.List; +import java.util.Iterator; +import java.util.Map; +import java.util.ArrayList; + +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonWriterFactoryTest1 + * + * @assertion_ids: JSONP:JAVADOC:110; JSONP:JAVADOC:414; JSONP:JAVADOC:422; + * JSONP:JAVADOC:452; JSONP:JAVADOC:463; + * + * @test_Strategy: Tests the JsonWriterFactory API. + * + * JsonWriterFactory writerFactory = Json.createWriterFactory(Map); + * JsonWriter writer1 = writerFactory.createWriter(Writer) JsonWriter writer2 + * = writerFactory.createWriter(Writer) + */ + @Test + public void jsonWriterFactoryTest1() throws Fault { + boolean pass = true; + JsonWriter writer1 = null; + JsonWriter writer2 = null; + String expString = "{}"; + String actString; + JsonObject jsonObject = Json.createReader(new StringReader(expString)) + .readObject(); + try { + System.out.println("Create JsonWriterFactory with Map with EMPTY config"); + JsonWriterFactory writerFactory = Json + .createWriterFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = writerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + System.out.println("--------------------------------------------------"); + System.out.println("TEST CASE [JsonWriterFactory.createWriter(Writer)]"); + System.out.println("--------------------------------------------------"); + System.out.println("Create 1st JsonWriter using JsonWriterFactory"); + Writer sWriter1 = new StringWriter(); + writer1 = writerFactory.createWriter(sWriter1); + if (writer1 == null) { + System.err.println("WriterFactory failed to create writer1"); + pass = false; + } else { + writer1.writeObject(jsonObject); + writer1.close(); + } + System.out.println("sWriter1=" + sWriter1.toString()); + actString = JSONP_Util.removeWhitespace(sWriter1.toString()); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + System.out.println("Create 2nd JsonWriter using JsonWriterFactory"); + Writer sWriter2 = new StringWriter(); + writer2 = writerFactory.createWriter(sWriter2); + if (writer2 == null) { + System.err.println("WriterFactory failed to create writer2"); + pass = false; + } else { + writer2.writeObject(jsonObject); + writer2.close(); + } + System.out.println("sWriter2=" + sWriter2.toString()); + actString = JSONP_Util.removeWhitespace(sWriter2.toString()); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonWriterFactoryTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterFactoryTest1 Failed"); + } + + /* + * @testName: jsonWriterFactoryTest2 + * + * @assertion_ids: JSONP:JAVADOC:110; JSONP:JAVADOC:414; JSONP:JAVADOC:424; + * JSONP:JAVADOC:452; JSONP:JAVADOC:463; + * + * @test_Strategy: Tests the JsonWriterFactory API. + * + * JsonWriterFactory writerFactory = Json.createWriterFactory(Map); + * JsonWriter writer1 = writerFactory.createWriter(OutputStream, Charset) + * JsonWriter writer2 = writerFactory.createWriter(OutputStream, Charset) + * + * Create writer with both UTF-8 and UTF-16BE. + */ + @Test + public void jsonWriterFactoryTest2() throws Fault { + boolean pass = true; + JsonWriter writer1 = null; + JsonWriter writer2 = null; + String expString = "{}"; + String actString; + JsonObject jsonObject = Json.createReader(new StringReader(expString)) + .readObject(); + try { + System.out.println("Create JsonWriterFactory with Map with EMPTY config"); + JsonWriterFactory writerFactory = Json + .createWriterFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = writerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println( + "-----------------------------------------------------------------"); + System.out.println( + "TEST CASE [JsonWriterFactory.createWriter(OutputStream, Charset)]"); + System.out.println( + "-----------------------------------------------------------------"); + System.out.println( + "Create 1st JsonWriter using JsonWriterFactory with UTF-8 encoding"); + ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + writer1 = writerFactory.createWriter(baos1, JSONP_Util.UTF_8); + if (writer1 == null) { + System.err.println("WriterFactory failed to create writer1"); + pass = false; + } else { + writer1.writeObject(jsonObject); + writer1.close(); + } + System.out.println("baos1=" + baos1.toString("UTF-8")); + actString = JSONP_Util.removeWhitespace(baos1.toString("UTF-8")); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + System.out.println( + "Create 2nd JsonWriter using JsonWriterFactory with UTF-8 encoding"); + ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); + writer2 = writerFactory.createWriter(baos2, JSONP_Util.UTF_8); + if (writer2 == null) { + System.err.println("WriterFactory failed to create writer2"); + pass = false; + } else { + writer2.writeObject(jsonObject); + writer2.close(); + } + System.out.println("baos2=" + baos2.toString("UTF-8")); + actString = JSONP_Util.removeWhitespace(baos2.toString("UTF-8")); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonWriterFactoryTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterFactoryTest2 Failed"); + } + + /* + * @testName: jsonWriterFactoryTest3 + * + * @assertion_ids: JSONP:JAVADOC:110; JSONP:JAVADOC:414; JSONP:JAVADOC:423; + * JSONP:JAVADOC:452; JSONP:JAVADOC:463; + * + * @test_Strategy: Tests the JsonWriterFactory API. + * + * JsonWriterFactory writerFactory = Json.createWriterFactory(Map); + * JsonWriter writer1 = writerFactory.createWriter(OutputStream) JsonWriter + * writer2 = writerFactory.createWriter(OutputStream) + */ + @Test + public void jsonWriterFactoryTest3() throws Fault { + boolean pass = true; + JsonWriter writer1 = null; + JsonWriter writer2 = null; + String expString = "{}"; + String actString; + JsonObject jsonObject = Json.createReader(new StringReader(expString)) + .readObject(); + try { + System.out.println("Create JsonWriterFactory with Map with EMPTY config"); + JsonWriterFactory writerFactory = Json + .createWriterFactory(JSONP_Util.getEmptyConfig()); + System.out.println("Checking factory configuration properties"); + Map config = writerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("--------------------------------------------------------"); + System.out.println("TEST CASE [JsonWriterFactory.createWriter(OutputStream)]"); + System.out.println("--------------------------------------------------------"); + System.out.println("Create 1st JsonWriter using JsonWriterFactory"); + ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + writer1 = writerFactory.createWriter(baos1); + if (writer1 == null) { + System.err.println("WriterFactory failed to create writer1"); + pass = false; + } else { + writer1.writeObject(jsonObject); + writer1.close(); + } + System.out.println("baos1=" + baos1.toString("UTF-8")); + actString = JSONP_Util.removeWhitespace(baos1.toString("UTF-8")); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + System.out.println("Create 2nd JsonWriter using JsonWriterFactory"); + ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); + writer2 = writerFactory.createWriter(baos2); + if (writer2 == null) { + System.err.println("WriterFactory failed to create writer2"); + pass = false; + } else { + writer2.writeObject(jsonObject); + writer2.close(); + } + System.out.println("baos2=" + baos2.toString("UTF-8")); + actString = JSONP_Util.removeWhitespace(baos2.toString("UTF-8")); + if (!JSONP_Util.assertEqualsJsonText(expString, actString)) + pass = false; + + } catch (Exception e) { + throw new Fault("jsonWriterFactoryTest3 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterFactoryTest3 Failed"); + } + + /* + * @testName: jsonWriterFactoryTest4 + * + * @assertion_ids: JSONP:JAVADOC:452; JSONP:JAVADOC:463; + * + * @test_Strategy: Tests the JsonWriterFactory API. + * + * JsonWriterFactory writerFactory = Json.createWriterFactory(Map); + * Map config = JsonWriterFactory.getConfigInUse(); + * + * Test for the following 3 scenarios: 1) no supported provider property + * (empty config) 2) supported provider property 3) supported and non + * supported provider property + */ + @Test + public void jsonWriterFactoryTest4() throws Fault { + boolean pass = true; + JsonWriterFactory writerFactory; + Map config; + try { + System.out.println("----------------------------------------------"); + System.out.println("Test scenario1: no supported provider property"); + System.out.println("----------------------------------------------"); + System.out.println("Create JsonWriterFactory with Map with EMPTY config"); + writerFactory = Json.createWriterFactory(JSONP_Util.getEmptyConfig()); + config = writerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("-------------------------------------------"); + System.out.println("Test scenario2: supported provider property"); + System.out.println("-------------------------------------------"); + System.out.println("Create JsonWriterFactory with Map with FOO config"); + writerFactory = Json.createWriterFactory(JSONP_Util.getFooConfig()); + config = writerFactory.getConfigInUse(); + String[] props = { JsonGenerator.PRETTY_PRINTING, }; + if (!JSONP_Util.doConfigCheck(config, 0)) + pass = false; + + System.out.println("-------------------------------------------------------------"); + System.out.println("Test scenario3: supported and non supported provider property"); + System.out.println("-------------------------------------------------------------"); + System.out.println("Create JsonGeneratorFactory with Map with all config"); + writerFactory = Json.createWriterFactory(JSONP_Util.getAllConfig()); + config = writerFactory.getConfigInUse(); + if (!JSONP_Util.doConfigCheck(config, 1, props)) + pass = false; + } catch (Exception e) { + throw new Fault("jsonWriterFactoryTest4 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterFactoryTest4 Failed"); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonwritertests/ClientTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonwritertests/ClientTests.java new file mode 100644 index 00000000..19bed5bb --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonwritertests/ClientTests.java @@ -0,0 +1,1108 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonwritertests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.common.*; +import jakarta.jsonp.tck.lib.harness.Fault; + +import java.io.*; +import java.util.*; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +import jakarta.json.*; + +// $Id$ +@RunWith(Arquillian.class) +public class ClientTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, ClientTests.class.getPackage().getName()); + } + /* Tests */ + + /* + * @testName: jsonWriterTest1 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:110; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. + * Comparison is done by reading the JsonWriter output using JsonReader and + * recreating the JsonObject and than performing a JsonObject comparison for + * equality. + * + * Tests using API methods: Json.createWriter(Writer) and + * writer.writeObject(JsonObject) + * + */ + @Test + public void jsonWriterTest1() throws Fault { + boolean pass = true; + try { + + System.out.println("Create sample JsonObject for testing"); + JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); + + System.out.println("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeObject(myJsonObject1); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String contents = sWriter.toString(); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + contents); + + System.out.println( + "Read the JsonObject back into 'myJsonObject2' using a JsonReader"); + JsonReader reader = Json.createReader(new StringReader(contents)); + JsonObject myJsonObject2 = (JsonObject) reader.read(); + + System.out.println("Compare myJsonObject1 and myJsonObject2 for equality"); + pass = JSONP_Util.assertEqualsJsonObjects(myJsonObject1, myJsonObject2); + } catch (Exception e) { + throw new Fault("jsonWriterTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterTest1 Failed"); + } + + /* + * @testName: jsonWriterTest2 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:187; JSONP:JAVADOC:110; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. + * Comparison is done by comparing the expected JsonObject text output with + * the actual JsonObject text output from the JsonWriter for equality. + * + * Tests using API methods: Json.createWriter(OutputStream) and + * writer.writeObject(JsonObject) + * + */ + @Test + public void jsonWriterTest2() throws Fault { + boolean pass = true; + try { + + System.out.println("Create sample JsonObject for testing"); + JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); + + System.out.println("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriter(baos); + writer.writeObject(myJsonObject1); + System.out.println("Close JsonWriter"); + baos.close(); + writer.close(); + + System.out.println("Save contents of the JsonWriter as a String"); + String actJsonObjectText = baos.toString("UTF-8"); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + actJsonObjectText); + + System.out.println( + "Compare expected JsonObject text with actual JsonObject text for equality"); + pass = JSONP_Util.assertEqualsJsonText( + JSONP_Util.EXPECTED_SAMPLEJSONOBJECT_TEXT, actJsonObjectText); + } catch (Exception e) { + throw new Fault("jsonWriterTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterTest2 Failed"); + } + + /* + * @testName: jsonWriterTest3 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:107; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. + * Comparison is done by reading the JsonWriter output using JsonReader and + * recreating the JsonArray and than performing a JsonArray comparison for + * equality. + * + * Tests using API methods: Json.createWriter(Writer) and + * writer.writeArray(JsonArray) + * + */ + @Test + public void jsonWriterTest3() throws Fault { + boolean pass = true; + try { + + System.out.println("Create sample JsonArray for testing"); + JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); + + System.out.println("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.writeArray(myJsonArray1); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String contents = sWriter.toString(); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + contents); + + System.out.println("Read the JsonArray back into 'myJsonArray2' using a JsonReader"); + JsonArray myJsonArray2; + try (JsonReader reader = Json.createReader(new StringReader(contents))) { + myJsonArray2 = (JsonArray) reader.read(); + System.out.println("Close JsonReader"); + } + + System.out.println("Compare myJsonArray1 and myJsonArray2 for equality"); + pass = JSONP_Util.assertEqualsJsonArrays(myJsonArray1, myJsonArray2); + } catch (Exception e) { + throw new Fault("jsonWriterTest3 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterTest3 Failed"); + } + + /* + * @testName: jsonWriterTest4 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:187; JSONP:JAVADOC:107; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. + * Comparison is done by comparing the expected JsonArray text output with the + * actual JsonArray text output from the JsonWriter for equality. + * + * Tests using API methods: Json.createWriter(OutputStream) and + * writer.writeArray(JsonArray) + * + */ + @Test + public void jsonWriterTest4() throws Fault { + boolean pass = true; + try { + + System.out.println("Create sample JsonArray for testing"); + JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); + + System.out.println("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriter(baos); + writer.writeArray(myJsonArray1); + System.out.println("Close JsonWriter"); + baos.close(); + writer.close(); + + System.out.println("Save contents of the JsonWriter as a String"); + String actJsonArrayText = baos.toString("UTF-8"); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + actJsonArrayText); + + System.out.println( + "Compare expected JsonArray text with actual JsonArray text for equality"); + pass = JSONP_Util.assertEqualsJsonText( + JSONP_Util.EXPECTED_SAMPLEJSONARRAY_TEXT, actJsonArrayText); + } catch (Exception e) { + throw new Fault("jsonWriterTest4 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterTest4 Failed"); + } + + /* + * @testName: jsonWriterTest5 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:424; JSONP:JAVADOC:110; + * JSONP:JAVADOC:452; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. + * Comparison is done by comparing the expected JsonObject text output with + * the actual JsonObject text output from the JsonWriter for equality. + * + * Tests using API methods: + * Json.createWriterFactory(Map).createWriter(OutputStream, Charset) + * writer.writeObject(JsonObject) + * + * For encoding use UTF-16BE. + */ + @Test + public void jsonWriterTest5() throws Fault { + boolean pass = true; + try { + + System.out.println("Create sample JsonObject for testing"); + JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); + + System.out.println("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) + .createWriter(baos, JSONP_Util.UTF_16BE); + writer.writeObject(myJsonObject1); + System.out.println("Close JsonWriter"); + baos.close(); + writer.close(); + + System.out.println("Save contents of the JsonWriter as a String"); + String actJsonObjectText = JSONP_Util + .removeWhitespace(baos.toString("UTF-16BE")); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + actJsonObjectText); + + System.out.println( + "Compare expected JsonObject text with actual JsonObject text for equality"); + pass = JSONP_Util.assertEqualsJsonText( + JSONP_Util.EXPECTED_SAMPLEJSONOBJECT_TEXT, actJsonObjectText); + } catch (Exception e) { + throw new Fault("jsonWriterTest5 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterTest5 Failed"); + } + + /* + * @testName: jsonWriterTest6 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:424; JSONP:JAVADOC:107; + * JSONP:JAVADOC:452; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. + * Comparison is done by comparing the expected JsonArray text output with the + * actual JsonArray text output from the JsonWriter for equality. + * + * Tests using API methods: + * Json.createWriterFactory.createWriter(OutputStream, Charset) + * writer.writeArray(JsonArray) + * + * For encoding use UTF-8. + */ + @Test + public void jsonWriterTest6() throws Fault { + boolean pass = true; + try { + + System.out.println("Create a configuration with PRETT_PRINTING enabled."); + Map config = JSONP_Util.getPrettyPrintingConfig(); + + System.out.println("Create sample JsonArray for testing"); + JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); + + System.out.println("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriterFactory(config).createWriter(baos, + JSONP_Util.UTF_8); + writer.writeArray(myJsonArray1); + System.out.println("Close JsonWriter"); + baos.close(); + writer.close(); + + System.out.println("Save contents of the JsonWriter as a String"); + String actJsonArrayText = JSONP_Util + .removeWhitespace(baos.toString("UTF-8")); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + actJsonArrayText); + + System.out.println( + "Compare expected JsonArray text with actual JsonArray text for equality"); + pass = JSONP_Util.assertEqualsJsonText( + JSONP_Util.EXPECTED_SAMPLEJSONARRAY_TEXT, actJsonArrayText); + } catch (Exception e) { + throw new Fault("jsonWriterTest6 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterTest6 Failed"); + } + + /* + * @testName: jsonWriterTest7 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:191; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. + * Comparison is done by reading the JsonWriter output using JsonReader and + * recreating the JsonObject and than performing a JsonObject comparison for + * equality. + * + * Tests using API methods: Json.createWriter(Writer) and + * writer.write(JsonStructure) + * + */ + @Test + public void jsonWriterTest7() throws Fault { + boolean pass = true; + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); + + System.out.println("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.write(myJsonObject1); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String contents = sWriter.toString(); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + contents); + + System.out.println( + "Read the JsonObject back into 'myJsonObject2' using a JsonReader"); + JsonReader reader = Json.createReader(new StringReader(contents)); + JsonObject myJsonObject2 = (JsonObject) reader.read(); + + System.out.println("Compare myJsonObject1 and myJsonObject2 for equality"); + pass = JSONP_Util.assertEqualsJsonObjects(myJsonObject1, myJsonObject2); + } catch (Exception e) { + throw new Fault("jsonWriterTest7 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterTest7 Failed"); + } + + /* + * @testName: jsonWriterTest8 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:191; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. + * Comparison is done by reading the JsonWriter output using JsonReader and + * recreating the JsonArray and than performing a JsonArray comparison for + * equality. + * + * Tests using API methods: Json.createWriter(Writer) and + * writer.write(JsonStructure) + * + */ + @Test + public void jsonWriterTest8() throws Fault { + boolean pass = true; + try { + + System.out.println("Create sample JsonArray for testing"); + JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); + + System.out.println("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); + StringWriter sWriter = new StringWriter(); + try (JsonWriter writer = Json.createWriter(sWriter)) { + writer.write(myJsonArray1); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String contents = sWriter.toString(); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + contents); + + System.out.println("Read the JsonArray back into 'myJsonArray2' using a JsonReader"); + JsonReader reader = Json.createReader(new StringReader(contents)); + JsonArray myJsonArray2 = (JsonArray) reader.read(); + + System.out.println("Compare myJsonArray1 and myJsonArray2 for equality"); + pass = JSONP_Util.assertEqualsJsonArrays(myJsonArray1, myJsonArray2); + } catch (Exception e) { + throw new Fault("jsonWriterTest8 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterTest8 Failed"); + } + + /* + * @testName: jsonWriterUTFEncodedTests + * + * @assertion_ids: JSONP:JAVADOC:110; JSONP:JAVADOC:423; JSONP:JAVADOC:452; + * + * @test_Strategy: Tests various JsonWriter API's to create a JsonObject. + * + * The output is written to an OutputStream using all supported UTF encodings + * and read back as a string and filtered to remove whitespace and is compared + * against an expected string. The following UTF encodings are tested: + * + * UTF8 UTF16 UTF16LE UTF16BE UTF32LE UTF32BE + * + * { "object":{"string":"string","number":1,"true":true,"false":false,"null": + * null}, "array":["string", 1, true, false, null] } + */ + @Test + public void jsonWriterUTFEncodedTests() throws Fault { + boolean pass = true; + System.out.println( + "Create expected JSON text with no whitespace for use in comparsion"); + String expJson = "{\"object\":{\"string\":\"string\",\"number\":1,\"true\":true,\"false\":false,\"null\":null},\"array\":[\"string\",1,true,false,null]}"; + try { + System.out.println( + "-----------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-8]"); + System.out.println( + "-----------------------------------------------------------------------------------------------"); + System.out.println("Create JsonWriter using UTF-8 encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) + .createWriter(baos, JSONP_Util.UTF_8); + JSONP_Util.writeJsonObjectFromString(writer, expJson); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-8")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-8 encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-8")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing generation to UTF-8 encoding: " + e); + } + try { + System.out.println( + "------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-16]"); + System.out.println( + "------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonWriter using UTF-16 encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) + .createWriter(baos, JSONP_Util.UTF_16); + JSONP_Util.writeJsonObjectFromString(writer, expJson); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-16")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-16 encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println("Exception occurred testing generation to UTF-16 encoding: " + e); + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-16LE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonWriter using UTF-16LE encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) + .createWriter(baos, JSONP_Util.UTF_16LE); + JSONP_Util.writeJsonObjectFromString(writer, expJson); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-16LE")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-16LE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16LE")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println( + "Exception occurred testing generation to UTF-16LE encoding: " + e); + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-16BE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonWriter using UTF-16BE encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) + .createWriter(baos, JSONP_Util.UTF_16BE); + JSONP_Util.writeJsonObjectFromString(writer, expJson); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-16BE")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-16BE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-16BE")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println( + "Exception occurred testing generation to UTF-16BE encoding: " + e); + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-32LE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonWriter using UTF-32LE encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) + .createWriter(baos, JSONP_Util.UTF_32LE); + JSONP_Util.writeJsonObjectFromString(writer, expJson); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-32LE")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-32LE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-32LE")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println( + "Exception occurred testing generation to UTF-32LE encoding: " + e); + } + try { + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println( + "TEST CASE [Json.createWriterFactory(Map).createWriter(OutputStream, Charset) as UTF-32BE]"); + System.out.println( + "--------------------------------------------------------------------------------------------------"); + System.out.println("Create JsonWriter using UTF-32BE encoding"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriterFactory(JSONP_Util.getEmptyConfig()) + .createWriter(baos, JSONP_Util.UTF_32BE); + JSONP_Util.writeJsonObjectFromString(writer, expJson); + + // Dump JsonText output + System.out.println("Generated Output=" + baos.toString("UTF-32BE")); + + // Do comparison + System.out.println( + "Read the JSON text back from OutputStream using UTF-32BE encoding removing whitespace"); + String actJson = JSONP_Util.removeWhitespace(baos.toString("UTF-32BE")); + if (!JSONP_Util.assertEqualsJsonText(expJson, actJson)) + pass = false; + + } catch (Exception e) { + pass = false; + System.err.println( + "Exception occurred testing generation to UTF-32BE encoding: " + e); + } + if (!pass) + throw new Fault("jsonWriterUTFEncodedTests Failed"); + } + + /* + * @testName: jsonWriterWithConfigTest1 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:422; JSONP:JAVADOC:110; + * JSONP:JAVADOC:452; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonObject. + * Comparison is done by comparing the expected JsonObject text output with + * the actual JsonObject text output from the JsonWriter for equality. + * + * Tests using API methods: + * Json.createWriterFactory(Map).createWriter(Writer) + * writer.writeObject(JsonObject) + * + */ + @Test + public void jsonWriterWithConfigTest1() throws Fault { + boolean pass = true; + try { + + System.out.println("Create a configuration with PRETT_PRINTING enabled."); + Map config = JSONP_Util.getPrettyPrintingConfig(); + + System.out.println("Create sample JsonObject for testing"); + JsonObject myJsonObject1 = JSONP_Util.createSampleJsonObject(); + + System.out.println("Write the JsonObject 'myJsonObject1' out to a JsonWriter"); + StringWriter swriter = new StringWriter(); + try (JsonWriter writer = Json.createWriterFactory(config) + .createWriter(swriter)) { + writer.writeObject(myJsonObject1); + System.out.println("Close JsonWriter"); + } + + System.out.println("Save contents of the JsonWriter as a String"); + String actJsonObjectText = JSONP_Util + .removeWhitespace(swriter.toString()); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + actJsonObjectText); + + System.out.println( + "Compare expected JsonObject text with actual JsonObject text for equality"); + pass = JSONP_Util.assertEqualsJsonText( + JSONP_Util.EXPECTED_SAMPLEJSONOBJECT_TEXT, actJsonObjectText); + } catch (Exception e) { + throw new Fault("jsonWriterWithConfigTest1 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterWithConfigTest1 Failed"); + } + + /* + * @testName: jsonWriterWithConfigTest2 + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:423; JSONP:JAVADOC:107; + * + * @test_Strategy: Tests JsonWriter API's for writing out a JsonArray. + * Comparison is done by comparing the expected JsonArray text output with the + * actual JsonArray text output from the JsonWriter for equality. + * + * Tests using API methods: + * Json.createWriterFactory(Map).creatWriter(OutputStream) + * writer.writeArray(JsonArray) + * + */ + @Test + public void jsonWriterWithConfigTest2() throws Fault { + boolean pass = true; + try { + + System.out.println("Create a configuration with PRETT_PRINTING enabled."); + Map config = JSONP_Util.getPrettyPrintingConfig(); + + System.out.println("Create sample JsonArray for testing"); + JsonArray myJsonArray1 = JSONP_Util.createSampleJsonArray(); + + System.out.println("Write the JsonArray 'myJsonArray1' out to a JsonWriter"); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + JsonWriter writer = Json.createWriterFactory(config).createWriter(baos); + writer.writeArray(myJsonArray1); + System.out.println("Close JsonWriter"); + baos.close(); + writer.close(); + + System.out.println("Save contents of the JsonWriter as a String"); + String actJsonArrayText = JSONP_Util + .removeWhitespace(baos.toString("UTF-8")); + + System.out.println("Dump contents of JsonWriter as a String"); + System.out.println("JsonWriterContents=" + actJsonArrayText); + + System.out.println( + "Compare expected JsonArray text with actual JsonArray text for equality"); + pass = JSONP_Util.assertEqualsJsonText( + JSONP_Util.EXPECTED_SAMPLEJSONARRAY_TEXT, actJsonArrayText); + } catch (Exception e) { + throw new Fault("jsonWriterWithConfigTest2 Failed: ", e); + } + if (!pass) + throw new Fault("jsonWriterWithConfigTest2 Failed"); + } + + /* + * @testName: jsonWriterExceptionTests + * + * @assertion_ids: JSONP:JAVADOC:105; JSONP:JAVADOC:106; JSONP:JAVADOC:109; + * JSONP:JAVADOC:112; JSONP:JAVADOC:222; + * + * @test_Strategy: Test for JsonWriter exception test conditions. o + * IllegalStateException + * + */ + @Test + public void jsonWriterExceptionTests() throws Fault { + boolean pass = true; + JsonWriter writer = null; + + // IllegalStateException if writer.close() already called before + // writer.writeArray(JsonArray) + try { + System.out.println("Create sample JsonArray for testing"); + JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); + + System.out.println("Create JsonWriter, write something and close it"); + StringWriter sWriter = new StringWriter(); + writer = Json.createWriter(sWriter); + writer.writeArray(jsonArray); + writer.close(); + + System.out.println( + "IllegalStateException if writer.close() already called before writer.writeArray(JsonArray)"); + writer.writeArray(jsonArray); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // IllegalStateException if writer.writeArray() called after + // writer.writeArray(JsonArray) + try { + System.out.println("Create sample JsonArray for testing"); + JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); + + System.out.println("Create JsonWriter and write out array"); + StringWriter sWriter = new StringWriter(); + writer = Json.createWriter(sWriter); + writer.writeArray(jsonArray); + + System.out.println( + "IllegalStateException if writer.writeArray(JsonArray) called after writer.writeArray(JsonArray)"); + writer.writeArray(jsonArray); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (writer != null) + writer.close(); + } + + // IllegalStateException if writer.writeObject() called after + // writer.writeArray(JsonArray) + try { + System.out.println("Create sample JsonArray for testing"); + JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); + + System.out.println("Create sample JsonObject for testing"); + JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create JsonWriter and write out array"); + StringWriter sWriter = new StringWriter(); + writer = Json.createWriter(sWriter); + writer.writeArray(jsonArray); + + System.out.println( + "IllegalStateException if writer.writeObject(JsonObject) called after writer.writeArray(JsonArray)"); + writer.writeObject(jsonObject); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (writer != null) + writer.close(); + } + + // IllegalStateException if writer.close() already called before + // writer.writeObject(JsonArray) + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create JsonWriter, write something and close it"); + StringWriter sWriter = new StringWriter(); + writer = Json.createWriter(sWriter); + writer.writeObject(jsonObject); + writer.close(); + + System.out.println( + "IllegalStateException if writer.close() already called before writer.writeObject(JsonObject)"); + writer.writeObject(jsonObject); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // IllegalStateException if writer.writeObject() called after + // writer.writeObject(JsonObject) + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create JsonWriter and write out object"); + StringWriter sWriter = new StringWriter(); + writer = Json.createWriter(sWriter); + writer.writeObject(jsonObject); + + System.out.println( + "IllegalStateException if writer.writeObject(JsonObject) called after writer.writeObject(JsonObject)"); + writer.writeObject(jsonObject); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (writer != null) + writer.close(); + } + + // IllegalStateException if writer.writeArray() called after + // writer.writeObject(JsonObject) + try { + System.out.println("Create sample JsonArray for testing"); + JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); + + System.out.println("Create sample JsonObject for testing"); + JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create JsonWriter and write out object"); + StringWriter sWriter = new StringWriter(); + writer = Json.createWriter(sWriter); + writer.writeObject(jsonObject); + + System.out.println( + "IllegalStateException if writer.writeArray(JsonArray) called after writer.writeObject(JsonObject)"); + writer.writeArray(jsonArray); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (writer != null) + writer.close(); + } + + // IllegalStateException if writer.close() already called before + // writer.write(JsonArray) + try { + System.out.println("Create sample JsonArray for testing"); + JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); + + System.out.println("Create JsonWriter, write something and close it"); + StringWriter sWriter = new StringWriter(); + writer = Json.createWriter(sWriter); + writer.write(jsonArray); + writer.close(); + + System.out.println( + "IllegalStateException if writer.close() already called before writer.write(JsonArray)"); + writer.write(jsonArray); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // IllegalStateException if writer.write(JsonArray) called after + // writer.writeArray(JsonArray) + try { + System.out.println("Create sample JsonArray for testing"); + JsonArray jsonArray = JSONP_Util.createSampleJsonArray(); + + System.out.println("Create JsonWriter and write out array"); + StringWriter sWriter = new StringWriter(); + writer = Json.createWriter(sWriter); + writer.writeArray(jsonArray); + + System.out.println( + "IllegalStateException if writer.write(JsonArray) called after writer.writeArray(JsonArray)"); + writer.write(jsonArray); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (writer != null) + writer.close(); + } + + // IllegalStateException if writer.write(JsonObject) called after + // writer.writeJsonObject(JsonObject) + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject jsonObject = JSONP_Util.createSampleJsonObject(); + + System.out.println("Create JsonWriter and write out object"); + StringWriter sWriter = new StringWriter(); + writer = Json.createWriter(sWriter); + writer.writeObject(jsonObject); + + System.out.println( + "IllegalStateException if writer.write(JsonObject) called after writer.writeObject(JsonObject)"); + writer.write(jsonObject); + pass = false; + System.err.println("Failed to throw IllegalStateException"); + } catch (IllegalStateException e) { + System.out.println("Got expected IllegalStateException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } finally { + if (writer != null) + writer.close(); + } + + if (!pass) + throw new Fault("jsonWriterExceptionTests Failed"); + } + + /* + * @testName: jsonWriterIOErrorTests + * + * @assertion_ids: JSONP:JAVADOC:108; JSONP:JAVADOC:111; JSONP:JAVADOC:221; + * JSONP:JAVADOC:414; + * + * @test_Strategy: Tests for JsonException for testable i/o errors. + * + */ + @Test + public void jsonWriterIOErrorTests() throws Fault { + boolean pass = true; + + // Trip JsonException if there is an i/o error on JsonWriter.close() + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject myJsonObject = JSONP_Util.createSampleJsonObject(); + System.out.println( + "Trip JsonException if there is an i/o error on JsonWriter.close()."); + MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); + try (JsonWriter writer = Json.createWriter(mbw)) { + writer.writeObject(myJsonObject); + mbw.setThrowIOException(true); + System.out.println("Calling JsonWriter.close()"); + } + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonException if there is an i/o error on + // JsonWriter.writeObject(JsonObject) + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject myJsonObject = JSONP_Util.createSampleJsonObject(); + System.out.println( + "Trip JsonException if there is an i/o error on JsonWriter.writeObject(JsonObject)."); + MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); + try (JsonWriter writer = Json.createWriter(mbw)) { + mbw.setThrowIOException(true); + System.out.println("Calling JsonWriter.writeObject(JsonObject)"); + writer.writeObject(myJsonObject); + } + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonException if there is an i/o error on + // JsonWriter.writeArray(JsonArray) + try { + System.out.println("Create sample JsonArray for testing"); + JsonArray myJsonArray = JSONP_Util.createSampleJsonArray(); + System.out.println( + "Trip JsonException if there is an i/o error on JsonWriter.writeArray(JsonArray)."); + MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); + try (JsonWriter writer = Json.createWriter(mbw)) { + mbw.setThrowIOException(true); + System.out.println("Calling JsonWriter.writeArray(JsonArray)"); + writer.writeArray(myJsonArray); + } + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + // Trip JsonException if there is an i/o error on + // JsonWriter.write(JsonStructure) + try { + System.out.println("Create sample JsonObject for testing"); + JsonObject myJsonObject = JSONP_Util.createSampleJsonObject(); + System.out.println( + "Trip JsonException if there is an i/o error on JsonWriter.write(JsonStructure)."); + MyBufferedWriter mbw = new MyBufferedWriter(new StringWriter()); + try (JsonWriter writer = Json.createWriter(mbw)) { + mbw.setThrowIOException(true); + System.out.println("Calling JsonWriter.write(JsonStructure)"); + writer.write(myJsonObject); + } + System.err.println("Did not get expected JsonException"); + pass = false; + } catch (JsonException e) { + System.out.println("Caught expected JsonException"); + } catch (Exception e) { + pass = false; + System.err.println("Caught unexpected exception: " + e); + } + + if (!pass) + throw new Fault("jsonWriterIOErrorTests Failed"); + } + + /* + * @testName: jsonWriter11Test + * + * @assertion_ids: JSONP:JAVADOC:650; JSONP:JAVADOC:583; JSONP:JAVADOC:584; + * JSONP:JAVADOC:585; JSONP:JAVADOC:586; JSONP:JAVADOC:587; JSONP:JAVADOC:588; + * JSONP:JAVADOC:662; JSONP:JAVADOC:663; JSONP:JAVADOC:664; JSONP:JAVADOC:665; + * JSONP:JAVADOC:666; JSONP:JAVADOC:667; + * + * @test_Strategy: Tests JsonWriter API methods added in JSON-P 1.1. + */ + @Test + public void jsonWriter11Test() throws Fault { + Writer writerTest = new Writer(); + final TestResult result = writerTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonwritertests/Writer.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonwritertests/Writer.java new file mode 100644 index 00000000..8de88329 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/jsonwritertests/Writer.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.jsonwritertests; + +import jakarta.jsonp.tck.api.common.JsonValueType; +import jakarta.jsonp.tck.api.common.SimpleValues; +import jakarta.jsonp.tck.api.common.TestResult; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import jakarta.json.Json; +import jakarta.json.JsonException; +import jakarta.json.JsonValue; +import jakarta.json.JsonWriter; +import jakarta.json.stream.JsonParser; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests for {@link JsonWriter}. + */ +public class Writer { + + /** Tests input data. */ + private static final Object[] VALUES = new Object[] { OBJ_VALUE, // write(JsonValue) + // for + // JsonObject + createEmptyArrayWithStr(), // write(JsonValue) for simple JsonArray + STR_VALUE, // write(JsonValue) for String + INT_VALUE, // write(JsonValue) for int + LNG_VALUE, // write(JsonValue) for long + DBL_VALUE, // write(JsonValue) for double + BIN_VALUE, // write(JsonValue) for BigInteger + BDC_VALUE, // write(JsonValue) for BigDecimal + BOOL_VALUE, // write(JsonValue) for boolean + null // write(JsonValue) for null + }; + + /** + * Creates an instance of JavaScript Object Notation (JSON) compatibility + * tests for {@link JsonWriter}. + */ + Writer() { + super(); + } + + /** + * {@link JsonWriter} API methods added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonWriter API methods added in JSON-P 1.1."); + System.out.println("JsonWriter API methods added in JSON-P 1.1."); + testWriteValue(result); + testDoubleWriteValue(result); + testIOExceptionOnWriteValue(result); + return result; + } + + /** + * Test {@code void write(JsonValue)} method on all child types of + * {@code JsonValue}. + * + * @param result + * Test suite result. + */ + private void testWriteValue(final TestResult result) { + for (Object value : VALUES) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println(" - write(JsonValue) for " + typeName + " as an argument"); + final JsonValue jsonValue = SimpleValues.toJsonValue(value); + final StringWriter strWriter = new StringWriter(); + try (final JsonWriter writer = Json.createWriter(strWriter)) { + writer.write(jsonValue); + } catch (JsonException ex) { + System.out.println("Caught JsonException: " + ex.getLocalizedMessage()); + result.fail("write(JsonValue)", + "Caught JsonException: " + ex.getLocalizedMessage()); + } + final String data = strWriter.toString(); + System.out.println(" - Data: " + data); + final JsonParser parser = Json.createParser(new StringReader(data)); + parser.next(); + final JsonValue outValue = parser.getValue(); + if (operationFailed(jsonValue, outValue)) { + result.fail("write(JsonValue)", + "Writer output " + valueToString(outValue) + " value shall be " + + valueToString(jsonValue)); + } + } + } + + /** + * Test {@code void write(JsonValue)} method with duplicated {@code JsonValue} + * write call. Second call is expected to throw {@code IllegalStateException} + * exception. + * + * @param result + * Test suite result. + */ + private void testDoubleWriteValue(final TestResult result) { + for (Object value : VALUES) { + final String typeName = JsonValueType.getType(value).name(); + System.out.println( + " - duplicate write(JsonValue) for " + typeName + " as an argument"); + final JsonValue jsonValue = SimpleValues.toJsonValue(value); + final StringWriter strWriter = new StringWriter(); + try (final JsonWriter writer = Json.createWriter(strWriter)) { + // 1st attempt to write the data shall pass + writer.write(jsonValue); + try { + // 2nd attempt to write the data shall throw IllegalStateException + writer.write(jsonValue); + result.fail("write(JsonValue)", + "Duplicate call of write(JsonValue) shall throw IllegalStateException"); + } catch (IllegalStateException ex) { + System.out.println(" - Expected exception: " + ex.getMessage()); + } catch (Throwable t) { + result.fail("write(JsonValue)", + "Duplicate call of write(JsonValue) shall throw IllegalStateException, not " + + t.getClass().getSimpleName()); + } + } catch (JsonException ex) { + System.out.println("Caught JsonException: " + ex.getLocalizedMessage()); + result.fail("write(JsonValue)", + "Caught JsonException: " + ex.getLocalizedMessage()); + } + } + } + + /** + * Test {@code void write(JsonValue)} method with write call that causes + * IOException. IOException shall be encapsulated in JsonException. + * + * @param result + * Test suite result. + */ + @SuppressWarnings("ConvertToTryWithResources") + private void testIOExceptionOnWriteValue(final TestResult result) { + System.out.println(" - write(JsonValue) into already closed file writer"); + final JsonValue jsonValue = SimpleValues.toJsonValue(DEF_VALUE); + File temp = null; + JsonWriter writer; + // Close writer before calling write method. + try { + temp = File.createTempFile("testIOExceptionOnWriteValue", ".txt"); + System.out.println(" - Temporary file: " + temp.getAbsolutePath()); + final FileWriter fileWriter = new FileWriter(temp); + writer = Json.createWriter(fileWriter); + fileWriter.close(); + } catch (IOException ex) { + System.out.println("Caught IOException: " + ex.getLocalizedMessage()); + result.fail("write(JsonValue)", + "Caught IOException: " + ex.getLocalizedMessage()); + return; + } finally { + if (temp != null) { + temp.delete(); + } + } + try { + writer.write(jsonValue); + result.fail("write(JsonValue)", + "Call of write(JsonValue) on already closed file writer shall throw JsonException"); + } catch (JsonException ex) { + System.out.println(" - Expected exception: " + ex.getMessage()); + } catch (Throwable t) { + result.fail("write(JsonValue)", + "Call of write(JsonValue) on already closed file writer shall throw JsonException, not " + + t.getClass().getSimpleName()); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeAddValue.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeAddValue.java new file mode 100644 index 00000000..13d5b782 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeAddValue.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.mergetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.JsonObject; + +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility + * tests.
+ * Checks scenario described in + * {@see RFC 7396: 1. + * Introduction}: If the provided merge patch contains members that do not + * appear within the target, those members are added. + */ +public class MergeAddValue extends MergeCommon { + + /** + * Creates an instance of RFC 7396 value adding test. + */ + MergeAddValue() { + super(); + } + + /** + * Test RFC 7396: Adding non existing values. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "RFC 7396: Add non existing values"); + System.out.println("Testing RFC 7396: Add non existing values"); + testStringOnEmptyObject(result); + testStringOnsimpleObject(result); + testIntOnEmptyObject(result); + testIntOnsimpleObject(result); + testBoolOnEmptyObject(result); + testBoolOnsimpleObject(result); + testObjectOnEmptyObject(result); + testObjectOnsimpleObject(result); + return result; + } + + /** + * Test RFC 7396 patch and diff for {@code String} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testStringOnEmptyObject(final TestResult result) { + System.out.println(" - for String on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject patch = createSimpleObjectStr(); + final JsonObject check = createSimpleObjectStr(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testStringOnsimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject patch = createSimpleObjectStr(); + final JsonObject check = createSimpleObjectWithStr(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code int} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testIntOnEmptyObject(final TestResult result) { + System.out.println(" - for int on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject patch = createSimpleObjectInt(); + final JsonObject check = createSimpleObjectInt(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testIntOnsimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject patch = createSimpleObjectInt(); + final JsonObject check = createSimpleObjectWithInt(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code boolean} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testBoolOnEmptyObject(final TestResult result) { + System.out.println(" - for boolean on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject patch = createSimpleObjectBool(); + final JsonObject check = createSimpleObjectBool(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testBoolOnsimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject patch = createSimpleObjectBool(); + final JsonObject check = createSimpleObjectWithBool(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code JsonObject} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testObjectOnEmptyObject(final TestResult result) { + System.out.println(" - for JsonObject on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject patch = createSimpleObjectObject(); + final JsonObject check = createSimpleObjectObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code JsonObject} on compound JSON + * object. + * + * @param result + * Tests result record. + */ + private void testObjectOnsimpleObject(final TestResult result) { + System.out.println(" - for JsonObject on compound JSON object"); + final JsonObject in = createCompoundObject(); + final JsonObject patch = createSimpleObjectObject(); + final JsonObject check = createCompoundObjectWithObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeCommon.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeCommon.java new file mode 100644 index 00000000..1fc3f03a --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeCommon.java @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.mergetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests.
+ */ +public abstract class MergeCommon { + + /** Message content: "MERGE" operation. */ + private static final String MERGE_STR = "MERGE"; + + /** Message content: "DIFF" operation. */ + private static final String DIFF_STR = "DIFF"; + + /** Message content template for test failure log message: patch. */ + private static final String TEST_FAIL_PATCH = "Patch "; + + /** Message content template for test failure log message: failed on. */ + private static final String TEST_FAIL_ON = " failed on "; + + /** Message content template for test failure log message: value. */ + private static final String TEST_FAIL_VAL = " value"; + + /** Message content template for test failure log message: patch. */ + private static final String TEST_FAIL_FROM = "Diff from "; + + /** Message content template for test failure log message: failed on. */ + private static final String TEST_FAIL_TO = " to "; + + /** Message content template for test failure log message: value. */ + private static final String TEST_FAIL_FAIL = " failed"; + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @param message + * Assert message. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, final JsonValue out, + final String message) { + return out == null || !assertEquals(check, out, message); + } + + /** + * Test helper: Verify merge of JSON patch on provided JSON value and verify + * result using provided expected JSON value. + * + * @param result + * Test suite result. + * @param in + * Source JSON value to be modified. + * @param patch + * JSON patch to be done on source value. + * @param check + * Expected modified JSON object (used for operation check). + */ + protected void simpleMerge(final TestResult result, final JsonValue in, + final JsonValue patch, final JsonValue check) { + final JsonValue out = Json.createMergePatch(patch).apply(in); + if (operationFailed(check, out, MERGE_STR + " mismatch")) { + final String targetClassName = in.getValueType().name().toLowerCase(); + result.fail(testName(MERGE_STR, targetClassName), + testMergeMessage(valueToString(in), valueToString(patch))); + } + } + + /** + * Test helper: Verify diff on provided JSON values and verify result using + * provided expected JSON value. + * + * @param result + * Test suite result. + * @param src + * Source JSON value for diff. + * @param target + * Target JSON value for diff. + * @param diff + * Expected diff JSON object (used for operation check). + */ + protected void simpleDiff(final TestResult result, final JsonValue src, + final JsonValue target, final JsonValue diff) { + final JsonValue out = Json.createMergeDiff(src, target).toJsonValue(); + if (operationFailed(diff, out, DIFF_STR + " mismatch")) { + final String srcClassName = src.getValueType().name().toLowerCase(); + final String targetClassName = target.getValueType().name().toLowerCase(); + result.fail(testName(DIFF_STR, srcClassName, targetClassName), + testDiffMessage(valueToString(src), valueToString(target))); + } + } + + /** + * Build test name for test failure log message. + * + * @param operation + * Name of operation. + * @param targetType + * Name of the target (JSON value being modified) value type. + * @return Test name for test failure log message. + */ + protected String testName(final String operation, final String targetType) { + final StringBuilder sb = new StringBuilder( + operation.length() + targetType.length() + 1); + sb.append(operation); + sb.append(' '); + sb.append(targetType); + return sb.toString(); + } + + /** + * Build test name for test failure log message. + * + * @param operation + * Name of operation. + * @param srcType + * Name of the source (JSON value being used for modification) value + * type. + * @param targetType + * Name of the target (JSON value being modified) value type. + * @return Test name for test failure log message. + */ + protected String testName(final String operation, final String srcType, + final String targetType) { + final StringBuilder sb = new StringBuilder( + operation.length() + srcType.length() + targetType.length() + 2); + sb.append(operation); + sb.append(' '); + sb.append(srcType); + sb.append(','); + sb.append(targetType); + return sb.toString(); + } + + /** + * Build message content for test failure log message. + * + * @param in + * Source JSON value to be modified. + * @param patch + * JSON patch to be done on source value. + * @return Log message content. + */ + protected String testMergeMessage(final String in, final String patch) { + final StringBuilder sb = new StringBuilder( + TEST_FAIL_PATCH.length() + TEST_FAIL_ON.length() + + TEST_FAIL_VAL.length() + patch.length() + in.length()); + sb.append(TEST_FAIL_PATCH); + sb.append(patch); + sb.append(TEST_FAIL_ON); + sb.append(in); + sb.append(TEST_FAIL_VAL); + return sb.toString(); + } + + /** + * Build message content for test failure log message. + * + * @param src + * Source JSON value for diff. + * @param target + * Target JSON value for diff. + * @return Log message content. + */ + protected String testDiffMessage(final String src, final String target) { + final StringBuilder sb = new StringBuilder( + TEST_FAIL_FROM.length() + TEST_FAIL_TO.length() + + TEST_FAIL_FAIL.length() + src.length() + target.length()); + sb.append(TEST_FAIL_FROM); + sb.append(src); + sb.append(TEST_FAIL_TO); + sb.append(target); + sb.append(TEST_FAIL_FAIL); + return sb.toString(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeNonObject.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeNonObject.java new file mode 100644 index 00000000..dbcba22d --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeNonObject.java @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.mergetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility + * tests.
+ * Checks scenario described in + * {@see RFC 7396: 1. + * Introduction}: If the patch is anything other than an object, the result + * will always be to replace the entire target with the entire patch. + */ +public class MergeNonObject extends MergeCommon { + + /** + * Creates an instance of RFC 7396 non object patch test. + */ + MergeNonObject() { + super(); + } + + /** + * Test RFC 7396: Non object patch. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult("RFC 7396: Non object patch"); + System.out.println("Testing RFC 7396: Non object patch"); + testStringOnEmptyObject(result); + testStringOnSimpleObject(result); + testStringOnSimpleArray(result); + testIntOnEmptyObject(result); + testIntOnSimpleObject(result); + testIntOnSimpleArray(result); + testBoolOnEmptyObject(result); + testBoolOnSimpleObject(result); + testBoolOnSimpleArray(result); + testArrayOnEmptyObject(result); + testArrayOnCompoundObject(result); + testArrayOnSimpleArray(result); + return result; + } + + /** + * Test RFC 7396 patch and diff for {@code String} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testStringOnEmptyObject(final TestResult result) { + System.out.println(" - for String on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonValue patch = Json.createValue(STR_VALUE); + final JsonValue check = Json.createValue(STR_VALUE); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code String} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testStringOnSimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObjectWithStr(); + final JsonValue patch = Json.createValue(STR_VALUE); + final JsonValue check = Json.createValue(STR_VALUE); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code String} on empty JSON array. + * + * @param result + * Tests result record. + */ + private void testStringOnSimpleArray(final TestResult result) { + System.out.println(" - for String on simple JSON array"); + final JsonArray in = createStringArray2(); + final JsonValue patch = Json.createValue(STR_VALUE); + final JsonValue check = Json.createValue(STR_VALUE); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code int} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testIntOnEmptyObject(final TestResult result) { + System.out.println(" - for int on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonValue patch = Json.createValue(INT_VALUE); + final JsonValue check = Json.createValue(INT_VALUE); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code int} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testIntOnSimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObjectWithInt(); + final JsonValue patch = Json.createValue(INT_VALUE); + final JsonValue check = Json.createValue(INT_VALUE); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code int} on empty JSON array. + * + * @param result + * Tests result record. + */ + private void testIntOnSimpleArray(final TestResult result) { + System.out.println(" - for int on simple JSON array"); + final JsonArray in = createIntArray2(); + final JsonValue patch = Json.createValue(INT_VALUE); + final JsonValue check = Json.createValue(INT_VALUE); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code boolean} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testBoolOnEmptyObject(final TestResult result) { + System.out.println(" - for boolean on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonValue patch = toJsonValue(BOOL_VALUE); + final JsonValue check = toJsonValue(BOOL_VALUE); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code boolean} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testBoolOnSimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObjectWithBool(); + final JsonValue patch = toJsonValue(BOOL_VALUE); + final JsonValue check = toJsonValue(BOOL_VALUE); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code boolean} on empty JSON array. + * + * @param result + * Tests result record. + */ + private void testBoolOnSimpleArray(final TestResult result) { + System.out.println(" - for boolean on simple JSON array"); + final JsonArray in = createBoolArray2(); + final JsonValue patch = toJsonValue(BOOL_VALUE); + final JsonValue check = toJsonValue(BOOL_VALUE); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code JsonArray} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testArrayOnEmptyObject(final TestResult result) { + System.out.println(" - for JsonArray on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonArray patch = createStringArray1(); + final JsonArray check = createStringArray1(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code JsonArray} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testArrayOnCompoundObject(final TestResult result) { + System.out.println(" - for JsonArray on compound JSON object"); + final JsonObject in = createCompoundObject(); + final JsonValue patch = createStringArray2(); + final JsonValue check = createStringArray2(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code JsonArray} on empty JSON array. + * + * @param result + * Tests result record. + */ + private void testArrayOnSimpleArray(final TestResult result) { + System.out.println(" - for JsonArray on simple JSON array"); + final JsonArray in = createBoolArray2(); + final JsonValue patch = createIntArray2(); + final JsonValue check = createIntArray2(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeRFCSample.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeRFCSample.java new file mode 100644 index 00000000..37dd77ff --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeRFCSample.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.mergetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.JsonObject; + +import static jakarta.jsonp.tck.api.common.MergeRFCObject.*; + +// $Id$ +/** + * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility + * tests.
+ * Test based on + * {@see RFC 7396: 3. + * Example} objects. + */ +public class MergeRFCSample extends MergeCommon { + + /** + * Creates an instance of RFC 7396 value replacing test. + */ + MergeRFCSample() { + super(); + } + + /** + * Test RFC 7396: Adding non existing values. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult("RFC 7396: Example JSON object"); + System.out.println("Testing RFC 7396: Example JSON object"); + testMerge(result); + testDiff(result); + return result; + } + + /** + * Test RFC 7396 patch for example objects. + * + * @param result + * Tests result record. + */ + private void testMerge(final TestResult result) { + System.out.println(" - merge"); + final JsonObject in = createRFCSourceObject(); + final JsonObject patch = createRFCPatchObject(); + final JsonObject check = createRFCTargetObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 diff for example objects. + * + * @param result + * Tests result record. + */ + private void testDiff(final TestResult result) { + System.out.println(" - diff"); + final JsonObject in = createRFCSourceObject(); + final JsonObject diff = createRFCPatchObject(); + final JsonObject out = createRFCTargetObject(); + simpleDiff(result, in, out, diff); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeRemoveValue.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeRemoveValue.java new file mode 100644 index 00000000..039fb704 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeRemoveValue.java @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.mergetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.JsonObject; + +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility + * tests.
+ * Checks scenario described in + * {@see RFC 7396: 1. + * Introduction}: {@code null} values in the merge patch are given special + * meaning to indicate the removal of existing values in the target. + */ +public class MergeRemoveValue extends MergeCommon { + + /** + * Creates an instance of RFC 7396 value removal test. + */ + MergeRemoveValue() { + super(); + } + + /** + * Test RFC 7396: Removing existing values. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "RFC 7396: Remove existing values"); + System.out.println("Testing RFC 7396: Remove existing values"); + testStringOnEmptyObject(result); + testStringOnsimpleObject(result); + testIntOnEmptyObject(result); + testIntOnsimpleObject(result); + testBoolOnEmptyObject(result); + testBoolOnsimpleObject(result); + testObjectOnEmptyObject(result); + testObjectOnsimpleObject(result); + return result; + } + + /** + * Test RFC 7396 patch and diff for {@code String} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testStringOnEmptyObject(final TestResult result) { + System.out.println(" - for String to produce empty JSON object"); + final JsonObject in = createSimpleObjectStr(); + final JsonObject patch = createPatchRemoveStr(); + final JsonObject check = createEmptyObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testStringOnsimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObjectWithStr(); + final JsonObject patch = createPatchRemoveStr(); + final JsonObject check = createSimpleObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code int} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testIntOnEmptyObject(final TestResult result) { + System.out.println(" - for int to produce empty JSON object"); + final JsonObject in = createSimpleObjectInt(); + final JsonObject patch = createPatchRemoveInt(); + final JsonObject check = createEmptyObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testIntOnsimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObjectWithInt(); + final JsonObject patch = createPatchRemoveInt(); + final JsonObject check = createSimpleObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code boolean} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testBoolOnEmptyObject(final TestResult result) { + System.out.println(" - for boolean to produce empty JSON object"); + final JsonObject in = createSimpleObjectBool(); + final JsonObject patch = createPatchRemoveBool(); + final JsonObject check = createEmptyObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testBoolOnsimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObjectWithBool(); + final JsonObject patch = createPatchRemoveBool(); + final JsonObject check = createSimpleObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code JsonObject} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testObjectOnEmptyObject(final TestResult result) { + System.out.println(" - for JsonObject to produce empty JSON object"); + final JsonObject in = createSimpleObjectObject(); + final JsonObject patch = createPatchRemoveObject(); + final JsonObject check = createEmptyObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code JsonObject} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testObjectOnsimpleObject(final TestResult result) { + System.out.println(" - for JsonObject on compoubnd JSON object"); + final JsonObject in = createCompoundObjectWithObject(); + final JsonObject patch = createPatchRemoveObject(); + final JsonObject check = createCompoundObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeReplaceValue.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeReplaceValue.java new file mode 100644 index 00000000..5d66b442 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeReplaceValue.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.mergetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.JsonObject; + +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility + * tests.
+ * Checks scenario described in + * {@see RFC 7396: 1. + * Introduction}: If the target does contain the member, the value is + * replaced. + */ +public class MergeReplaceValue extends MergeCommon { + + /** + * Creates an instance of RFC 7396 value replacing test. + */ + MergeReplaceValue() { + super(); + } + + /** + * Test RFC 7396: Adding non existing values. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "RFC 7396: Replace existing values"); + System.out.println("Testing RFC 7396: Replace existing values"); + testStringOnsimpleObject(result); + testIntOnsimpleObject(result); + testBoolOnsimpleObject(result); + testObjectOnsimpleObject(result); + return result; + } + + /** + * Test RFC 7396 patch and diff for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testStringOnsimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject patch = createSimpleObjectMoveStr(); + final JsonObject check = createSimpleObjectMoveStr(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testIntOnsimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject patch = createSimpleObjectMoveInt(); + final JsonObject check = createSimpleObjectMoveInt(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testBoolOnsimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject patch = createSimpleObjectMoveBool(); + final JsonObject check = createSimpleObjectMoveBool(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + + /** + * Test RFC 7396 patch and diff for {@code JsonObject} on compound JSON + * object. + * + * @param result + * Tests result record. + */ + private void testObjectOnsimpleObject(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject patch = createSimpleObjectMoveObject(); + final JsonObject check = createSimpleObjectMoveObject(); + simpleMerge(result, in, patch, check); + simpleDiff(result, in, check, patch); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeTests.java new file mode 100644 index 00000000..b9cd494c --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/mergetests/MergeTests.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.mergetests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.lib.harness.Fault; + +import org.junit.Test; + +// $Id$ +/** + * RFC 7396: JavaScript Object Notation (JSON) Merge Patch compatibility + * tests.
+ * {@see RFC 7396}. + */ +public class MergeTests { + + /** + * Test JSON-P API response on + * {@see RFC 7396: 1. + * Introduction}: If the provided merge patch contains members that do not + * appear within the target, those members are added. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonMergeAddValueTest + * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; + * JSONP:JAVADOC:617; JSONP:JAVADOC:620; JSONP:JAVADOC:654; + * JSONP:JAVADOC:655; + * @test_Strategy: Test API response on various JSON values. + */ + @Test + public void jsonMergeAddValueTest() throws Fault { + MergeAddValue addTest = new MergeAddValue(); + final TestResult result = addTest.test(); + result.eval(); + } + + /** + * Test JSON-P API response on + * {@see RFC 7396: 1. + * Introduction}: If the target does contain the member, the value is + * replaced. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonMergeReplaceValueTest + * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; + * JSONP:JAVADOC:617; JSONP:JAVADOC:654; JSONP:JAVADOC:655; + * @test_Strategy: Test API response on various JSON values. + */ + @Test + public void jsonMergeReplaceValueTest() throws Fault { + MergeReplaceValue replaceTest = new MergeReplaceValue(); + final TestResult result = replaceTest.test(); + result.eval(); + } + + /** + * Test JSON-P API response on + * {@see RFC 7396: 1. + * Introduction}: {@code null} values in the merge patch are given special + * meaning to indicate the removal of existing values in the target. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonMergeRemoveValueTest + * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; + * JSONP:JAVADOC:617; JSONP:JAVADOC:654; JSONP:JAVADOC:655; + * @test_Strategy: Test API response on various JSON values. + */ + @Test + public void jsonMergeRemoveValueTest() throws Fault { + MergeRemoveValue removeTest = new MergeRemoveValue(); + final TestResult result = removeTest.test(); + result.eval(); + } + + /** + * Test JSON-P API response on + * {@see RFC 7396: 1. + * Introduction}: If the patch is anything other than an object, the + * result will always be to replace the entire target with the entire patch. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonMergeNonObjectTest + * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; + * JSONP:JAVADOC:617; JSONP:JAVADOC:654; JSONP:JAVADOC:655; + * JSONP:JAVADOC:583; JSONP:JAVADOC:584; + * @test_Strategy: Test API response on various JSON values. + */ + @Test + public void jsonMergeNonObjectTest() throws Fault { + MergeNonObject nonObjTest = new MergeNonObject(); + final TestResult result = nonObjTest.test(); + result.eval(); + } + + /** + * Test JSON-P API response on Test based on + * {@see RFC 7396: 3. + * Example} objects. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonMergeRFCSampleTest + * @assertion_ids: JSONP:JAVADOC:575; JSONP:JAVADOC:576; JSONP:JAVADOC:616; + * JSONP:JAVADOC:617; JSONP:JAVADOC:654; JSONP:JAVADOC:655; + * @test_Strategy: Test API response on RFC example objects. + */ + @Test + public void jsonMergeRFCSampleTest() throws Fault { + MergeRFCSample rfcSampleTest = new MergeRFCSample(); + final TestResult result = rfcSampleTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/CommonOperation.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/CommonOperation.java new file mode 100644 index 00000000..0ac66755 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/CommonOperation.java @@ -0,0 +1,507 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonException; +import jakarta.json.JsonPatch; +import jakarta.json.JsonPatchBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests. + */ +public abstract class CommonOperation { + + /** Message content template for test failure log message: operation name. */ + private static final String TEST_FAIL_OP = " operation"; + + /** Message content template for test failure log message: path. */ + private static final String TEST_FAIL_FOR = " for "; + + /** Message content template for test failure log message: failed. */ + private static final String TEST_FAIL_FAI = " failed"; + + /** + * Message content template for test failure log message: on target type + * prefix. + */ + private static final String TEST_FAIL_ON1 = " on JSON "; + + /** + * Message content template for test failure log message: on target type + * suffix. + */ + private static final String TEST_FAIL_ON2 = " value"; + + /** + * Message content template for test failure log message: patching execution + * method. + */ + private static final String TEST_FAIL_MET = " using "; + + /** + * Creates an instance of JavaScript Object Notation (JSON) compatibility + * tests. + */ + protected CommonOperation() { + super(); + } + + /** + * Tested operation name, e.g. {@code "ADD"}, {@code "REPLACE"}, + * {@code "MOVE"}. Child class callback. + * + * @return Operation name to be used in logs. + */ + protected abstract String operationName(); + + /** + * Create and initialize patch builder to contain patch operation to be + * applied. Child class callback. + * + * @param path + * JSON path of operation. + * @param value + * JSON value used in patch operation. + * @return Patch builder containing operation to be applied. + */ + protected abstract JsonPatchBuilder createOperationBuilder(final String path, + final Object value); + + /** + * Update patch builder to contain next patch operation to be applied. Child + * class callback. + * + * @param builder + * JSON patch builder to update. + * @param path + * JSON path of operation. + * @param value + * JSON value used in patch operation. + * @return Patch builder containing operation to be applied. + */ + protected abstract JsonPatchBuilder updateOperationBuilder( + final JsonPatchBuilder builder, final String path, final Object value); + + /** + * Test helper: Verify simple operation on provided JSON value and verify + * result using provided expected JSON value. Operation execution is done + * using all known methods to build and apply JSON patch. + * + * @param result + * Test suite result. + * @param in + * JSON value to be modified. + * @param check + * Expected modified JSON object (used for operation check). + * @param path + * JSON path of operation. + * @param value + * JSON value used in patch operation. + */ + protected void simpleOperation(final TestResult result, final JsonValue in, + final JsonValue check, final String path, final Object value) { + final JsonPatchBuilder builder = createOperationBuilder(path, value); + final JsonPatch patch = builder.build(); + JsonValue out; + try { + out = patchApply(patch, in); + } catch (JsonException e) { + out = null; + System.out.println( + " Exception for path \"" + path + "\" on " + valueToString(in)); + System.out.println(" " + e.getMessage()); + } + if (operationFailed(check, out)) { + final String targetClassName = in.getValueType().name().toLowerCase(); + final String operation = valueToString(patch.toJsonArray()); + System.out.println(" " + operation); + result.fail(testName(path, targetClassName), + testMessage(operation, path, valueToString(in))); + } + } + + /** + * Test helper: Verify set of operations on provided JSON value and verify + * result using provided expected JSON value. Verification is done using all + * known methods to build and apply JSON patch. This method allows custom + * patching of JSON array. Used for operations without value operand, e.g. + * REMOVE. Operation builder callback will receive {@code null} as value. + * + * @param result + * Test suite result. + * @param in + * JSON array to be modified. + * @param check + * Expected modified JSON array (used for operation check). + * @param paths + * JSON paths array of operations. + */ + protected void complexOperation(final TestResult result, final JsonArray in, + final JsonArray check, final String[] paths) { + final Object[] values = new Object[paths.length]; + for (int i = 0; i < paths.length; i++) { + values[i] = null; + } + complexOperation(result, in, check, paths, values); + } + + /** + * Test helper: Verify set of operations on provided JSON value and verify + * result using provided expected JSON value. Verification is done using all + * known methods to build and apply JSON patch. This method allows custom + * patching of JSON array. + * + * @param result + * Test suite result. + * @param in + * JSON array to be modified. + * @param check + * Expected modified JSON array (used for operation check). + * @param paths + * JSON paths array of operations. Pairs of {@code paths[i]} and + * {@code values[i]} are used for individual operations. + * @param values + * JSON values array used in patch operations. + */ + protected void complexOperation(final TestResult result, final JsonArray in, + final JsonArray check, final String[] paths, final Object[] values) { + if (paths.length != values.length) { + throw new IllegalArgumentException( + "Number of paths does not match number of indexes"); + } + final JsonPatchBuilder builder = prepareComplexBuilder(paths, values); + final JsonPatch patch = builder.build(); + final JsonValue out = patchApply(patch, in); + if (operationFailed(check, out)) { + final String operations = valueToString(patch.toJsonArray()); + final String targetClassName = in.getValueType().name().toLowerCase(); + System.out.println(" " + operations); + result.fail(testName(paths, targetClassName), + testMessage(operations, paths, valueToString(in))); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + + /** + * Builds JSON patch builder with set of operations stored in {@code paths} + * and {@code values}. + * + * @param paths + * JSON paths array of operations. Pairs of {@code paths[i]} and + * {@code values[i]} are used for individual operations. + * @param values + * JSON values array used in patch operations. + */ + private JsonPatchBuilder prepareComplexBuilder(final String[] paths, + final Object[] values) { + JsonPatchBuilder builder = Json.createPatchBuilder(); + for (int i = 0; i < paths.length; i++) { + builder = updateOperationBuilder(builder, paths[i], values[i]); + } + return builder; + } + + /** + * Test helper: Verify that operation on provided JSON value fails. Operation + * execution is done using all known methods to build and apply JSON patch. + * + * @param result + * Test suite result. + * @param in + * JSON value to be modified. + * @param path + * JSON path of operation. + * @param value + * JSON value used in patch operation. + */ + protected void simpleOperationFail(final TestResult result, + final JsonValue in, final String path, final Object value) { + try { + final JsonPatch patch = createOperationBuilder(path, value).build(); + patchApply(patch, in); + final String targetClassName = in.getValueType().name().toLowerCase(); + final String operation = valueToString(patch.toJsonArray()); + System.out.println( + " Failed for path \"" + path + "\" on " + valueToString(in)); + System.out.println(" " + operation); + result.fail(testName(path, targetClassName), + testMessage(operation, path, valueToString(in))); + } catch (JsonException e) { + // There are too many combinations to log them. + // System.out.println(" - Expected exception: "+e.getMessage()); + } + } + + /** + * Get source class name. + * + * @param value + * JSON value to search for class name. + * @return Class name of provided JSON value or {@code null} when this value + * has been {@code null}. + */ + protected String getSrcName(final Object value) { + return value != null ? value.getClass().getSimpleName() : null; + } + + /** + * Get source classes names. + * + * @param values + * JSON values to search for class name. + * @return Class name of provided JSON value or {@code null} when this value + * has been {@code null}. + */ + protected String[] getSrcNames(final Object[] values) { + if (values == null) { + return null; + } + final String[] names = new String[values.length]; + for (int i = 0; i < values.length; i++) { + names[i] = values[i] != null ? values[i].getClass().getSimpleName() + : null; + } + return names; + } + + /** + * Build test name for test failure log message. + * + * @param path + * JSON patch operation source path. + * @param targetType + * Name of target (JSON value being modified) value type. + * @return Test name for test failure log message. + */ + protected String testName(final String path, final String targetType) { + final String operationName = operationName(); + final int pathLen = path != null ? path.length() + 1 : 0; + final StringBuilder sb = new StringBuilder( + operationName.length() + pathLen + targetType.length() + 1); + sb.append(operationName); + if (pathLen > 0) { + sb.append(' '); + sb.append(path); + } + sb.append(' '); + sb.append(targetType); + return sb.toString(); + } + + /** + * Build test name for test failure log message. + * + * @param paths + * JSON patch operation source paths. + * @param targetType + * Name of target (JSON value being modified) value type. + * @return Test name for test failure log message. + */ + protected String testName(final String[] paths, final String targetType) { + final String operationName = operationName(); + final int pathsLen = paths != null ? paths.length : 0; + int pathsSize = 0; + for (int i = 0; i < pathsLen; i++) { + pathsSize += paths[i] != null ? paths[i].length() : NULL.length(); + if (i > 0) { + pathsSize += 1; + } + } + if (pathsLen > 1) { + pathsSize += 2; + } + final StringBuilder sb = new StringBuilder( + operationName.length() + pathsSize + targetType.length() + 2); + sb.append(operationName); + sb.append(' '); + if (pathsLen > 1) { + sb.append('['); + } + for (int i = 0; i < pathsLen; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(paths[i] != null ? paths[i] : NULL); + } + if (pathsLen > 1) { + sb.append(']'); + } + sb.append(' '); + sb.append(targetType); + return sb.toString(); + } + + /** + * Build message content for test failure log message. + * + * @param operation + * JSON patch operation being executed. + * @param path + * JSON patch operation source path. + * @param value + * Target value being modified. + * @return Log message content. + */ + protected String testMessage(final String operation, final String path, + final String value) { + final int tarLen = value != null + ? TEST_FAIL_ON1.length() + TEST_FAIL_ON2.length() + value.length() + : 0; + final StringBuilder sb = new StringBuilder( + operation.length() + TEST_FAIL_OP.length() + TEST_FAIL_FOR.length() + + path.length() + TEST_FAIL_FAI.length() + tarLen); + sb.append(operation); + sb.append(TEST_FAIL_OP); + sb.append(TEST_FAIL_FOR); + sb.append(path); + sb.append(TEST_FAIL_FAI); + if (tarLen > 0) { + sb.append(TEST_FAIL_ON1); + sb.append(value); + sb.append(TEST_FAIL_ON2); + } + return sb.toString(); + } + + /** + * Build message content for test failure log message. + * + * @param operation + * JSON patch operation being executed. + * @param paths + * JSON patch operation source paths. + * @param value + * Target value being modified. + * @return Log message content. + */ + protected String testMessage(final String operation, final String[] paths, + final String value) { + final int tarLen = value != null + ? TEST_FAIL_ON1.length() + TEST_FAIL_ON2.length() + value.length() + : 0; + final int pathsLen = paths != null ? paths.length : 0; + int pathsSize = 0; + for (int i = 0; i < pathsLen; i++) { + pathsSize += paths[i] != null ? paths[i].length() : NULL.length(); + if (i > 0) { + pathsSize += 1; + } + } + if (pathsLen > 1) { + pathsSize += 2; + } + final StringBuilder sb = new StringBuilder( + operation.length() + TEST_FAIL_OP.length() + TEST_FAIL_FOR.length() + + pathsSize + TEST_FAIL_FAI.length() + tarLen); + sb.append(operation); + sb.append(TEST_FAIL_OP); + sb.append(TEST_FAIL_FOR); + if (pathsLen > 1) { + sb.append('['); + } + for (int i = 0; i < pathsLen; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(paths[i] != null ? paths[i] : NULL); + } + if (pathsLen > 1) { + sb.append(']'); + } + sb.append(TEST_FAIL_FAI); + if (tarLen > 0) { + sb.append(TEST_FAIL_ON1); + sb.append(value); + sb.append(TEST_FAIL_ON2); + } + return sb.toString(); + } + + /** + * Build message content for test failure log message. + * + * @param paths + * JSON patch operation source path. + * @param targetType + * Name of target (JSON value being modified) value type. + * @return Log message content. + */ + protected String testMessage(final String[] paths, final String targetType) { + final String operationName = operationName(); + final int tarLen = targetType != null + ? TEST_FAIL_ON1.length() + TEST_FAIL_ON2.length() + targetType.length() + : 0; + int pathsLen = 0; + for (int i = 0; i < paths.length; i++) { + pathsLen += paths[i] != null ? paths[i].length() : NULL.length(); + if (i > 0) { + pathsLen += 1; + } + } + if (paths.length > 1) { + pathsLen += 2; + } + final StringBuilder sb = new StringBuilder( + operationName.length() + TEST_FAIL_OP.length() + TEST_FAIL_FOR.length() + + pathsLen + TEST_FAIL_FAI.length() + tarLen); + sb.append(operationName); + sb.append(TEST_FAIL_OP); + sb.append(TEST_FAIL_FOR); + if (paths.length > 1) { + sb.append('['); + } + for (int i = 0; i < paths.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(paths[i] != null ? paths[i] : NULL); + } + if (paths.length > 1) { + sb.append(']'); + } + sb.append(TEST_FAIL_FAI); + if (tarLen > 0) { + sb.append(TEST_FAIL_ON1); + sb.append(targetType); + sb.append(TEST_FAIL_ON2); + } + return sb.toString(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchCreate.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchCreate.java new file mode 100644 index 00000000..e5fc243d --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchCreate.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonPatch; +import jakarta.json.JsonPatchBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * JavaScript Object Notation (JSON) compatibility tests: {@link JsonPatch} API + * factory methods added in JSON-P 1.1.
+ */ +public class PatchCreate { + + /** + * Creates an instance of {@link JsonPatch} API factory methods added in + * JSON-P 1.1 test. + */ + PatchCreate() { + super(); + } + + /** + * Test {@link JsonPatch} factory method added in JSON-P 1.1. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonPatch API factory methods added in JSON-P 1.1."); + System.out.println("JsonPatch API factory methods added in JSON-P 1.1."); + testCreateDiff(result); + testCreatePatch(result); + testCreatePatchBuilder(result); + return result; + } + + /** + * Test {@link Json#createDiff(JsonStructure,JsonStructure)} method. + * + * @param result + * Test suite result. + */ + private void testCreateDiff(final TestResult result) { + System.out.println(" - Json#createDiff(JsonStructure,JsonStructure)"); + final JsonObject src = createSimpleObject(); + final JsonObject trg = createSimpleObjectWithStr(); + final JsonPatch patch = Json.createDiff(src, trg); + final JsonObject out = patch.apply(src); + if (operationFailed(trg, out)) { + result.fail("createDiff(JsonStructure,JsonStructure)", "Builder output " + + valueToString(out) + " value shall be " + valueToString(trg)); + } + } + + /** + * Test {@link Json#createPatch(JsonArray)} method. + * + * @param result + * Test suite result. + */ + private void testCreatePatch(final TestResult result) { + System.out.println(" - Json#createPatch(JsonArray)"); + final JsonObject src = createSimpleObject(); + final JsonObject trg = createSimpleObjectWithStr(); + final JsonArray patchArray = Json.createDiff(src, trg).toJsonArray(); + final JsonPatch patch = Json.createPatch(patchArray); + final JsonObject out = patch.apply(src); + if (operationFailed(trg, out)) { + result.fail("createPatch(JsonArray)", "Builder output " + + valueToString(out) + " value shall be " + valueToString(trg)); + } + } + + /** + * Test {@link Json#createPatchBuilder(JsonArray)} method. + * + * @param result + * Test suite result. + */ + private void testCreatePatchBuilder(final TestResult result) { + System.out.println(" - Json#createPatchBuilder(JsonArray)"); + final JsonObject src = createSimpleObject(); + final JsonObject trg = createSimpleObjectWithStr(); + final JsonArray patchArray = Json.createDiff(src, trg).toJsonArray(); + final JsonPatchBuilder patchBuilder = Json.createPatchBuilder(patchArray); + final JsonObject out = patchBuilder.build().apply(src); + if (operationFailed(trg, out)) { + result.fail("createPatchBuilder(JsonArray)", "Builder output " + + valueToString(out) + " value shall be " + valueToString(trg)); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null || !assertEquals(check, out); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationAdd.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationAdd.java new file mode 100644 index 00000000..73182846 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationAdd.java @@ -0,0 +1,586 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.JsonValueType; +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonPatch; +import jakarta.json.JsonPatchBuilder; +import jakarta.json.JsonValue; +import jakarta.json.JsonStructure; +import jakarta.json.Json; +import jakarta.json.JsonPointer; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
+ * {@see RFC 6902}. + *

+ * Implements + * {@see RFC 6902: + * 4.1. add} tests. + */ +class PatchOperationAdd extends CommonOperation { + + /** Tested operation name. */ + private final String OPERATION = "ADD"; + + /** + * Creates an instance of RFC 6902 add operation test. + */ + PatchOperationAdd() { + super(); + } + + /** + * Test RFC 6902 add operation. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult("RFC 6902 add operation"); + System.out.println("Testing RFC 6902 add operation:"); + testAddStringOnEmptyObject(result); + testAddStringOnSimpleObject(result); + testAddStringOnEmptyArray(result); + testAddStringOnSimpleArray(result); + testAddStringOnSimpleArray2(result); + testAddIntOnEmptyObject(result); + testAddIntOnSimpleObject(result); + testAddIntOnEmptyArray(result); + testAddIntOnSimpleArray(result); + testAddIntOnSimpleArray2(result); + testAddBooleanOnEmptyObject(result); + testAddBooleanOnSimpleObject(result); + testAddBooleanOnEmptyArray(result); + testAddBooleanOnSimpleArray(result); + testAddBooleanOnSimpleArray2(result); + testAddObjectOnEmptyObject(result); + testAddObjectOnSimpleObject(result); + testAddObjectOnEmptyArray(result); + testAddObjectOnSimpleArray(result); + testAddObjectOnSimpleArray2(result); + testAddArrayToReplaceObject(result); + testAddArrayToReplaceDocument(result); + testAddStringArrayToStringArray(result); + testAddStringToNonExistingObject(result); + return result; + } + + /** + * Test RFC 6902 add operation for {@code String} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testAddStringOnEmptyObject(final TestResult result) { + System.out.println(" - for String on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject check = createSimpleObjectStr(); + simpleOperation(result, in, check, STR_PATH, STR_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code String} on empty JSON array. Only + * allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testAddStringOnEmptyArray(final TestResult result) { + System.out.println(" - for String on empty JSON array"); + final JsonArray in = createEmptyArray(); + final JsonArray check = createEmptyArrayWithStr(); + simpleOperation(result, in, check, "/0", STR_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testAddStringOnSimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject check = createSimpleObjectWithStr(); + simpleOperation(result, in, check, STR_PATH, STR_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code String} on simple JSON array. Using + * index {@code 0} to add {@code String} before already existing element and + * index {@code 1} to add {@code String} after already existing element. + * + * @param result + * Tests result record. + */ + private void testAddStringOnSimpleArray(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 1"); + final JsonArray in = createStringArray1(); + final JsonArray checkBefore = createSimpleStringArrayWithStrBefore(); + final JsonArray checkAfter = createSimpleStringArrayWithStrAfter(); + // Add before. + simpleOperation(result, in, checkBefore, "/0", STR_VALUE); + // Add after. + simpleOperation(result, in, checkAfter, "/1", STR_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code String}s on simple JSON array. + * Starting with an array of size 2. + *

    + *
  • Adding {@code String} at the end, in the middle and at the beginning of + * this array. + *
  • Adding {@code String} at the beginning, in the middle and at the end of + * this array. + *
+ * + * @param result + * Tests result record. + */ + private void testAddStringOnSimpleArray2(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 2"); + final JsonArray in = createStringArray2(); + final JsonArray check = createSimpleStringArray5(); + complexOperation(result, in, check, new String[] { "/2", "/1", "/0" }, + new String[] { STR_VALUE_5, STR_VALUE_3, STR_VALUE_1 }); + complexOperation(result, in, check, new String[] { "/0", "/2", "/4" }, + new String[] { STR_VALUE_1, STR_VALUE_3, STR_VALUE_5 }); + } + + /** + * Test RFC 6902 add operation for {@code int} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testAddIntOnEmptyObject(final TestResult result) { + System.out.println(" - for int on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject check = createSimpleObjectInt(); + simpleOperation(result, in, check, INT_PATH, INT_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code int} on empty JSON array. Only + * allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testAddIntOnEmptyArray(final TestResult result) { + System.out.println(" - for int on empty JSON array"); + final JsonArray in = createEmptyArray(); + final JsonArray check = createEmptyArrayWithInt(); + simpleOperation(result, in, check, "/0", INT_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testAddIntOnSimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject check = createSimpleObjectWithInt(); + simpleOperation(result, in, check, INT_PATH, INT_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code int} on simple JSON array. Using + * index {@code 0} to add {@code int} before already existing element and + * index {@code 1} to add {@code int} after already existing element. + * + * @param result + * Tests result record. + */ + private void testAddIntOnSimpleArray(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 1"); + final JsonArray in = createIntArray1(); + final JsonArray checkBefore = createSimpleIntArrayWithIntBefore(); + final JsonArray checkAfter = createSimpleIntArrayWithIntAfter(); + // Add before. + simpleOperation(result, in, checkBefore, "/0", INT_VALUE); + // Add after. + simpleOperation(result, in, checkAfter, "/1", INT_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code int}s on simple JSON array. Starting + * with an array of size 2. + *
    + *
  • Adding {@code int} at the end, in the middle and at the beginning of + * this array. + *
  • Adding {@code int} at the beginning, in the middle and at the end of + * this array. + *
+ * + * @param result + * Tests result record. + */ + private void testAddIntOnSimpleArray2(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 2"); + final JsonArray in = createIntArray2(); + final JsonArray check = createSimpleIntArray5(); + complexOperation(result, in, check, new String[] { "/2", "/1", "/0" }, + new Integer[] { INT_VALUE_5, INT_VALUE_3, INT_VALUE_1 }); + complexOperation(result, in, check, new String[] { "/0", "/2", "/4" }, + new Integer[] { INT_VALUE_1, INT_VALUE_3, INT_VALUE_5 }); + } + + /** + * Test RFC 6902 add operation for {@code boolean} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testAddBooleanOnEmptyObject(final TestResult result) { + System.out.println(" - for boolean on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject check = createSimpleObjectBool(); + simpleOperation(result, in, check, BOOL_PATH, BOOL_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code boolean} on empty JSON array. Only + * allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testAddBooleanOnEmptyArray(final TestResult result) { + System.out.println(" - for boolean on empty JSON array"); + final JsonArray in = createEmptyArray(); + final JsonArray check = createEmptyArrayWithBool(); + simpleOperation(result, in, check, "/0", BOOL_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testAddBooleanOnSimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject check = createSimpleObjectWithBool(); + simpleOperation(result, in, check, BOOL_PATH, BOOL_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code boolean} on simple JSON array. Using + * index {@code 0} to add {@code boolean} before already existing element and + * index {@code 1} to add {@code boolean} after already existing element. + * + * @param result + * Tests result record. + */ + private void testAddBooleanOnSimpleArray(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 1"); + final JsonArray in = createBoolArray1(); + final JsonArray checkBefore = createSimpleBoolArrayWithBoolBefore(); + final JsonArray checkAfter = createSimpleBoolArrayWithBoolAfter(); + // Add before. + simpleOperation(result, in, checkBefore, "/0", BOOL_FALSE); + // Add after. + simpleOperation(result, in, checkAfter, "/1", BOOL_FALSE); + } + + /** + * Test RFC 6902 add operation for {@code boolean}s on simple JSON array. + * Starting with an array of size 2. + *
    + *
  • Adding {@code boolean} at the end, in the middle and at the beginning + * of this array. + *
  • Adding {@code boolean} at the beginning, in the middle and at the end + * of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testAddBooleanOnSimpleArray2(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 2"); + final JsonArray in = createBoolArray2(); + final JsonArray check = createSimpleBoolArray5(); + complexOperation(result, in, check, new String[] { "/2", "/1", "/0" }, + new Boolean[] { BOOL_TRUE, BOOL_TRUE, BOOL_FALSE }); + complexOperation(result, in, check, new String[] { "/0", "/2", "/4" }, + new Boolean[] { BOOL_FALSE, BOOL_TRUE, BOOL_TRUE }); + } + + /** + * Test RFC 6902 add operation for {@code JsonObject} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testAddObjectOnEmptyObject(final TestResult result) { + System.out.println(" - for JsonObject on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject check = createSimpleObjectObject(); + simpleOperation(result, in, check, OBJ_PATH, OBJ_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code JsonObject} on empty JSON array. + * Only allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testAddObjectOnEmptyArray(final TestResult result) { + System.out.println(" - for JsonObject on empty JSON array"); + final JsonArray in = createEmptyArray(); + final JsonArray check = createEmptyArrayWithObject(); + simpleOperation(result, in, check, "/0", OBJ_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code JsonObject} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testAddObjectOnSimpleObject(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON object"); + final JsonObject in = createCompoundObject(); + final JsonObject check = createCompoundObjectWithObject(); + simpleOperation(result, in, check, OBJ_PATH, OBJ_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code JsonObject} on simple JSON array. + * Using index {@code 0} to add {@code JsonObject} before already existing + * element and index {@code 1} to add {@code JsonObject} after already + * existing element. + * + * @param result + * Tests result record. + */ + private void testAddObjectOnSimpleArray(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 1"); + final JsonArray in = createObjectArray1(); + final JsonArray checkBefore = createSimpleObjectArrayWithObjectBefore(); + final JsonArray checkAfter = createSimpleObjectArrayWithObjectAfter(); + // Add before. + simpleOperation(result, in, checkBefore, "/0", OBJ_VALUE); + // Add after. + simpleOperation(result, in, checkAfter, "/1", OBJ_VALUE); + } + + /** + * Test RFC 6902 add operation for {@code JsonObject}s on simple JSON array. + * Starting with an array of size 2. + *
    + *
  • Adding {@code JsonObject} at the end, in the middle and at the + * beginning of this array. + *
  • Adding {@code JsonObject} at the beginning, in the middle and at the + * end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testAddObjectOnSimpleArray2(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 2"); + final JsonArray in = createObjectArray2(); + final JsonArray check = createSimpleObjectArray5(); + complexOperation(result, in, check, new String[] { "/2", "/1", "/0" }, + new JsonObject[] { OBJ_VALUE_5, OBJ_VALUE_3, OBJ_VALUE_1 }); + complexOperation(result, in, check, new String[] { "/0", "/2", "/4" }, + new JsonObject[] { OBJ_VALUE_1, OBJ_VALUE_3, OBJ_VALUE_5 }); + } + + // Tests based on RFC 6902 definitions and examples. + + /** + * Test that existing target object is replaced by specified array when ADD + * operation is applied. + * {@see RFC 6902: + * 4.1. add}:
+ * When the operation is applied, the target location MUST reference one of: + *
    + *
  • A member to add to an existing object - whereupon the supplied value is + * added to that object at the indicated location. If the member already + * exists, it is replaced by the specified value.
  • + *
  • ...
  • + *
+ */ + private void testAddArrayToReplaceObject(final TestResult result) { + System.out.println(" - for JsonArray to replace JsonObject"); + final JsonObject in = createCompoundObject(); + final JsonObject check = createCompoundObjectWithObjectReplaced(); + final JsonArray value = createSimpleStringArray5(); + simpleOperation(result, in, check, DEF_OBJ_PATH, value); + } + + /** + * Test that whole document is replaced by specified array when ADD operation + * is applied with root pointer. + * {@see RFC 6902: + * 4.1. add}:
+ * When the operation is applied, the target location MUST reference one of: + *
    + *
  • The root of the target document - whereupon the specified value becomes + * the entire content of the target document.
  • + *
  • ...
  • + *
+ */ + private void testAddArrayToReplaceDocument(final TestResult result) { + System.out.println(" - for JsonArray to replace whole document"); + final JsonObject in = createCompoundObject(); + final JsonArray check = createSimpleStringArray5(); + final JsonArray value = createSimpleStringArray5(); + // Instance being replaced is JsonObject, instance being added is JsonArray. + // The only API method allowing + // this is the one working with JsonStructure. New builder instance is used + // for each of the cases. + final JsonPatch patch1 = builderAdd(Json.createPatchBuilder(), "", value) + .build(); + final JsonValue out1 = patch1.apply((JsonStructure) in); + if (!assertEquals(check, out1)) { + final String className = value.getClass().getSimpleName(); + result.fail("ADD " + className + " to compound object", + "ADD operation for " + className + " failed on compound value"); + } + } + + /** + * Test ADD operation of an array of {@code String}s into existing array of + * {@code String}s. This scenario is inspired by + * {@see RFC 6902: + * 4.1. add} operation example {@code { "op": "add", "path": "/a/b/c", + * "value": [ "foo", "bar" ] }} and following explanation of this operation on + * an array: + *
    + *
  • An element to add to an existing array - whereupon the supplied value + * is added to the array at the indicated location. Any elements at or above + * the specified index are shifted one position to the right. The specified + * index MUST NOT be greater than the number of elements in the array. If the + * "-" character is used to index the end of the array (see [RFC6901]), this + * has the effect of appending the value to the array.
  • + *
+ */ + private void testAddStringArrayToStringArray(final TestResult result) { + System.out.println(" - for String array to be added to existing String array"); + final JsonArray in = createStringArray2(); + final JsonArray check = createStringArray2WithStringArrayInTheMiddle(); + final JsonArray value = createStringInnerArray2(); + simpleOperation(result, in, check, "/1", value); + } + + /** + * Test ADD operation on non existing JsonObject. This scenario is described + * in {@see RFC + * 6902: 4.1. add} error handling samples. Test is trying to ADD value { + * "address" : "In a galaxy far far away"} into object { "name" : "John Smith" + * } using path "/child/address". Even "/child" path does not exist so this + * operation must fail. + * + */ + private void testAddStringToNonExistingObject(final TestResult result) { + System.out.println(" - for String to be added to non existing JsonObject"); + final JsonObject in = createSimpleObject(); + final JsonValue value = Json.createValue(STR_VALUE); + final String path = DEF_OBJ_PATH + STR_PATH; + final JsonPointer ptr = Json.createPointer(path); + simpleOperationFail(result, in, path, value); + } + + /** + * Tested operation name {@code "MOVE"}. + * + * @return Operation name to be used in logs. + */ + @Override + protected String operationName() { + return OPERATION; + } + + /** + * Create and initialize patch builder to contain ADD operation to be applied. + * + * @param path + * JSON path of value to be added. + * @param value + * JSON Value to be added. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder createOperationBuilder(final String path, + final Object value) { + return builderAdd(Json.createPatchBuilder(), path, value); + } + + /** + * Update patch builder to contain next ADD operation to be applied. + * + * @param builder + * JSON patch builder to update. + * @param path + * JSON path of value to be added. + * @param value + * JSON Value to be added. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder updateOperationBuilder( + final JsonPatchBuilder builder, final String path, final Object value) { + return builderAdd(builder, path, value); + } + + /** + * Add {@code value} at {@code path} to provided JSON patch builder. + * + * @param builder + * Target JSON patch builder. + * @param path + * JSON path of value to be added. + * @param value + * Value to be added at given JSON path. + * @return JSON patch builder containing new {@code value} at {@code path} + * added. + */ + @SuppressWarnings("UnnecessaryUnboxing") + private static JsonPatchBuilder builderAdd(final JsonPatchBuilder builder, + final String path, final Object value) { + switch (JsonValueType.getType(value.getClass())) { + case String: + return builder.add(path, (String) value); + case Integer: + return builder.add(path, ((Integer) value).intValue()); + case Boolean: + return builder.add(path, ((Boolean) value).booleanValue()); + case JsonValue: + return builder.add(path, (JsonValue) value); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationCopy.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationCopy.java new file mode 100644 index 00000000..f0765c60 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationCopy.java @@ -0,0 +1,298 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonPatchBuilder; + +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
+ * {@see RFC 6902}. + *

+ * Implements + * {@see RFC 6902: + * 4.5. copy} tests. + */ +public class PatchOperationCopy extends CommonOperation { + + /** Tested operation name. */ + private final String OPERATION = "COPY"; + + /** + * Creates an instance of RFC 6902 replace operation test. + */ + PatchOperationCopy() { + super(); + } + + /** + * Test RFC 6902 COPY operation. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult("RFC 6902 copy operation"); + System.out.println("Testing RFC 6902 copy operation:"); + testCopyStringOnSimpleObject(result); + testCopyStringOnSimpleArray(result); + testCopyIntOnSimpleObject(result); + testCopyIntOnSimpleArray(result); + testCopyBoolOnSimpleObject(result); + testCopyBoolOnSimpleArray(result); + testCopyObjectOnSimpleObject(result); + testCopyObjectOnSimpleArray(result); + testCopyStringOnCompoundObject(result); + testCopyOfNonExistingLocationInObject(result); + testCopyOfNonExistingLocationInArray(result); + + return result; + } + + /** + * Test RFC 6902 COPY operation for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testCopyStringOnSimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObjectStr(); + final JsonObject check = createSimpleObjectCopyStr(); + simpleOperation(result, in, check, STR_PATH, DEF_PATH); + } + + /** + * Test RFC 6902 COPY operation for {@code String} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testCopyStringOnSimpleArray(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 2"); + final JsonArray in = createStringArray2(); + simpleOperation(result, in, createStringArray2Copy1to0(), "/1", "/0"); + simpleOperation(result, in, createStringArray2Copy0to2(), "/0", "/2"); + simpleOperation(result, in, createStringArray2Copy0to1(), "/0", "/1"); + } + + /** + * Test RFC 6902 COPY operation for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testCopyIntOnSimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObjectInt(); + final JsonObject check = createSimpleObjectCopyInt(); + simpleOperation(result, in, check, INT_PATH, DEF_PATH); + } + + /** + * Test RFC 6902 COPY operation for {@code int} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testCopyIntOnSimpleArray(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 2"); + final JsonArray in = createIntArray2(); + simpleOperation(result, in, createIntArray2Copy1to0(), "/1", "/0"); + simpleOperation(result, in, createIntArray2Copy0to2(), "/0", "/2"); + simpleOperation(result, in, createIntArray2Copy0to1(), "/0", "/1"); + } + + /** + * Test RFC 6902 COPY operation for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testCopyBoolOnSimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObjectBool(); + final JsonObject check = createSimpleObjectCopyBool(); + simpleOperation(result, in, check, BOOL_PATH, DEF_PATH); + } + + /** + * Test RFC 6902 COPY operation for {@code boolean} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testCopyBoolOnSimpleArray(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 2"); + final JsonArray in = createBoolArray2(); + simpleOperation(result, in, createBoolArray2Copy1to0(), "/1", "/0"); + simpleOperation(result, in, createBoolArray2Copy0to2(), "/0", "/2"); + simpleOperation(result, in, createBoolArray2Copy0to1(), "/0", "/1"); + } + + /** + * Test RFC 6902 COPY operation for {@code JsonObject} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testCopyObjectOnSimpleObject(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON object"); + final JsonObject in = createSimpleObjectObject(); + final JsonObject check = createSimpleObjectCopyObject(); + simpleOperation(result, in, check, OBJ_PATH, DEF_PATH); + } + + /** + * Test RFC 6902 COPY operation for {@code JsonObject} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testCopyObjectOnSimpleArray(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 2"); + final JsonArray in = createObjectArray2(); + simpleOperation(result, in, createObjectArray2Copy1to0(), "/1", "/0"); + simpleOperation(result, in, createObjectArray2Copy0to2(), "/0", "/2"); + simpleOperation(result, in, createObjectArray2Copy0to1(), "/0", "/1"); + } + + /** + * Test RFC 6902 COPY operation for {@code String} on compound JSON object. + * Copied value overwrites an existing value. + * + * @param result + * Tests result record. + */ + private void testCopyStringOnCompoundObject(final TestResult result) { + System.out.println(" - for String on compound JSON object"); + final JsonObject in = createCompoundObject(); + final JsonObject check = createCompoundObjectCopyValue(); + simpleOperation(result, in, check, DEF_PATH, DEF_OBJ_PATH + DEF_PATH); + } + + // Tests based on RFC 6902 definitions and examples. + + /** + * Test RFC 6902 COPY operation for non existing location in object. + * {@see RFC 6902: + * 4.5. copy} defines:
+ * The "from" location MUST exist for the operation to be successful. + */ + private void testCopyOfNonExistingLocationInObject(final TestResult result) { + System.out.println(" - for non existing location in JsonObject"); + final JsonObject[] objsIn = new JsonObject[] { createEmptyObject(), + createSimpleObject(), createCompoundObject() }; + final String[] paths = new String[] { STR_PATH, INT_PATH, BOOL_PATH, + OBJ_PATH }; + final Object[] values = new Object[] { OBJ_PATH, BOOL_PATH, INT_PATH, + STR_PATH }; + // Go trough all objects + for (int i = 0; i < objsIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + simpleOperationFail(result, objsIn[i], paths[j], values[i]); + } + } + } + + /** + * Test RFC 6902 COPY operation for non existing location in array. + * {@see RFC 6902: + * 4.5. copy} defines:
+ * The "from" location MUST exist for the operation to be successful. + */ + private void testCopyOfNonExistingLocationInArray(final TestResult result) { + System.out.println(" - for non existing location in JsonArray"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray1(), createIntArray2(), createSimpleBoolArray5(), + createObjectArray2() }; + final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", + STR_PATH + "/0" }; + final Object[] values = new Object[] { "/0", "/1", "/2", "/5", "/1" }; + // Go trough all arrays + for (int i = 0; i < arraysIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + simpleOperationFail(result, arraysIn[i], paths[j], values[i]); + } + } + } + + /** + * Tested operation name {@code "COPY"}. + * + * @return Operation name to be used in logs. + */ + @Override + protected String operationName() { + return OPERATION; + } + + /** + * Create and initialize patch builder to contain COPY operation to be + * applied. + * + * @param path + * Source JSON path of COPY operation. + * @param value + * Target JSON path of COPY operation. Must be instance of + * {@link String}. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder createOperationBuilder(final String path, + final Object value) { + if (value instanceof String) { + // System.out.println(" COPY "+path+" -> "+(String)value); + return Json.createPatchBuilder().copy((String) value, path); + } else { + throw new IllegalArgumentException( + "Argument \"value\" is not an instance of String"); + } + } + + /** + * Update patch builder to contain next COPY operation to be applied. + * + * @param builder + * JSON patch builder to update. + * @param path + * Source JSON path of COPY operation. + * @param value + * Target JSON path of COPY operation. Must be instance of + * {@link String}. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder updateOperationBuilder( + final JsonPatchBuilder builder, final String path, final Object value) { + if (value instanceof String) { + // System.out.println(" COPY "+path+" -> "+(String)value); + return builder.copy((String) value, path); + } else { + throw new IllegalArgumentException( + "Argument \"value\" is not an instance of String"); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationEnum.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationEnum.java new file mode 100644 index 00000000..82f0c6b3 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationEnum.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.JsonPatch; + +// $Id$ +/** + * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
+ * {@see RFC 6902}. + *

+ * Test {@link JsonPatch.Operation} enumeration. + */ +public class PatchOperationEnum { + + /** + * Creates an instance of {@link JsonPatch.Operation} enumeration test. + */ + PatchOperationEnum() { + super(); + } + + /** + * Test {@link JsonPatch.Operation} enumeration. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "JsonPatch.Operation enumeration test"); + System.out.println("JsonPatch.Operation enumeration test"); + testOperationName(result); + testOperationValueOf(result); + return result; + } + + /** + * Test {@link JsonPatch.Operation#fromOperationName(String)} and + * {@link JsonPatch.Operation#operationName()} methods. + * + * @param result + * Tests result record. + */ + private void testOperationName(final TestResult result) { + System.out.println(" - fromOperationName(String) and operationName(String)"); + for (final JsonPatch.Operation op : JsonPatch.Operation.values()) { + final String opName = op.operationName(); + final JsonPatch.Operation opOut = JsonPatch.Operation + .fromOperationName(opName); + final int opNameLen = opName.length(); + boolean opNameLc = true; + for (int i = 0; opNameLc && i < opNameLen; i++) { + opNameLc = Character.isLowerCase(opName.charAt(i)); + } + if (!opNameLc) { + result.fail("operationName(String)", + "Returned value " + opName + " is not lower case String"); + } + if (op != opOut) { + result.fail("fromOperationName(String) and operationName(String)", + "Returned operation " + opOut.name() + " shall be " + op.name()); + } + } + } + + /** + * Test {@code JsonPatch.Operation#valueOf(String)} method. + * + * @param result + * Tests result record. + */ + private void testOperationValueOf(final TestResult result) { + System.out.println(" - valueOf(String)"); + for (final JsonPatch.Operation op : JsonPatch.Operation.values()) { + final String opName = op.name(); + final JsonPatch.Operation opOut = JsonPatch.Operation.valueOf(opName); + if (op != opOut) { + result.fail("valueOf(String)", + "Returned operation " + opOut.name() + " shall be " + op.name()); + } + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationMove.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationMove.java new file mode 100644 index 00000000..0286f524 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationMove.java @@ -0,0 +1,455 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonException; +import jakarta.json.JsonObject; +import jakarta.json.JsonPatch; +import jakarta.json.JsonPatchBuilder; +import jakarta.json.JsonPointer; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
+ * {@see RFC 6902}. + *

+ * Implements + * {@see RFC 6902: + * 4.4. move} tests. + */ +public class PatchOperationMove extends CommonOperation { + + /** Tested operation name. */ + private final String OPERATION = "MOVE"; + + /** + * Creates an instance of RFC 6902 replace operation test. + */ + PatchOperationMove() { + super(); + } + + /** + * Test RFC 6902 MOVE operation. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult("RFC 6902 move operation"); + System.out.println("Testing RFC 6902 move operation:"); + testMoveStringOnSimpleObject(result); + testMoveStringOnSimpleArray(result); + testMoveStringOnSimpleArray2(result); + testMoveIntOnSimpleObject(result); + testMoveIntOnSimpleArray(result); + testMoveIntOnSimpleArray2(result); + testMoveBoolOnSimpleObject(result); + testMoveBoolOnSimpleArray(result); + testMoveBoolOnSimpleArray2(result); + testMoveObjectOnSimpleObject(result); + testMoveObjectOnSimpleArray(result); + testMoveObjectOnSimpleArray2(result); + testMoveStringOnCompoundObject(result); + testMoveOfNonExistingLocationInObject(result); + testMoveOfNonExistingLocationInArray(result); + testMoveVsRemoveAddOnSelfContainedPath(result); + return result; + } + + /** + * Test RFC 6902 MOVE operation for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testMoveStringOnSimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObjectStr(); + final JsonObject check = createSimpleObjectMoveStr(); + simpleOperation(result, in, check, STR_PATH, DEF_PATH); + } + + /** + * Test RFC 6902 MOVE operation for {@code String} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testMoveStringOnSimpleArray(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 2"); + final JsonArray in = createStringArray2(); + final JsonArray check = createStringArray2R(); + simpleOperation(result, in, in, "/0", "/0"); + simpleOperation(result, in, check, "/1", "/0"); + simpleOperation(result, in, check, "/0", "/1"); + simpleOperation(result, in, check, "/0", "/-"); + } + + /** + * Test RFC 6902 MOVE operation for {@code String} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testMoveStringOnSimpleArray2(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 5"); + final JsonArray in = createSimpleStringArray5(); + final JsonArray check = createSimpleStringArray5R(); + complexOperation(result, in, check, new String[] { "/3", "/0", "/3", "/4" }, + new String[] { "/1", "/2", "/1", "/0" }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/0", "/2" }, + new String[] { "/-", "/2", "/3", "/0" }); + } + + /** + * Test RFC 6902 MOVE operation for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testMoveIntOnSimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObjectInt(); + final JsonObject check = createSimpleObjectMoveInt(); + simpleOperation(result, in, check, INT_PATH, DEF_PATH); + } + + /** + * Test RFC 6902 MOVE operation for {@code int} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testMoveIntOnSimpleArray(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 2"); + final JsonArray in = createIntArray2(); + final JsonArray check = createIntArray2R(); + simpleOperation(result, in, in, "/0", "/0"); + simpleOperation(result, in, check, "/1", "/0"); + simpleOperation(result, in, check, "/0", "/1"); + simpleOperation(result, in, check, "/0", "/-"); + } + + /** + * Test RFC 6902 MOVE operation for {@code int} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testMoveIntOnSimpleArray2(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 5"); + final JsonArray in = createSimpleIntArray5(); + final JsonArray check = createSimpleIntArray5R(); + complexOperation(result, in, check, new String[] { "/3", "/0", "/3", "/4" }, + new String[] { "/1", "/2", "/1", "/0" }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/0", "/2" }, + new String[] { "/-", "/2", "/3", "/0" }); + } + + /** + * Test RFC 6902 MOVE operation for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testMoveBoolOnSimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObjectBool(); + final JsonObject check = createSimpleObjectMoveBool(); + simpleOperation(result, in, check, BOOL_PATH, DEF_PATH); + } + + /** + * Test RFC 6902 MOVE operation for {@code boolean} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testMoveBoolOnSimpleArray(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 2"); + final JsonArray in = createBoolArray2(); + final JsonArray check = createBoolArray2R(); + simpleOperation(result, in, in, "/0", "/0"); + simpleOperation(result, in, check, "/1", "/0"); + simpleOperation(result, in, check, "/0", "/1"); + simpleOperation(result, in, check, "/0", "/-"); + } + + /** + * Test RFC 6902 MOVE operation for {@code boolean} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testMoveBoolOnSimpleArray2(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 5"); + final JsonArray in = createSimpleBoolArray5(); + final JsonArray check = createSimpleBoolArray5R(); + complexOperation(result, in, check, new String[] { "/3", "/0", "/3", "/4" }, + new String[] { "/1", "/2", "/1", "/0" }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/0", "/2" }, + new String[] { "/-", "/2", "/3", "/0" }); + } + + /** + * Test RFC 6902 MOVE operation for {@code JsonObject} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testMoveObjectOnSimpleObject(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON object"); + final JsonObject in = createSimpleObjectObject(); + final JsonObject check = createSimpleObjectMoveObject(); + simpleOperation(result, in, check, OBJ_PATH, DEF_PATH); + } + + /** + * Test RFC 6902 MOVE operation for {@code JsonObject} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testMoveObjectOnSimpleArray(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 2"); + final JsonArray in = createObjectArray2(); + final JsonArray check = createObjectArray2R(); + simpleOperation(result, in, in, "/0", "/0"); + simpleOperation(result, in, check, "/1", "/0"); + simpleOperation(result, in, check, "/0", "/1"); + simpleOperation(result, in, check, "/0", "/-"); + } + + /** + * Test RFC 6902 MOVE operation for {@code JsonObject} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testMoveObjectOnSimpleArray2(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 5"); + final JsonArray in = createSimpleObjectArray5(); + final JsonArray check = createSimpleObjectArray5R(); + complexOperation(result, in, check, new String[] { "/3", "/0", "/3", "/4" }, + new String[] { "/1", "/2", "/1", "/0" }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/0", "/2" }, + new String[] { "/-", "/2", "/3", "/0" }); + } + + /** + * Test RFC 6902 MOVE operation for {@code String} on compound JSON object. + * Moved value overwrites an existing value. + * + * @param result + * Tests result record. + */ + private void testMoveStringOnCompoundObject(final TestResult result) { + System.out.println(" - for String on compound JSON object"); + final JsonObject in = createCompoundObject(); + final JsonObject check = createCompoundObjectMoveValue(); + simpleOperation(result, in, check, DEF_PATH, DEF_OBJ_PATH + DEF_PATH); + } + + // Tests based on RFC 6902 definitions and examples. + + /** + * Test RFC 6902 MOVE operation for non existing location in object. + * {@see RFC 6902: + * 4.4. move} defines:
+ * The "from" location MUST exist for the operation to be successful. + */ + private void testMoveOfNonExistingLocationInObject(final TestResult result) { + System.out.println(" - for non existing location in JsonObject"); + final JsonObject[] objsIn = new JsonObject[] { createEmptyObject(), + createSimpleObject(), createCompoundObject() }; + final String[] paths = new String[] { STR_PATH, INT_PATH, BOOL_PATH, + OBJ_PATH }; + final Object[] values = new Object[] { OBJ_PATH, BOOL_PATH, INT_PATH, + STR_PATH }; + // Go trough all objects + for (int i = 0; i < objsIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + simpleOperationFail(result, objsIn[i], paths[j], values[i]); + } + } + } + + /** + * Test RFC 6902 MOVE operation for non existing location in array. + * {@see RFC 6902: + * 4.4. move} defines:
+ * The "from" location MUST exist for the operation to be successful. + */ + private void testMoveOfNonExistingLocationInArray(final TestResult result) { + System.out.println(" - for non existing location in JsonArray"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray1(), createIntArray2(), createSimpleBoolArray5(), + createObjectArray2() }; + final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", + STR_PATH + "/0" }; + final Object[] values = new Object[] { "/0", "/1", "/2", "/5", "/1" }; + // Go trough all arrays + for (int i = 0; i < arraysIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + simpleOperationFail(result, arraysIn[i], paths[j], values[i]); + } + } + } + + /** + * Test RFC 6902 MOVE operation for moving existing path into path containing + * source path as a prefix. + * {@see RFC 6902: + * 4.4. move} defines:
+ * This operation is functionally identical to a "remove" operation on the + * "from" location, followed immediately by an "add" operation at the target + * location with the value that was just removed. + * {@see RFC 6901: 7. + * Error Handling} defines:
+ * This specification does not define how errors are handled. An application + * of JSON Pointer SHOULD specify the impact and handling of each type of + * error.
+ * For example, some applications might stop pointer processing upon an error, + * while others may attempt to recover from missing values by inserting + * default ones.
+ * This means, that such an operation may fail on non existing target "path" + * after ADD operation, but also missing pointer error recovery may take care + * of creating missing "path" elements. In both cases MOVE and sequence of + * REMOVE and ADD operations MUST produce the same result. + */ + private void testMoveVsRemoveAddOnSelfContainedPath(final TestResult result) { + System.out.println(" - for moving JsonObject under itself"); + final JsonObject in = createCompoundObject(); + final String targetPath = DEF_OBJ_PATH + DEF_PATH; + final JsonPointer ptr = Json.createPointer(DEF_OBJ_PATH); + final JsonValue value = ptr.getValue(in); + final JsonPatchBuilder moveBuilder = Json.createPatchBuilder() + .move(targetPath, DEF_OBJ_PATH); + final JsonPatchBuilder remAddBuilder = Json.createPatchBuilder() + .remove(DEF_OBJ_PATH).add(targetPath, value); + final JsonPatch movePatch = moveBuilder.build(); + final JsonPatch remAddPatch = remAddBuilder.build(); + // Check REMOVE and ADD sequence first. + JsonObject remAddOut; + try { + + remAddOut = remAddPatch.apply(in); + System.out.println(" REMOVE and ADD passed"); + } catch (JsonException e) { + remAddOut = null; + System.out.println(" REMOVE and ADD failed: " + e.getMessage()); + } + // Check MOVE second + JsonObject moveOut; + try { + moveOut = movePatch.apply(in); + System.out.println(" MOVE passed"); + } catch (JsonException e) { + moveOut = null; + System.out.println(" MOVE failed: " + e.getMessage()); + } + // Results evaluation + if (remAddOut != null) { + // Both output values are not null: Compare them + if (moveOut != null) { + if (!assertEquals(remAddOut, moveOut)) { + result.fail("MOVE vs REMOVE and ADD", + "Returned values are not equal"); + } + // REMOVE and ADD output is not null but MOVE output is null + } else { + result.fail("MOVE vs REMOVE and ADD", + "REMOVE and ADD failed but MOVE dit not"); + } + } else { + // REMOVE and ADD output is null but MOVE output is not null + if (moveOut != null) { + result.fail("MOVE vs REMOVE and ADD", + "MOVE failed but REMOVE and ADD dit not"); + } + // else: Both output values are null: both patch operations failed -> test + // passed + } + } + + /** + * Tested operation name {@code "MOVE"}. + * + * @return Operation name to be used in logs. + */ + @Override + protected String operationName() { + return OPERATION; + } + + /** + * Create and initialize patch builder to contain MOVE operation to be + * applied. + * + * @param path + * Source JSON path of MOVE operation. + * @param value + * Target JSON path of MOVE operation. Must be instance of + * {@link String}. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder createOperationBuilder(final String path, + final Object value) { + if (value instanceof String) { + // System.out.println(" MOVE "+path+" -> "+(String)value); + return Json.createPatchBuilder().move((String) value, path); + } else { + throw new IllegalArgumentException( + "Argument \"value\" is not an instance of String"); + } + } + + /** + * Update patch builder to contain next MOVE operation to be applied. + * + * @param builder + * JSON patch builder to update. + * @param path + * Source JSON path of MOVE operation. + * @param value + * Target JSON path of MOVE operation. Must be instance of + * {@link String}. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder updateOperationBuilder( + final JsonPatchBuilder builder, final String path, final Object value) { + if (value instanceof String) { + // System.out.println(" MOVE "+path+" -> "+(String)value); + return builder.move((String) value, path); + } else { + throw new IllegalArgumentException( + "Argument \"value\" is not an instance of String"); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationRemove.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationRemove.java new file mode 100644 index 00000000..a19b362d --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationRemove.java @@ -0,0 +1,491 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonPatchBuilder; + +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/* + * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
+ * {@see RFC 6902}. + *

+ * Implements {@see RFC 6902: 4.2. remove} + * tests. + */ +public class PatchOperationRemove extends CommonOperation { + + /** Tested operation name. */ + private final String OPERATION = "REMOVE"; + + /** + * Creates an instance of RFC 6902 remove operation test. + */ + PatchOperationRemove() { + super(); + } + + /** + * Test RFC 6902 remove operation. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult("RFC 6902 remove operation"); + System.out.println("Testing RFC 6902 remove operation:"); + testRemoveStringOnEmptyObject(result); + testRemoveStringOnEmptyArray(result); + testRemoveStringOnSimpleObject(result); + testRemoveStringOnSimpleArray(result); + testRemoveStringOnSimpleArray2(result); + testRemoveIntOnEmptyObject(result); + testRemoveIntOnEmptyArray(result); + testRemoveIntOnSimpleObject(result); + testRemoveIntOnSimpleArray(result); + testRemoveIntOnSimpleArray2(result); + testRemoveBoolOnEmptyObject(result); + testRemoveBoolOnEmptyArray(result); + testRemoveBoolOnSimpleObject(result); + testRemoveBoolOnSimpleArray(result); + testRemoveBoolOnSimpleArray2(result); + testRemoveObjectOnEmptyObject(result); + testRemoveObjectOnEmptyArray(result); + testRemoveObjectOnSimpleObject(result); + testRemoveObjectOnSimpleArray(result); + testRemoveObjectOnSimpleArray2(result); + testRemoveFromNonExistingLocationInObject(result); + testRemoveFromNonExistingLocationInArray(result); + return result; + } + + /** + * Test pointer remove operation for {@code String} to produce empty JSON + * object. + * + * @param result + * Tests result record. + */ + private void testRemoveStringOnEmptyObject(final TestResult result) { + System.out.println(" - for String to produce empty JSON object"); + final JsonObject in = createSimpleObjectStr(); + final JsonObject check = createEmptyObject(); + simpleOperation(result, in, check, STR_PATH, null); + } + + /** + * Test pointer remove operation for {@code String} to produce empty JSON + * array. Only allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testRemoveStringOnEmptyArray(final TestResult result) { + System.out.println(" - for String to produce empty JSON array"); + final JsonArray in = createEmptyArrayWithStr(); + final JsonArray check = createEmptyArray(); + simpleOperation(result, in, check, "/0", null); + } + + /** + * Test pointer remove operation for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveStringOnSimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObjectWithStr(); + final JsonObject check = createSimpleObject(); + simpleOperation(result, in, check, STR_PATH, null); + } + + /** + * Test pointer remove operation for {@code String} on simple JSON array of + * size 2. Using index {@code 0} to remove {@code String} before another + * existing element and index {@code 1} to remove {@code String} after another + * existing element. + * + * @param result + * Tests result record. + */ + private void testRemoveStringOnSimpleArray(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 2"); + final JsonArray inBefore = createSimpleStringArrayWithStrBefore(); + final JsonArray inAfter = createSimpleStringArrayWithStrAfter(); + final JsonArray check = createStringArray1(); + simpleOperation(result, inBefore, check, "/0", null); + simpleOperation(result, inAfter, check, "/1", null); + } + + /** + * Test pointer REMOVE for {@code String} on simple JSON array of size 5. + * Starting with an array of size 2. + *

    + *
  • Removing {@code String} at the end, at the middle and at the beginning + * of this array. + *
  • Removing {@code String} at the beginning, in the middle and at the end + * of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testRemoveStringOnSimpleArray2(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 5"); + final JsonArray in = createSimpleStringArray5(); + final JsonArray check = createStringArray2(); + complexOperation(result, in, check, new String[] { "/4", "/2", "/0" }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/2" }); + } + + /** + * Test pointer REMOVE operation for {@code int} to produce empty JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveIntOnEmptyObject(final TestResult result) { + System.out.println(" - for int to produce empty JSON object"); + final JsonObject in = createSimpleObjectInt(); + final JsonObject check = createEmptyObject(); + simpleOperation(result, in, check, INT_PATH, null); + } + + /** + * Test pointer REMOVE operation for {@code int} to produce empty JSON array. + * Only allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testRemoveIntOnEmptyArray(final TestResult result) { + System.out.println(" - for int to produce empty JSON array"); + final JsonArray in = createEmptyArrayWithInt(); + final JsonArray check = createEmptyArray(); + simpleOperation(result, in, check, "/0", null); + } + + /** + * Test pointer REMOVE operation for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveIntOnSimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObjectWithInt(); + final JsonObject check = createSimpleObject(); + simpleOperation(result, in, check, INT_PATH, null); + } + + /** + * Test pointer REMOVE operation for {@code int} on simple JSON array of size + * 2. Using index {@code 0} to remove {@code int} before another existing + * element and index {@code 1} to remove {@code int} after another existing + * element. + * + * @param result + * Tests result record. + */ + private void testRemoveIntOnSimpleArray(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 2"); + final JsonArray inBefore = createSimpleIntArrayWithIntBefore(); + final JsonArray inAfter = createSimpleIntArrayWithIntAfter(); + final JsonArray check = createIntArray1(); + simpleOperation(result, inBefore, check, "/0", null); + simpleOperation(result, inAfter, check, "/1", null); + } + + /** + * Test pointer REMOVE for {@code int} on simple JSON array of size 5. + * Starting with an array of size 5. + *
    + *
  • Removing {@code int} at the end, at the middle and at the beginning of + * this array. + *
  • Removing {@code int} at the beginning, in the middle and at the end of + * this array. + *
+ * + * @param result + * Tests result record. + */ + private void testRemoveIntOnSimpleArray2(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 5"); + final JsonArray in = createSimpleIntArray5(); + final JsonArray check = createIntArray2(); + complexOperation(result, in, check, new String[] { "/4", "/2", "/0" }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/2" }); + } + + /** + * Test pointer REMOVE operation for {@code boolean} to produce empty JSON + * object. + * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnEmptyObject(final TestResult result) { + System.out.println(" - for boolean to produce empty JSON object"); + final JsonObject in = createSimpleObjectBool(); + final JsonObject check = createEmptyObject(); + simpleOperation(result, in, check, BOOL_PATH, null); + } + + /** + * Test pointer REMOVE operation for {@code boolean} to produce empty JSON + * array. Only allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnEmptyArray(final TestResult result) { + System.out.println(" - for boolean to produce empty JSON array"); + final JsonArray in = createEmptyArrayWithBool(); + final JsonArray check = createEmptyArray(); + simpleOperation(result, in, check, "/0", null); + } + + /** + * Test pointer REMOVE operation for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnSimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObjectWithBool(); + final JsonObject check = createSimpleObject(); + simpleOperation(result, in, check, BOOL_PATH, null); + } + + /** + * Test pointer REMOVE operation for {@code boolean} on simple JSON array of + * size 2. Using index {@code 0} to remove {@code boolean} before another + * existing element and index {@code 1} to remove {@code boolean} after + * another existing element. + * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnSimpleArray(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 2"); + final JsonArray inBefore = createSimpleBoolArrayWithBoolBefore(); + final JsonArray inAfter = createSimpleBoolArrayWithBoolAfter(); + final JsonArray check = createBoolArray1(); + simpleOperation(result, inBefore, check, "/0", null); + simpleOperation(result, inAfter, check, "/1", null); + } + + /** + * Test pointer REMOVE for {@code boolean} on simple JSON array of size 5. + * Starting with an array of size 5. + *
    + *
  • Removing {@code boolean} at the end, at the middle and at the beginning + * of this array. + *
  • Removing {@code boolean} at the beginning, in the middle and at the end + * of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnSimpleArray2(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 5"); + final JsonArray in = createSimpleBoolArray5(); + final JsonArray check = createBoolArray2(); + complexOperation(result, in, check, new String[] { "/4", "/2", "/0" }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/2" }); + } + + /** + * Test pointer REMOVE operation for {@code JsonObject} to produce empty JSON + * object. + * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnEmptyObject(final TestResult result) { + System.out.println(" - for JsonObject to produce empty JSON object"); + final JsonObject in = createSimpleObjectObject(); + final JsonObject check = createEmptyObject(); + simpleOperation(result, in, check, OBJ_PATH, null); + } + + /** + * Test pointer REMOVE operation for {@code JsonObject} to produce empty JSON + * array. Only allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnEmptyArray(final TestResult result) { + System.out.println(" - for JsonObject to produce empty JSON array"); + final JsonArray in = createEmptyArrayWithObject(); + final JsonArray check = createEmptyArray(); + simpleOperation(result, in, check, "/0", null); + } + + /** + * Test pointer REMOVE operation for {@code JsonObject} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnSimpleObject(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON object"); + final JsonObject in = createCompoundObjectWithObject(); + final JsonObject check = createCompoundObject(); + simpleOperation(result, in, check, OBJ_PATH, null); + } + + /** + * Test pointer REMOVE operation for {@code JsonObject} on simple JSON array + * of size 2. Using index {@code 0} to remove {@code JsonObject} before + * another existing element and index {@code 1} to remove {@code JsonObject} + * after another existing element. + * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnSimpleArray(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 2"); + final JsonArray inBefore = createSimpleObjectArrayWithObjectBefore(); + final JsonArray inAfter = createSimpleObjectArrayWithObjectAfter(); + final JsonArray check = createObjectArray1(); + simpleOperation(result, inBefore, check, "/0", null); + simpleOperation(result, inAfter, check, "/1", null); + } + + /** + * Test pointer REMOVE for {@code JsonObject} on simple JSON array of size 5. + * Starting with an array of size 5. + *
    + *
  • Removing {@code JsonObject} at the end, at the middle and at the + * beginning of this array. + *
  • Removing {@code JsonObject} at the beginning, in the middle and at the + * end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnSimpleArray2(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 5"); + final JsonArray in = createSimpleObjectArray5(); + final JsonArray check = createObjectArray2(); + complexOperation(result, in, check, new String[] { "/4", "/2", "/0" }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/2" }); + } + + // Tests based on RFC 6902 definitions and examples. + + /** + * Test pointer REMOVE for non existing location in object. + * {@see RFC 6902: + * 4.2. remove} defines:
+ * The target location MUST exist for the operation to be successful. + */ + private void testRemoveFromNonExistingLocationInObject( + final TestResult result) { + System.out.println(" - for non existing location in JsonObject"); + final JsonObject[] objsIn = new JsonObject[] { createEmptyObject(), + createSimpleObject(), createCompoundObject() }; + final String[] paths = new String[] { STR_PATH, INT_PATH, BOOL_PATH, + OBJ_PATH }; + // Go trough all objects + for (int i = 0; i < objsIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + simpleOperationFail(result, objsIn[i], paths[j], null); + } + } + } + + /** + * Test pointer REMOVE for non existing location in array. + * {@see RFC 6902: + * 4.2. remove} defines:
+ * The target location MUST exist for the operation to be successful. + */ + private void testRemoveFromNonExistingLocationInArray( + final TestResult result) { + System.out.println(" - for non existing location in JsonArray"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray1(), createIntArray2(), createSimpleBoolArray5(), + createObjectArray2() + + }; + final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", + STR_PATH + "/0" }; + // Go trough all arrays + for (int i = 0; i < arraysIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + simpleOperationFail(result, arraysIn[i], paths[j], null); + } + } + } + + /** + * Tested operation name {@code "REMOVE"}. + * + * @return Operation name to be used in logs. + */ + @Override + protected String operationName() { + return OPERATION; + } + + /** + * Create and initialize patch builder to contain REMOVE operation to be + * applied. + * + * @param path + * JSON path of value to removed. + * @param value + * Not used for REMOVE operation. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder createOperationBuilder(final String path, + final Object value) { + return Json.createPatchBuilder().remove(path); + } + + /** + * Update patch builder to contain next REMOVE operation to be applied. + * + * @param builder + * JSON patch builder to update. + * @param path + * JSON path of value to removed. + * @param value + * Not used for REMOVE operation. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder updateOperationBuilder( + final JsonPatchBuilder builder, final String path, final Object value) { + return builder.remove(path); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationReplace.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationReplace.java new file mode 100644 index 00000000..66190c56 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationReplace.java @@ -0,0 +1,396 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.JsonValueType; +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonPatchBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
+ * {@see RFC 6902}. + *

+ * Implements + * {@see RFC 6902: + * 4.3. replace} tests. + */ +public class PatchOperationReplace extends CommonOperation { + + /** Tested operation name. */ + private final String OPERATION = "REPLACE"; + + /** + * Creates an instance of RFC 6902 replace operation test. + */ + PatchOperationReplace() { + super(); + } + + /** + * Test RFC 6902 replace operation. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult("RFC 6902 replace operation"); + System.out.println("Testing RFC 6902 replace operation:"); + testReplaceStringOnSimpleObject(result); + testReplaceStringOnSimpleArray(result); + testReplaceStringOnSimpleArray2(result); + testReplaceIntOnSimpleObject(result); + testReplaceIntOnSimpleArray(result); + testReplaceIntOnSimpleArray2(result); + testReplaceBoolOnSimpleObject(result); + testReplaceBoolOnSimpleArray(result); + testReplaceBoolOnSimpleArray2(result); + testReplaceObjectOnCompoundObject(result); + testReplaceObjectOnSimpleArray(result); + testReplaceObjectOnSimpleArray2(result); + testReplaceOfNonExistingLocationInObject(result); + testReplaceOfNonExistingLocationInArray(result); + return result; + } + + /** + * Test pointer replace operation for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testReplaceStringOnSimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObjectStr(); + final JsonObject check = createSimpleObjectReplaceStr(); + simpleOperation(result, in, check, STR_PATH, STR_VALUE2); + } + + /** + * Test pointer replace operation for {@code String} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testReplaceStringOnSimpleArray(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 1"); + final JsonArray in = createStringArray1(); + final JsonArray check = createSimpleStringArrayReplaceStr(); + simpleOperation(result, in, check, "/0", STR_VALUE); + } + + /** + * Test pointer replace operation for {@code String} on simple JSON array of + * size 5. Starting with an array of size 5. + *

    + *
  • Replacing {@code String} items from the end to the beginning of this + * array. + *
  • Replacing {@code String} from the beginning to the end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testReplaceStringOnSimpleArray2(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 5"); + final JsonArray in = createSimpleStringArray5(); + final JsonArray check = createSimpleStringArray5R(); + complexOperation(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, + new String[] { STR_VALUE_1, STR_VALUE_2, STR_VALUE_4, STR_VALUE_5 }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, + new String[] { STR_VALUE_5, STR_VALUE_4, STR_VALUE_2, STR_VALUE_1 }); + } + + /** + * Test pointer replace operation for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testReplaceIntOnSimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObjectInt(); + final JsonObject check = createSimpleObjectReplaceInt(); + simpleOperation(result, in, check, INT_PATH, INT_VALUE2); + } + + /** + * Test pointer replace operation for {@code int} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testReplaceIntOnSimpleArray(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 1"); + final JsonArray in = createIntArray1(); + final JsonArray check = createSimpleIntArrayReplaceInt(); + simpleOperation(result, in, check, "/0", INT_VALUE); + } + + /** + * Test pointer replace operation for {@code int} on simple JSON array of size + * 5. Starting with an array of size 5. + *
    + *
  • Replacing {@code int} items from the end to the beginning of this + * array. + *
  • Replacing {@code int} from the beginning to the end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testReplaceIntOnSimpleArray2(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 5"); + final JsonArray in = createSimpleIntArray5(); + final JsonArray check = createSimpleIntArray5R(); + complexOperation(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, + new Integer[] { INT_VALUE_1, INT_VALUE_2, INT_VALUE_4, INT_VALUE_5 }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, + new Integer[] { INT_VALUE_5, INT_VALUE_4, INT_VALUE_2, INT_VALUE_1 }); + } + + /** + * Test pointer replace operation for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testReplaceBoolOnSimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObjectBool(); + final JsonObject check = createSimpleObjectReplaceBool(); + simpleOperation(result, in, check, BOOL_PATH, BOOL_VALUE2); + } + + /** + * Test pointer replace operation for {@code boolean} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testReplaceBoolOnSimpleArray(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 1"); + final JsonArray in = createBoolArray1(); + final JsonArray check = createSimpleBoolArrayReplaceBool(); + simpleOperation(result, in, check, "/0", BOOL_FALSE); + } + + /** + * Test pointer replace operation for {@code boolean} on simple JSON array of + * size 5. Starting with an array of size 5. + *
    + *
  • Replacing {@code boolean} items from the end to the beginning of this + * array. + *
  • Replacing {@code boolean} from the beginning to the end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testReplaceBoolOnSimpleArray2(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 5"); + final JsonArray in = createSimpleBoolArray5(); + final JsonArray check = createSimpleBoolArray5R(); + complexOperation(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, + new Boolean[] { BOOL_FALSE, BOOL_TRUE, BOOL_FALSE, BOOL_TRUE }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, + new Boolean[] { BOOL_TRUE, BOOL_FALSE, BOOL_TRUE, BOOL_FALSE }); + } + + /** + * Test pointer replace operation for {@code JsonObject} on compound JSON + * object. + * + * @param result + * Tests result record. + */ + private void testReplaceObjectOnCompoundObject(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON object"); + final JsonObject in = createCompoundObjectWithObject(); + final JsonObject check = createCompoundObjectReplaceObject(); + simpleOperation(result, in, check, OBJ_PATH, OBJ_VALUE2); + } + + /** + * Test pointer replace operation for {@code JsonObject} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testReplaceObjectOnSimpleArray(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 1"); + final JsonArray in = createObjectArray1(); + final JsonArray check = createSimpleObjectArrayReplaceObject(); + simpleOperation(result, in, check, "/0", OBJ_VALUE); + } + + /** + * Test pointer replace operation for {@code JsonObject} on simple JSON array + * of size 5. Starting with an array of size 5. + *
    + *
  • Replacing {@code JsonObject} items from the end to the beginning of + * this array. + *
  • Replacing {@code JsonObject} from the beginning to the end of this + * array. + *
+ * + * @param result + * Tests result record. + */ + private void testReplaceObjectOnSimpleArray2(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 5"); + final JsonArray in = createSimpleObjectArray5(); + final JsonArray check = createSimpleObjectArray5R(); + complexOperation(result, in, check, new String[] { "/4", "/3", "/1", "/0" }, + new JsonObject[] { OBJ_VALUE_1, OBJ_VALUE_2, OBJ_VALUE_4, + OBJ_VALUE_5 }); + complexOperation(result, in, check, new String[] { "/0", "/1", "/3", "/4" }, + new JsonObject[] { OBJ_VALUE_5, OBJ_VALUE_4, OBJ_VALUE_2, + OBJ_VALUE_1 }); + } + + // Tests based on RFC 6902 definitions and examples. + + /** + * Test pointer replace for non existing location in object. + * {@see RFC 6902: + * 4.3. replace} defines:
+ * The target location MUST exist for the operation to be successful. + */ + private void testReplaceOfNonExistingLocationInObject( + final TestResult result) { + System.out.println(" - for non existing location in JsonObject"); + final JsonObject[] objsIn = new JsonObject[] { createEmptyObject(), + createSimpleObject(), createCompoundObject() }; + final String[] paths = new String[] { STR_PATH, INT_PATH, BOOL_PATH, + OBJ_PATH }; + final Object[] values = new Object[] { STR_VALUE, INT_VALUE, BOOL_VALUE, + OBJ_VALUE }; + // Go trough all objects + for (int i = 0; i < objsIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + simpleOperationFail(result, objsIn[i], paths[j], values[i]); + } + } + } + + /** + * Test pointer replace for non existing location in array. + * {@see RFC 6902: + * 4.3. replace} defines:
+ * The target location MUST exist for the operation to be successful. + */ + private void testReplaceOfNonExistingLocationInArray( + final TestResult result) { + System.out.println(" - for non existing location in JsonArray"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray1(), createIntArray2(), createSimpleBoolArray5(), + createObjectArray2() }; + final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", + STR_PATH + "/0" }; + final Object[] values = new Object[] { STR_VALUE, STR_VALUE, INT_VALUE, + BOOL_VALUE, OBJ_VALUE }; + // Go trough all arrays + for (int i = 0; i < arraysIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + simpleOperationFail(result, arraysIn[i], paths[j], values[i]); + } + } + } + + /** + * Tested operation name {@code "MOVE"}. + * + * @return Operation name to be used in logs. + */ + @Override + protected String operationName() { + return OPERATION; + } + + /** + * Create and initialize patch builder to contain REPLACE operation to be + * applied. + * + * @param path + * JSON path of value to be replaced. + * @param value + * Value to replace previous one. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder createOperationBuilder(final String path, + final Object value) { + return builderReplace(Json.createPatchBuilder(), path, value); + } + + /** + * Update patch builder to contain next REPLACE operation to be applied. + * + * @param builder + * JSON patch builder to update. + * @param path + * JSON path of value to be replaced. + * @param value + * Value to replace previous one. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder updateOperationBuilder( + final JsonPatchBuilder builder, final String path, final Object value) { + return builderReplace(builder, path, value); + } + + /** + * Add REPLACE {@code value} at {@code path} operation to provided JSON patch + * builder. + * + * @param builder + * Target JSON patch builder. + * @param path + * JSON path of value to be replaced. + * @param value + * Value to be replaced at given JSON path. + * @return JSON patch builder containing new {@code value} at {@code path} + * replaced. + */ + @SuppressWarnings("UnnecessaryUnboxing") + private static JsonPatchBuilder builderReplace(final JsonPatchBuilder builder, + final String path, final Object value) { + switch (JsonValueType.getType(value.getClass())) { + case String: + return builder.replace(path, (String) value); + case Integer: + return builder.replace(path, ((Integer) value).intValue()); + case Boolean: + return builder.replace(path, ((Boolean) value).booleanValue()); + case JsonValue: + return builder.replace(path, (JsonValue) value); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationTest.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationTest.java new file mode 100644 index 00000000..14ac33b6 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchOperationTest.java @@ -0,0 +1,413 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.JsonValueType; +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonObject; +import jakarta.json.JsonPatchBuilder; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
+ * {@see RFC 6902}. + *

+ * Implements + * {@see RFC 6902: + * 4.6. test} tests. + */ +public class PatchOperationTest extends CommonOperation { + + /** Tested operation name. */ + private final String OPERATION = "TEST"; + + /** + * Creates an instance of RFC 6902 replace operation test. + */ + PatchOperationTest() { + super(); + } + + /** + * Test RFC 6902 MOVE operation. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult("RFC 6902 test operation"); + System.out.println("Testing RFC 6902 test operation:"); + testOnEmptyObject(result); + testOnEmptyArray(result); + testOnSimpleObject(result); + testOnSimpleStringArray(result); + testOnSimpleIntArray(result); + testOnSimpleBoolArray(result); + testOnSimpleObjectArray(result); + return result; + } + + /** + * Test RFC 6902 TEST operation on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testOnEmptyObject(final TestResult result) { + System.out.println(" - on empty JSON object"); + final JsonObject in = createEmptyObject(); + final String[] paths = new String[] { STR_PATH, INT_PATH, BOOL_PATH, + OBJ_PATH }; + final Object[] values = new Object[] { STR_VALUE, INT_VALUE, BOOL_VALUE, + OBJ_VALUE }; + // Go trough all values. + for (int i = 0; i < values.length; i++) { + // Go trough all paths. + for (int j = 0; j < paths.length; j++) { + // Everything shall fail on empty object. + simpleOperationFail(result, in, paths[j], values[i]); + } + } + // Whole document should pass on itself. + simpleOperation(result, in, null, "", in); + } + + /** + * Test RFC 6902 TEST operation on empty JSON array. + * + * @param result + * Tests result record. + */ + private void testOnEmptyArray(final TestResult result) { + System.out.println(" - on empty JSON array"); + final JsonArray in = createEmptyArray(); + final String[] paths = new String[] { "/-1", "/0", "/1", "/2", "/3", "/4", + "/5", "/-" }; + final Object[] values = new Object[] { STR_VALUE, INT_VALUE, BOOL_VALUE, + OBJ_VALUE }; + // Go trough all values. + for (int i = 0; i < values.length; i++) { + // Go trough all paths. + for (int j = 0; j < paths.length; j++) { + // Everything shall fail on empty object. + simpleOperationFail(result, in, paths[j], values[i]); + } + } + // Whole document should pass on itself. + simpleOperation(result, in, null, "", in); + } + + /** + * Test RFC 6902 TEST on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testOnSimpleObject(final TestResult result) { + System.out.println(" - on simple JSON object"); + final JsonObject[] in = new JsonObject[] { createSimpleObjectStr(), + createSimpleObjectInt(), createSimpleObjectBool(), + createSimpleObjectObject() }; + final String[] paths = new String[] { STR_PATH, INT_PATH, BOOL_PATH, + OBJ_PATH }; + final Object[] values = new Object[] { STR_VALUE, INT_VALUE, BOOL_VALUE, + OBJ_VALUE }; + // go trough all source objects. + for (int o = 0; o < in.length; o++) { + // Go trough all values. + for (int i = 0; i < values.length; i++) { + // Go trough all paths. + for (int j = 0; j < paths.length; j++) { + if (o == i && o == j) { + // TEST must pass for matching JsonObject, path and value + simpleOperation(result, in[o], null, paths[j], values[i]); + } else { + // TEST must fail for non matching JsonObject, path and value + simpleOperationFail(result, in[o], paths[j], values[i]); + } + } + } + // Whole document should pass on itself. + simpleOperation(result, in[o], null, "", in[o]); + } + } + + /** + * Test RFC 6902 TEST on simple JSON array of {@code String}. + * + * @param result + * Tests result record. + */ + private void testOnSimpleStringArray(final TestResult result) { + System.out.println(" - on simple JSON String array of size 5"); + final JsonArray in = createSimpleStringArray5(); + final String[] indexes = new String[] { "/-1", "/-", STR_PATH }; + final String[] values = new String[] { STR_VALUE_1, STR_VALUE_2, + STR_VALUE_3, STR_VALUE_4, STR_VALUE_5 }; + // Go trough all array indexes. + for (int i = 0; i <= 5; i++) { + final String path = arrayPtr("/", i); + // Go trough all values. + for (int v = 0; v < values.length; v++) { + if (i == v) { + // TEST must pass for matching index and value. + simpleOperation(result, in, null, path, values[v]); + } else { + // TEST must fail for non matching index and value. + simpleOperationFail(result, in, path, values[v]); + } + } + } + // Go trough all invalid indexes + for (int i = 0; i < indexes.length; i++) { + // Go trough all values. + for (int v = 0; v < values.length; v++) { + // TEST must fail for non matching index and value. + simpleOperationFail(result, in, indexes[i], values[v]); + } + } + // Whole document should pass on itself. + simpleOperation(result, in, null, "", in); + } + + /** + * Test RFC 6902 TEST on simple JSON array of {@code int}. + * + * @param result + * Tests result record. + */ + private void testOnSimpleIntArray(final TestResult result) { + System.out.println(" - on simple JSON int array of size 5"); + final JsonArray in = createSimpleIntArray5(); + final String[] indexes = new String[] { "/-1", "/-", INT_PATH }; + final int[] values = new int[] { INT_VALUE_1, INT_VALUE_2, INT_VALUE_3, + INT_VALUE_4, INT_VALUE_5 }; + // Go trough all array indexes. + for (int i = 0; i <= 5; i++) { + final String path = arrayPtr("/", i); + // Go trough all values. + for (int v = 0; v < values.length; v++) { + if (i == v) { + // TEST must pass for matching index and value. + simpleOperation(result, in, null, path, values[v]); + } else { + // TEST must fail for non matching index and value. + simpleOperationFail(result, in, path, values[v]); + } + } + } + // Go trough all invalid indexes + for (int i = 0; i < indexes.length; i++) { + // Go trough all values. + for (int v = 0; v < values.length; v++) { + // TEST must fail for non matching index and value. + simpleOperationFail(result, in, indexes[i], values[v]); + } + } + // Whole document should pass on itself. + simpleOperation(result, in, null, "", in); + } + + /** + * Test RFC 6902 TEST on simple JSON array of {@code boolean}. + * + * @param result + * Tests result record. + */ + private void testOnSimpleBoolArray(final TestResult result) { + System.out.println(" - on simple JSON boolean array of size 2"); + final JsonArray in = createBoolArray2(); + final String[] indexes = new String[] { "/-1", "/-", BOOL_PATH }; + final boolean[] values = new boolean[] { BOOL_TRUE, BOOL_FALSE }; + // Go trough all array indexes. + for (int i = 0; i <= 2; i++) { + final String path = arrayPtr("/", i); + // Go trough all values. + for (int v = 0; v < values.length; v++) { + if (i == v) { + // TEST must pass for matching index and value. + simpleOperation(result, in, null, path, values[v]); + } else { + // TEST must fail for non matching index and value. + simpleOperationFail(result, in, path, values[v]); + } + } + } + // Go trough all invalid indexes + for (int i = 0; i < indexes.length; i++) { + // Go trough all values. + for (int v = 0; v < values.length; v++) { + // TEST must fail for non matching index and value. + simpleOperationFail(result, in, indexes[i], values[v]); + } + } + // Whole document should pass on itself. + simpleOperation(result, in, null, "", in); + } + + /** + * Test RFC 6902 TEST on simple JSON array of {@code JsonObject}. + * + * @param result + * Tests result record. + */ + private void testOnSimpleObjectArray(final TestResult result) { + System.out.println(" - on simple JSON JsonObject array of size 5"); + final JsonArray in = createSimpleObjectArray5(); + final String[] indexes = new String[] { "/-1", "/-", OBJ_PATH }; + final JsonObject[] values = new JsonObject[] { OBJ_VALUE_1, OBJ_VALUE_2, + OBJ_VALUE_3, OBJ_VALUE_4, OBJ_VALUE_5 }; + // Go trough all array indexes. + for (int i = 0; i <= 5; i++) { + final String path = arrayPtr("/", i); + // Go trough all values. + for (int v = 0; v < values.length; v++) { + if (i == v) { + // TEST must pass for matching index and value. + simpleOperation(result, in, null, path, values[v]); + } else { + // TEST must fail for non matching index and value. + simpleOperationFail(result, in, path, values[v]); + } + } + } + // Go trough all invalid indexes + for (int i = 0; i < indexes.length; i++) { + // Go trough all values. + for (int v = 0; v < values.length; v++) { + // TEST must fail for non matching index and value. + simpleOperationFail(result, in, indexes[i], values[v]); + } + } + // Whole document should pass on itself. + simpleOperation(result, in, null, "", in); + } + + /** + * Build JSON array pointer for given prefix and index. + * + * @param prefix + * JSON array pointer prefix. + * @param index + * JSON array pointer index. + * @return JSON array pointer. + */ + private static String arrayPtr(final String prefix, final int index) { + final int prefixLen = prefix != null ? prefix.length() : 0; + final String indexStr = Integer.toString(index); + final StringBuilder sb = new StringBuilder(prefixLen + indexStr.length()); + if (prefixLen > 0) { + sb.append(prefix); + } + sb.append(indexStr); + return sb.toString(); + } + + /** + * Tested operation name {@code "TEST"}. + * + * @return Operation name to be used in logs. + */ + @Override + protected String operationName() { + return OPERATION; + } + + /** + * Create and initialize patch builder to contain TEST operation to be + * applied. + * + * @param path + * JSON path of value to be tested. + * @param value + * Value to be compared against value on specified path. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder createOperationBuilder(final String path, + final Object value) { + return builderTest(Json.createPatchBuilder(), path, value); + } + + /** + * Update patch builder to contain next TEST operation to be applied. + * + * @param builder + * JSON patch builder to update. + * @param path + * JSON path of value to be tested. + * @param value + * Value to be compared against value on specified path. + * @return Patch builder containing operation to be applied. + */ + @Override + protected JsonPatchBuilder updateOperationBuilder( + final JsonPatchBuilder builder, final String path, final Object value) { + return builderTest(builder, path, value); + } + + /** + * Add TEST {@code value} at {@code path} operation to provided JSON patch + * builder. + * + * @param builder + * Target JSON patch builder. + * @param path + * JSON path of value to be tested. + * @param value + * Value to be compared against value on specified path. + * @return JSON patch builder containing new TEST operation. + */ + @SuppressWarnings("UnnecessaryUnboxing") + private static JsonPatchBuilder builderTest(final JsonPatchBuilder builder, + final String path, final Object value) { + switch (JsonValueType.getType(value.getClass())) { + case String: + return builder.test(path, (String) value); + case Integer: + return builder.test(path, ((Integer) value).intValue()); + case Boolean: + return builder.test(path, ((Boolean) value).booleanValue()); + case JsonValue: + return builder.test(path, (JsonValue) value); + default: + throw new IllegalArgumentException( + "Value does not match known JSON value type"); + } + } + + /** + * Operation result check. + * + * @param check + * Expected modified JSON value. + * @param out + * Operation output. + * @return Value of {@code true} if operation passed or {@code false} + * otherwise. + */ + @Override + protected boolean operationFailed(final JsonValue check, + final JsonValue out) { + return out == null; + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchTests.java new file mode 100644 index 00000000..1c66c453 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/patchtests/PatchTests.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.patchtests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.lib.harness.Fault; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +// $Id$ +/* + * RFC 6902: JavaScript Object Notation (JSON) Patch compatibility tests.
+ * {@see RFC 6902}. + */ +@RunWith(Arquillian.class) +public class PatchTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, PatchTests.class.getPackage().getName()); + } + /** + * Test {@link JsonPatch} factory methods added in JSON-P 1.1. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonCreatePatch11Test + * + * @assertion_ids: JSONP:JAVADOC:574; JSONP:JAVADOC:579; JSONP:JAVADOC:581; + * JSONP:JAVADOC:653; JSONP:JAVADOC:658; JSONP:JAVADOC:660; + * JSONP:JAVADOC:620; JSONP:JAVADOC:621; + * + * @test_Strategy: Tests JsonPatch API factory methods added in JSON-P 1.1. + */ + @Test + public void jsonCreatePatch11Test() throws Fault { + PatchCreate createTest = new PatchCreate(); + final TestResult result = createTest.test(); + result.eval(); + } + + /** + * Test {@code JsonPatch.Operation} enumeration added in JSON-P 1.1. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonJsonPatchOperation11Test + * + * @assertion_ids: JSONP:JAVADOC:622; JSONP:JAVADOC:623; JSONP:JAVADOC:624; + * JSONP:JAVADOC:625; + * + * @test_Strategy: Tests JsonPatch.Operation enumeration added in JSON-P 1.1. + */ + @Test + public void jsonJsonPatchOperation11Test() throws Fault { + PatchOperationEnum enumTest = new PatchOperationEnum(); + final TestResult result = enumTest.test(); + result.eval(); + } + + /** + * Test JSONP API response on add operation.
+ * {@see RFC 6902: + * 4.1. add}. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonPatchAddTest + * @assertion_ids: JSONP:JAVADOC:626; JSONP:JAVADOC:627; JSONP:JAVADOC:628; + * JSONP:JAVADOC:629; JSONP:JAVADOC:580; JSONP:JAVADOC:659; + * JSONP:JAVADOC:620; JSONP:JAVADOC:630; + * @test_Strategy: Test API response on various usages of add operation. + */ + @Test + public void jsonPatchAddTest() throws Fault { + PatchOperationAdd addTest = new PatchOperationAdd(); + final TestResult result = addTest.test(); + result.eval(); + } + + /** + * Test JSONP API response on remove operation.
+ * {@see RFC 6902: + * 4.2. remove}. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonPatchRemoveTest + * @assertion_ids: JSONP:JAVADOC:633; JSONP:JAVADOC:580; JSONP:JAVADOC:659; + * JSONP:JAVADOC:620; JSONP:JAVADOC:630; + * @test_Strategy: Test API response on various usages of remove operation. + */ + @Test + public void jsonPatchRemoveTest() throws Fault { + PatchOperationRemove removeTest = new PatchOperationRemove(); + final TestResult result = removeTest.test(); + result.eval(); + } + + /** + * Test JSONP API response on replace operation.
+ * {@see RFC 6902: + * 4.3. replace}. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonPatchReplaceTest + * @assertion_ids: JSONP:JAVADOC:634; JSONP:JAVADOC:635; JSONP:JAVADOC:636; + * JSONP:JAVADOC:637; JSONP:JAVADOC:580; JSONP:JAVADOC:659; + * JSONP:JAVADOC:620; JSONP:JAVADOC:630; + * @test_Strategy: Test API response on various usages of replace operation. + */ + @Test + public void jsonPatchReplaceTest() throws Fault { + PatchOperationReplace replaceTest = new PatchOperationReplace(); + final TestResult result = replaceTest.test(); + result.eval(); + } + + /** + * Test JSONP API response on move operation.
+ * {@see RFC 6902: + * 4.4. move}. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonPatchMoveTest + * @assertion_ids: JSONP:JAVADOC:632; JSONP:JAVADOC:580; JSONP:JAVADOC:659; + * JSONP:JAVADOC:620; JSONP:JAVADOC:630; + * @test_Strategy: Test API response on various usages of move operation. + */ + @Test + public void jsonPatchMoveTest() throws Fault { + PatchOperationMove moveTest = new PatchOperationMove(); + final TestResult result = moveTest.test(); + result.eval(); + } + + /** + * Test JSONP API response on copy operation.
+ * {@see RFC 6902: + * 4.5. copy}. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonPatchCopyTest + * @assertion_ids: JSONP:JAVADOC:631; JSONP:JAVADOC:580; JSONP:JAVADOC:659; + * JSONP:JAVADOC:620; JSONP:JAVADOC:630; + * @test_Strategy: Test API response on various usages of copy operation. + */ + @Test + public void jsonPatchCopyTest() throws Fault { + PatchOperationCopy copyTest = new PatchOperationCopy(); + final TestResult result = copyTest.test(); + result.eval(); + } + + /** + * Test JSONP API response on test operation.
+ * {@see RFC 6902: + * 4.6. test}. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonPatchTestTest + * @assertion_ids: JSONP:JAVADOC:638; JSONP:JAVADOC:639; JSONP:JAVADOC:640; + * JSONP:JAVADOC:641; JSONP:JAVADOC:580; JSONP:JAVADOC:659; + * JSONP:JAVADOC:620; JSONP:JAVADOC:630; + * @test_Strategy: Test API response on various usages of test operation. + */ + @Test + public void jsonPatchTestTest() throws Fault { + PatchOperationTest testTest = new PatchOperationTest(); + final TestResult result = testTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerAdd.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerAdd.java new file mode 100644 index 00000000..7b0d9d49 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerAdd.java @@ -0,0 +1,695 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.pointertests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonException; +import jakarta.json.JsonObject; +import jakarta.json.JsonPointer; +import jakarta.json.JsonStructure; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * {@see RFC 6901}: pointer + * usage for {@see RFC 6902} + * add operation tests.
+ */ +public class PointerAdd { + + /** + * Creates an instance of RFC 6901 pointer instance usage for RFC 6902 add + * operation tests. + */ + PointerAdd() { + super(); + } + + /** + * Test RFC 6901 pointer instance usage for RFC 6902 add operation. Suite + * entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "RFC 6901 pointer usage for RFC 6902 add operation"); + System.out.println("Testing RFC 6901 pointer usage for RFC 6902 add operation"); + testAddStringOnEmptyObject(result); + testAddStringOnEmptyArray(result); + testAddStringOnSimpleObject(result); + testAddStringOnSimpleArray(result); + testAddStringOnSimpleArray2(result); + testAddIntOnEmptyObject(result); + testAddIntOnEmptyArray(result); + testAddIntOnSimpleObject(result); + testAddIntOnSimpleArray(result); + testAddIntOnSimpleArray2(result); + testAddBoolOnEmptyObject(result); + testAddBoolOnEmptyArray(result); + testAddBoolOnSimpleObject(result); + testAddBoolOnSimpleArray(result); + testAddBoolOnSimpleArray2(result); + testAddObjectOnEmptyObject(result); + testAddObjectOnEmptyArray(result); + testAddObjectOnSimpleObject(result); + testAddObjectOnSimpleArray(result); + testAddObjectOnSimpleArray2(result); + testAddArrayToReplaceObject(result); + testAddArrayToReplaceDocument(result); + testAddStringArrayToStringArray(result); + testAddStringToNonExistingObject(result); + return result; + } + + /** + * Test pointer ADD operation for {@code String} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testAddStringOnEmptyObject(final TestResult result) { + System.out.println(" - for String on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject check = createSimpleObjectStr(); + final JsonPointer ptr = Json.createPointer(STR_PATH); + final JsonObject out = ptr.add(in, Json.createValue(STR_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + STR_PATH + "\" ADD \"" + + STR_VALUE + "\" failed on empty JSON object"); + } + } + + /** + * Test pointer ADD operation for {@code String} on empty JSON array. Only + * allowed index for empty array is {@code 0} and {@code -}. + * + * @param result + * Tests result record. + */ + private void testAddStringOnEmptyArray(final TestResult result) { + System.out.println(" - for String on empty JSON array"); + final JsonArray in = createEmptyArray(); + final JsonArray check = createEmptyArrayWithStr(); + final JsonPointer[] ptrs = new JsonPointer[] { Json.createPointer("/0"), + Json.createPointer("/-") }; + for (final JsonPointer ptr : ptrs) { + final JsonArray out = ptr.add(in, Json.createValue(STR_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + ptr + "\" ADD \"" + + STR_VALUE + "\" failed on empty JSON array"); + } + } + } + + /** + * Test pointer ADD operation for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testAddStringOnSimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject check = createSimpleObjectWithStr(); + final JsonPointer ptr = Json.createPointer(STR_PATH); + final JsonObject out = ptr.add(in, Json.createValue(STR_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + STR_PATH + "\" ADD \"" + + STR_VALUE + "\" failed on simple JSON object"); + } + } + + /** + * Test pointer ADD operation for {@code String} on simple JSON array of size + * 1. Using index {@code 0} to add {@code String} before already existing + * element and indexes {@code 1} and {@code -} to add {@code String} after + * already existing element. + * + * @param result + * Tests result record. + */ + private void testAddStringOnSimpleArray(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 1"); + final JsonArray in = createStringArray1(); + final JsonArray checkBefore = createSimpleStringArrayWithStrBefore(); + final JsonArray checkAfter = createSimpleStringArrayWithStrAfter(); + final JsonPointer ptrBefore = Json.createPointer("/0"); + final JsonPointer[] ptrsAfter = new JsonPointer[] { + Json.createPointer("/1"), Json.createPointer("/-") }; + final JsonArray outBefore = ptrBefore.add(in, Json.createValue(STR_VALUE)); + if (!assertEquals(checkBefore, outBefore)) { + result.fail("Pointer ADD operation", "Pointer \"/0\" ADD \"" + STR_VALUE + + "\" failed on simple JSON array"); + } + for (final JsonPointer ptrAfter : ptrsAfter) { + final JsonArray outAfter = ptrAfter.add(in, Json.createValue(STR_VALUE)); + if (!assertEquals(checkAfter, outAfter)) { + result.fail("Pointer ADD operation", "Pointer \"/1\" ADD \"" + STR_VALUE + + "\" failed on simple JSON array"); + } + } + } + + /** + * Test pointer ADD operation for {@code String} on simple JSON array of size + * 2. Starting with an array of size 2. + *

    + *
  • Adding {@code String} at the end, in the middle and at the beginning of + * this array. + *
  • Adding {@code String} at the beginning, in the middle and at the end of + * this array. + *
+ * + * @param result + * Tests result record. + */ + private void testAddStringOnSimpleArray2(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 2"); + final JsonArray in = createStringArray2(); + final JsonArray check = createSimpleStringArray5(); + verifyAddValues(result, in, check, new String[] { "/2", "/1", "/0" }, + new String[] { STR_VALUE_5, STR_VALUE_3, STR_VALUE_1 }, + "Pointer ADD operation", + "Pointers \"/2\", \"/1\", \"/0\" ADD sequence failed on simple JSON array"); + verifyAddValues(result, in, check, new String[] { "/0", "/2", "/4" }, + new String[] { STR_VALUE_1, STR_VALUE_3, STR_VALUE_5 }, + "Pointer ADD operation", + "Pointers \"/0\", \"/2\", \"/4\" ADD sequence failed on simple JSON array"); + } + + /** + * Test pointer ADD operation for {@code int} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testAddIntOnEmptyObject(final TestResult result) { + System.out.println(" - for int on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject check = createSimpleObjectInt(); + final JsonPointer ptr = Json.createPointer(INT_PATH); + final JsonObject out = ptr.add(in, Json.createValue(INT_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + INT_PATH + "\" ADD \"" + + INT_VALUE + "\" failed on empty JSON object"); + } + } + + /** + * Test pointer ADD operation for {@code int} on empty JSON array. Only + * allowed index for empty array is {@code 0} and {@code -}. + * + * @param result + * Tests result record. + */ + private void testAddIntOnEmptyArray(final TestResult result) { + System.out.println(" - for int on empty JSON array"); + final JsonArray in = createEmptyArray(); + final JsonArray check = createEmptyArrayWithInt(); + final JsonPointer[] ptrs = new JsonPointer[] { Json.createPointer("/0"), + Json.createPointer("/-") }; + for (final JsonPointer ptr : ptrs) { + final JsonArray out = ptr.add(in, Json.createValue(INT_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + ptr + "\" ADD \"" + + INT_VALUE + "\" failed on empty JSON array"); + } + } + } + + /** + * Test pointer ADD operation for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testAddIntOnSimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject check = createSimpleObjectWithInt(); + final JsonPointer ptr = Json.createPointer(INT_PATH); + final JsonObject out = ptr.add(in, Json.createValue(INT_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + INT_PATH + "\" ADD \"" + + INT_VALUE + "\" failed on simple JSON object"); + } + } + + /** + * Test pointer ADD operation for {@code int} on simple JSON array of size 1. + * Using index {@code 0} to add {@code int} before already existing element + * and index {@code 1} and {@code -} to add {@code int} after already existing + * element. + * + * @param result + * Tests result record. + */ + private void testAddIntOnSimpleArray(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 1"); + final JsonArray in = createIntArray1(); + final JsonArray checkBefore = createSimpleIntArrayWithIntBefore(); + final JsonArray checkAfter = createSimpleIntArrayWithIntAfter(); + final JsonPointer ptrBefore = Json.createPointer("/0"); + final JsonPointer[] ptrsAfter = new JsonPointer[] { + Json.createPointer("/1"), Json.createPointer("/-") }; + final JsonArray outBefore = ptrBefore.add(in, Json.createValue(INT_VALUE)); + if (!assertEquals(checkBefore, outBefore)) { + result.fail("Pointer ADD operation", "Pointer \"/0\" ADD \"" + INT_VALUE + + "\" failed on simple JSON array"); + } + for (final JsonPointer ptrAfter : ptrsAfter) { + final JsonArray outAfter = ptrAfter.add(in, Json.createValue(INT_VALUE)); + if (!assertEquals(checkAfter, outAfter)) { + result.fail("Pointer ADD operation", "Pointer \"/1\" ADD \"" + INT_VALUE + + "\" failed on simple JSON array"); + } + } + } + + /** + * Test pointer ADD operation for {@code int} on simple JSON array of size 2. + * Starting with an array of size 2. + *
    + *
  • Adding {@code int} at the end, in the middle and at the beginning of + * this array. + *
  • Adding {@code int} at the beginning, in the middle and at the end of + * this array. + *
+ * + * @param result + * Tests result record. + */ + private void testAddIntOnSimpleArray2(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 2"); + final JsonArray in = createIntArray2(); + final JsonArray check = createSimpleIntArray5(); + verifyAddValues(result, in, check, new String[] { "/2", "/1", "/0" }, + new Integer[] { INT_VALUE_5, INT_VALUE_3, INT_VALUE_1 }, + "Pointer ADD operation", + "Pointers \"/2\", \"/1\", \"/0\" ADD sequence failed on simple JSON array"); + verifyAddValues(result, in, check, new String[] { "/0", "/2", "/4" }, + new Integer[] { INT_VALUE_1, INT_VALUE_3, INT_VALUE_5 }, + "Pointer ADD operation", + "Pointers \"/0\", \"/2\", \"/4\" ADD sequence failed on simple JSON array"); + } + + /** + * Test pointer ADD operation for {@code boolean} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testAddBoolOnEmptyObject(final TestResult result) { + System.out.println(" - for boolean on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject check = createSimpleObjectBool(); + final JsonPointer ptr = Json.createPointer(BOOL_PATH); + final JsonObject out = ptr.add(in, toJsonValue(BOOL_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + BOOL_PATH + + "\" ADD \"" + BOOL_VALUE + "\" failed on empty JSON object"); + } + } + + /** + * Test pointer ADD operation for {@code boolean} on empty JSON array. Only + * allowed index for empty array is {@code 0} and {@code -}. + * + * @param result + * Tests result record. + */ + private void testAddBoolOnEmptyArray(final TestResult result) { + System.out.println(" - for boolean on empty JSON array"); + final JsonArray in = createEmptyArray(); + final JsonArray check = createEmptyArrayWithBool(); + final JsonPointer[] ptrs = new JsonPointer[] { Json.createPointer("/0"), + Json.createPointer("/-") }; + for (final JsonPointer ptr : ptrs) { + final JsonArray out = ptr.add(in, toJsonValue(BOOL_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + ptr + "\" ADD \"" + + BOOL_VALUE + "\" failed on empty JSON array"); + } + } + } + + /** + * Test pointer ADD operation for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testAddBoolOnSimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObject(); + final JsonObject check = createSimpleObjectWithBool(); + final JsonPointer ptr = Json.createPointer(BOOL_PATH); + final JsonObject out = ptr.add(in, toJsonValue(BOOL_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + BOOL_PATH + + "\" ADD \"" + BOOL_VALUE + "\" failed on simple JSON object"); + } + } + + /** + * Test pointer ADD operation for {@code boolean} on simple JSON array of size + * 1. Using index {@code 0} to add {@code boolean} before already existing + * element and index {@code 1} and {@code -} to add {@code boolean} after + * already existing element. + * + * @param result + * Tests result record. + */ + private void testAddBoolOnSimpleArray(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 1"); + final JsonArray in = createBoolArray1(); + final JsonArray checkBefore = createSimpleBoolArrayWithBoolBefore(); + final JsonArray checkAfter = createSimpleBoolArrayWithBoolAfter(); + final JsonPointer ptrBefore = Json.createPointer("/0"); + final JsonPointer[] ptrsAfter = new JsonPointer[] { + Json.createPointer("/1"), Json.createPointer("/-") }; + final JsonArray outBefore = ptrBefore.add(in, toJsonValue(BOOL_FALSE)); + if (!assertEquals(checkBefore, outBefore)) { + result.fail("Pointer ADD operation", "Pointer \"/0\" ADD \"" + BOOL_FALSE + + "\" failed on simple JSON array"); + } + for (final JsonPointer ptrAfter : ptrsAfter) { + final JsonArray outAfter = ptrAfter.add(in, toJsonValue(BOOL_FALSE)); + if (!assertEquals(checkAfter, outAfter)) { + result.fail("Pointer ADD operation", "Pointer \"/1\" ADD \"" + + BOOL_FALSE + "\" failed on simple JSON array"); + } + } + } + + /** + * Test pointer ADD operation for {@code boolean} on simple JSON array of size + * 2. Starting with an array of size 2. + *
    + *
  • Adding {@code boolean} at the end, in the middle and at the beginning + * of this array. + *
  • Adding {@code boolean} at the beginning, in the middle and at the end + * of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testAddBoolOnSimpleArray2(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 2"); + final JsonArray in = createBoolArray2(); + final JsonArray check = createSimpleBoolArray5(); + verifyAddValues(result, in, check, new String[] { "/2", "/1", "/0" }, + new Boolean[] { BOOL_TRUE, BOOL_TRUE, BOOL_FALSE }, + "Pointer ADD operation", + "Pointers \"/2\", \"/1\", \"/0\" ADD sequence failed on simple JSON array"); + verifyAddValues(result, in, check, new String[] { "/0", "/2", "/4" }, + new Boolean[] { BOOL_FALSE, BOOL_TRUE, BOOL_TRUE }, + "Pointer ADD operation", + "Pointers \"/0\", \"/2\", \"/4\" ADD sequence failed on simple JSON array"); + } + + /** + * Test pointer ADD operation for {@code JsonObject} on empty JSON object. + * + * @param result + * Tests result record. + */ + private void testAddObjectOnEmptyObject(final TestResult result) { + System.out.println(" - for JsonObject on empty JSON object"); + final JsonObject in = createEmptyObject(); + final JsonObject check = createSimpleObjectObject(); + final JsonPointer ptr = Json.createPointer(OBJ_PATH); + final JsonObject out = ptr.add(in, OBJ_VALUE); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + OBJ_PATH + "\" ADD \"" + + OBJ_VALUE + "\" failed on empty JSON object"); + } + } + + /** + * Test pointer ADD operation for {@code JsonObject} on empty JSON array. Only + * allowed index for empty array is {@code 0} and {@code -}. + * + * @param result + * Tests result record. + */ + private void testAddObjectOnEmptyArray(final TestResult result) { + System.out.println(" - for JsonObject on empty JSON array"); + final JsonArray in = createEmptyArray(); + final JsonArray check = createEmptyArrayWithObject(); + final JsonPointer[] ptrs = new JsonPointer[] { Json.createPointer("/0"), + Json.createPointer("/-") }; + for (final JsonPointer ptr : ptrs) { + final JsonArray out = ptr.add(in, OBJ_VALUE); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + ptr + "\" ADD \"" + + OBJ_VALUE + "\" failed on empty JSON array"); + } + } + } + + /** + * Test pointer ADD operation for {@code JsonObject} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testAddObjectOnSimpleObject(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON object"); + final JsonObject in = createCompoundObject(); + final JsonObject check = createCompoundObjectWithObject(); + final JsonPointer ptr = Json.createPointer(OBJ_PATH); + final JsonObject out = ptr.add(in, OBJ_VALUE); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + OBJ_PATH + "\" ADD \"" + + OBJ_VALUE + "\" failed on simple JSON object"); + } + } + + /** + * Test pointer ADD operation for {@code JsonObject} on simple JSON array of + * size 1. Using index {@code 0} to add {@code JsonObject} before already + * existing element and index {@code 1} and {@code -} to add + * {@code JsonObject} after already existing element. + * + * @param result + * Tests result record. + */ + private void testAddObjectOnSimpleArray(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 1"); + final JsonArray in = createObjectArray1(); + final JsonArray checkBefore = createSimpleObjectArrayWithObjectBefore(); + final JsonArray checkAfter = createSimpleObjectArrayWithObjectAfter(); + final JsonPointer ptrBefore = Json.createPointer("/0"); + final JsonPointer[] ptrsAfter = new JsonPointer[] { + Json.createPointer("/1"), Json.createPointer("/-") }; + final JsonArray outBefore = ptrBefore.add(in, OBJ_VALUE); + if (!assertEquals(checkBefore, outBefore)) { + result.fail("Pointer ADD operation", "Pointer \"/0\" ADD \"" + OBJ_VALUE + + "\" failed on simple JSON array"); + } + for (final JsonPointer ptrAfter : ptrsAfter) { + final JsonArray outAfter = ptrAfter.add(in, OBJ_VALUE); + if (!assertEquals(checkAfter, outAfter)) { + result.fail("Pointer ADD operation", "Pointer \"/1\" ADD \"" + OBJ_VALUE + + "\" failed on simple JSON array"); + } + } + } + + /** + * Test pointer ADD operation for {@code JsonObject} on simple JSON array of + * size 2. Starting with an array of size 2. + *
    + *
  • Adding {@code JsonObject} at the end, in the middle and at the + * beginning of this array. + *
  • Adding {@code JsonObject} at the beginning, in the middle and at the + * end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testAddObjectOnSimpleArray2(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 2"); + final JsonArray in = createObjectArray2(); + final JsonArray check = createSimpleObjectArray5(); + verifyAddValues(result, in, check, new String[] { "/2", "/1", "/0" }, + new JsonObject[] { OBJ_VALUE_5, OBJ_VALUE_3, OBJ_VALUE_1 }, + "Pointer ADD operation", + "Pointers \"/2\", \"/1\", \"/0\" ADD sequence failed on simple JSON array"); + verifyAddValues(result, in, check, new String[] { "/0", "/2", "/4" }, + new JsonObject[] { OBJ_VALUE_1, OBJ_VALUE_3, OBJ_VALUE_5 }, + "Pointer ADD operation", + "Pointers \"/0\", \"/2\", \"/4\" ADD sequence failed on simple JSON array"); + } + + // Tests based on RFC 6902 definitions and examples. + + /** + * Test that existing target object is replaced by specified array when ADD + * operation is applied. + * {@see RFC 6902: + * 4.1. add}:
+ * When the operation is applied, the target location MUST reference one of: + *
    + *
  • A member to add to an existing object - whereupon the supplied value is + * added to that object at the indicated location. If the member already + * exists, it is replaced by the specified value.
  • + *
  • ...
  • + *
+ */ + private void testAddArrayToReplaceObject(final TestResult result) { + System.out.println(" - for JsonArray to replace JsonObject"); + final JsonObject in = createCompoundObject(); + final JsonObject check = createCompoundObjectWithObjectReplaced(); + final JsonPointer ptr = Json.createPointer(DEF_OBJ_PATH); + final JsonArray replace = createSimpleStringArray5(); + final JsonObject out = ptr.add(in, replace); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + DEF_OBJ_PATH + + "\" ADD array to replace existing object failed on compound JSON object"); + } + } + + /** + * Test that whole document is replaced by specified array when ADD operation + * is applied with root pointer. + * {@see RFC 6902: + * 4.1. add}:
+ * When the operation is applied, the target location MUST reference one of: + *
    + *
  • The root of the target document - whereupon the specified value becomes + * the entire content of the target document.
  • + *
  • ...
  • + *
+ */ + private void testAddArrayToReplaceDocument(final TestResult result) { + System.out.println(" - for JsonArray to replace whole document"); + final JsonObject in = createCompoundObject(); + final JsonArray check = createSimpleStringArray5(); + final JsonPointer ptr = Json.createPointer(""); + final JsonArray replace = createSimpleStringArray5(); + // Instance being replaced is JsonObject, instance being added is JsonArray + final JsonStructure out = ptr.add((JsonStructure) in, replace); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", "Pointer \"" + DEF_OBJ_PATH + + "\" ADD array to replace existing object failed on compound JSON object"); + } + } + + /** + * Test ADD operation of an array of {@code String}s into existing array of + * {@code String}s. This scenario is inspired by + * {@see RFC 6902: + * 4.1. add} operation example {@code { "op": "add", "path": "/a/b/c", + * "value": [ "foo", "bar" ] }} and following explanation of this operation on + * an array: + *
    + *
  • An element to add to an existing array - whereupon the supplied value + * is added to the array at the indicated location. Any elements at or above + * the specified index are shifted one position to the right. The specified + * index MUST NOT be greater than the number of elements in the array. If the + * "-" character is used to index the end of the array (see [RFC6901]), this + * has the effect of appending the value to the array.
  • + *
+ */ + private void testAddStringArrayToStringArray(final TestResult result) { + System.out.println(" - for String array to be added to existing String array"); + final JsonArray in = createStringArray2(); + final JsonArray check = createStringArray2WithStringArrayInTheMiddle(); + final JsonArray arrayToAdd = createStringInnerArray2(); + final JsonPointer ptr = Json.createPointer("/1"); + final JsonArray out = ptr.add(in, arrayToAdd); + if (!assertEquals(check, out)) { + result.fail("Pointer ADD operation", + "Pointer \"/1\" ADD array failed on JSON array"); + } + } + + /** + * Test ADD operation on non existing JsonObject. This scenario is described + * in {@see RFC + * 6902: 4.1. add} error handling samples. Test is trying to ADD value { + * "address" : "In a galaxy far far away"} into object { "name" : "John Smith" + * } using path "/child/address". Even "/child" path does not exist so this + * operation must fail. + * + */ + private void testAddStringToNonExistingObject(final TestResult result) { + System.out.println(" - for String to be added to non existing JsonObject"); + final JsonObject in = createSimpleObject(); + final JsonPointer ptr = Json.createPointer(DEF_OBJ_PATH + STR_PATH); + boolean exception = false; + try { + ptr.add(in, Json.createValue(STR_VALUE)); + } catch (JsonException e) { + exception = true; + System.out.println(" - Expected exception: " + e.getMessage()); + } + if (!exception) { + result.fail("Pointer ADD operation", + "ADD operation on non existing JsonObject \"" + DEF_OBJ_PATH + + "\" passed"); + } + } + + /** + * Test helper: Verify set of ADD operations on provided JSON array and verify + * result using provided expected JSON value. JSON pointer instance is used to + * modify the array. + * + * @param result + * Test suite result. + * @param in + * JSON array to be modified. + * @param check + * Expected modified JSON array (used for operation check). + * @param paths + * JSON array paths of values to be added. Pairs of {@code paths[i]} + * and {@code values[i]} are used for add operations. + * @param values + * JSON array values to be added on specified indexes. + * @param testName + * Name of this test. + * @param errorMessage + * Error message to be added on verification failure. + */ + private void verifyAddValues(final TestResult result, final JsonArray in, + final JsonArray check, final String[] paths, final Object[] values, + final String testName, final String errorMessage) { + if (paths.length != values.length) { + throw new IllegalArgumentException( + "Number of paths does not match number of indexes"); + } + JsonArray out = in; + for (int i = 0; i < paths.length; i++) { + final JsonPointer ptr = Json.createPointer(paths[i]); + out = ptr.add(out, toJsonValue(values[i])); + } + if (!assertEquals(check, out)) { + result.fail(testName, errorMessage); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerRemove.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerRemove.java new file mode 100644 index 00000000..3622a4ee --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerRemove.java @@ -0,0 +1,610 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.pointertests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonException; +import jakarta.json.JsonObject; +import jakarta.json.JsonPointer; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * {@see RFC 6901}: pointer + * usage for {@see RFC 6902} + * remove operation tests.
+ */ +public class PointerRemove { + + /** + * Creates an instance of RFC 6901 pointer instance usage for RFC 6902 remove + * operation tests. + */ + PointerRemove() { + super(); + } + + /** + * Test RFC 6901 pointer instance usage for RFC 6902 remove operation. Suite + * entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "RFC 6901 pointer usage for RFC 6902 remove operation"); + System.out.println("Testing RFC 6901 pointer usage for RFC 6902 remove operation"); + testRemoveStringOnEmptyObject(result); + testRemoveStringOnEmptyArray(result); + testRemoveStringOnSimpleObject(result); + testRemoveStringOnSimpleArray(result); + testRemoveStringOnSimpleArray2(result); + testRemoveIntOnEmptyObject(result); + testRemoveIntOnEmptyArray(result); + testRemoveIntOnSimpleObject(result); + testRemoveIntOnSimpleArray(result); + testRemoveIntOnSimpleArray2(result); + testRemoveBoolOnEmptyObject(result); + testRemoveBoolOnEmptyArray(result); + testRemoveBoolOnSimpleObject(result); + testRemoveBoolOnSimpleArray(result); + testRemoveBoolOnSimpleArray2(result); + testRemoveObjectOnEmptyObject(result); + testRemoveObjectOnEmptyArray(result); + testRemoveObjectOnSimpleObject(result); + testRemoveObjectOnSimpleArray(result); + testRemoveObjectOnSimpleArray2(result); + testRemoveFromNonExistingLocationInObject(result); + testRemoveFromNonExistingLocationInArray(result); + return result; + } + + /** + * Test pointer REMOVE operation for {@code String} to produce empty JSON + * object. + * + * @param result + * Tests result record. + */ + private void testRemoveStringOnEmptyObject(final TestResult result) { + System.out.println(" - for String to produce empty JSON object"); + final JsonObject in = createSimpleObjectStr(); + final JsonObject check = createEmptyObject(); + final JsonPointer ptr = Json.createPointer(STR_PATH); + final JsonObject out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", "Pointer \"" + STR_PATH + + "\" REMOVE failed when producing empty JSON object"); + } + } + + /** + * Test pointer REMOVE operation for {@code String} to produce empty JSON + * array. Only allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testRemoveStringOnEmptyArray(final TestResult result) { + System.out.println(" - for String to produce empty JSON array"); + final JsonArray in = createEmptyArrayWithStr(); + final JsonArray check = createEmptyArray(); + final JsonPointer ptr = Json.createPointer("/0"); + final JsonArray out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/0\" REMOVE failed when producing empty JSON array"); + } + } + + /** + * Test pointer REMOVE operation for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveStringOnSimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObjectWithStr(); + final JsonObject check = createSimpleObject(); + final JsonPointer ptr = Json.createPointer(STR_PATH); + final JsonObject out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", + "Pointer \"" + STR_PATH + "\" REMOVE failed on simple JSON object"); + } + } + + /** + * Test pointer REMOVE operation for {@code String} on simple JSON array of + * size 2. Using index {@code 0} to remove {@code String} before another + * existing element and index {@code 1} to remove {@code String} after another + * existing element. + * + * @param result + * Tests result record. + */ + private void testRemoveStringOnSimpleArray(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 2"); + final JsonArray inBefore = createSimpleStringArrayWithStrBefore(); + final JsonArray inAfter = createSimpleStringArrayWithStrAfter(); + final JsonArray check = createStringArray1(); + final JsonPointer ptrBefore = Json.createPointer("/0"); + final JsonPointer ptrAfter = Json.createPointer("/1"); + final JsonArray outBefore = ptrBefore.remove(inBefore); + final JsonArray outAfter = ptrAfter.remove(inAfter); + if (!assertEquals(check, outBefore)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/0\" REMOVE failed on simple JSON array"); + } + if (!assertEquals(check, outAfter)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/1\" REMOVE failed on simple JSON array"); + } + } + + /** + * Test pointer REMOVE for {@code String} on simple JSON array of size 5. + * Starting with an array of size 2. + *
    + *
  • Removing {@code String} at the end, at the middle and at the beginning + * of this array. + *
  • Removing {@code String} at the beginning, in the middle and at the end + * of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testRemoveStringOnSimpleArray2(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 5"); + final JsonArray in = createSimpleStringArray5(); + final JsonArray check = createStringArray2(); + verifyRemoveValues(result, in, check, new String[] { "/4", "/2", "/0" }, + "Pointer REMOVE operation", + "Pointers \"/4\", \"/2\", \"/0\" REMOVE sequence failed on simple JSON array"); + verifyRemoveValues(result, in, check, new String[] { "/0", "/1", "/2" }, + "Pointer REMOVE operation", + "Pointers \"/0\", \"/1\", \"/2\" REMOVE sequence failed on simple JSON array"); + } + + /** + * Test pointer REMOVE operation for {@code int} to produce empty JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveIntOnEmptyObject(final TestResult result) { + System.out.println(" - for int to produce empty JSON object"); + final JsonObject in = createSimpleObjectInt(); + final JsonObject check = createEmptyObject(); + final JsonPointer ptr = Json.createPointer(INT_PATH); + final JsonObject out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", "Pointer \"" + INT_PATH + + "\" REMOVE failed when producing empty JSON object"); + } + } + + /** + * Test pointer REMOVE operation for {@code int} to produce empty JSON array. + * Only allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testRemoveIntOnEmptyArray(final TestResult result) { + System.out.println(" - for int to produce empty JSON array"); + final JsonArray in = createEmptyArrayWithInt(); + final JsonArray check = createEmptyArray(); + final JsonPointer ptr = Json.createPointer("/0"); + final JsonArray out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/0\" REMOVE failed when producing empty JSON array"); + } + } + + /** + * Test pointer REMOVE operation for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveIntOnSimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObjectWithInt(); + final JsonObject check = createSimpleObject(); + final JsonPointer ptr = Json.createPointer(INT_PATH); + final JsonObject out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", + "Pointer \"" + INT_PATH + "\" REMOVE failed on simple JSON object"); + } + } + + /** + * Test pointer REMOVE operation for {@code int} on simple JSON array of size + * 2. Using index {@code 0} to remove {@code int} before another existing + * element and index {@code 1} to remove {@code int} after another existing + * element. + * + * @param result + * Tests result record. + */ + private void testRemoveIntOnSimpleArray(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 2"); + final JsonArray inBefore = createSimpleIntArrayWithIntBefore(); + final JsonArray inAfter = createSimpleIntArrayWithIntAfter(); + final JsonArray check = createIntArray1(); + final JsonPointer ptrBefore = Json.createPointer("/0"); + final JsonPointer ptrAfter = Json.createPointer("/1"); + final JsonArray outBefore = ptrBefore.remove(inBefore); + final JsonArray outAfter = ptrAfter.remove(inAfter); + if (!assertEquals(check, outBefore)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/0\" REMOVE failed on simple JSON array"); + } + if (!assertEquals(check, outAfter)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/1\" REMOVE failed on simple JSON array"); + } + } + + /** + * Test pointer REMOVE for {@code int} on simple JSON array of size 5. + * Starting with an array of size 5. + *
    + *
  • Removing {@code int} at the end, at the middle and at the beginning of + * this array. + *
  • Removing {@code int} at the beginning, in the middle and at the end of + * this array. + *
+ * + * @param result + * Tests result record. + */ + private void testRemoveIntOnSimpleArray2(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 5"); + final JsonArray in = createSimpleIntArray5(); + final JsonArray check = createIntArray2(); + verifyRemoveValues(result, in, check, new String[] { "/4", "/2", "/0" }, + "Pointer REMOVE operation", + "Pointers \"/4\", \"/2\", \"/0\" REMOVE sequence failed on simple JSON array"); + verifyRemoveValues(result, in, check, new String[] { "/0", "/1", "/2" }, + "Pointer REMOVE operation", + "Pointers \"/0\", \"/1\", \"/2\" REMOVE sequence failed on simple JSON array"); + } + + /** + * Test pointer REMOVE operation for {@code boolean} to produce empty JSON + * object. + * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnEmptyObject(final TestResult result) { + System.out.println(" - for boolean to produce empty JSON object"); + final JsonObject in = createSimpleObjectBool(); + final JsonObject check = createEmptyObject(); + final JsonPointer ptr = Json.createPointer(BOOL_PATH); + final JsonObject out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", "Pointer \"" + BOOL_PATH + + "\" REMOVE failed when producing empty JSON object"); + } + } + + /** + * Test pointer REMOVE operation for {@code boolean} to produce empty JSON + * array. Only allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnEmptyArray(final TestResult result) { + System.out.println(" - for boolean to produce empty JSON array"); + final JsonArray in = createEmptyArrayWithBool(); + final JsonArray check = createEmptyArray(); + final JsonPointer ptr = Json.createPointer("/0"); + final JsonArray out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/0\" REMOVE failed when producing empty JSON array"); + } + } + + /** + * Test pointer REMOVE operation for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnSimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObjectWithBool(); + final JsonObject check = createSimpleObject(); + final JsonPointer ptr = Json.createPointer(BOOL_PATH); + final JsonObject out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", + "Pointer \"" + BOOL_PATH + "\" REMOVE failed on simple JSON object"); + } + } + + /** + * Test pointer REMOVE operation for {@code boolean} on simple JSON array of + * size 2. Using index {@code 0} to remove {@code boolean} before another + * existing element and index {@code 1} to remove {@code boolean} after + * another existing element. + * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnSimpleArray(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 2"); + final JsonArray inBefore = createSimpleBoolArrayWithBoolBefore(); + final JsonArray inAfter = createSimpleBoolArrayWithBoolAfter(); + final JsonArray check = createBoolArray1(); + final JsonPointer ptrBefore = Json.createPointer("/0"); + final JsonPointer ptrAfter = Json.createPointer("/1"); + final JsonArray outBefore = ptrBefore.remove(inBefore); + final JsonArray outAfter = ptrAfter.remove(inAfter); + if (!assertEquals(check, outBefore)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/0\" REMOVE failed on simple JSON array"); + } + if (!assertEquals(check, outAfter)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/1\" REMOVE failed on simple JSON array"); + } + } + + /** + * Test pointer REMOVE for {@code boolean} on simple JSON array of size 5. + * Starting with an array of size 5. + *
    + *
  • Removing {@code boolean} at the end, at the middle and at the beginning + * of this array. + *
  • Removing {@code boolean} at the beginning, in the middle and at the end + * of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testRemoveBoolOnSimpleArray2(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 5"); + final JsonArray in = createSimpleBoolArray5(); + final JsonArray check = createBoolArray2(); + verifyRemoveValues(result, in, check, new String[] { "/4", "/2", "/0" }, + "Pointer REMOVE operation", + "Pointers \"/4\", \"/2\", \"/0\" REMOVE sequence failed on simple JSON array"); + verifyRemoveValues(result, in, check, new String[] { "/0", "/1", "/2" }, + "Pointer REMOVE operation", + "Pointers \"/0\", \"/1\", \"/2\" REMOVE sequence failed on simple JSON array"); + } + + /** + * Test pointer REMOVE operation for {@code JsonObject} to produce empty JSON + * object. + * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnEmptyObject(final TestResult result) { + System.out.println(" - for JsonObject to produce empty JSON object"); + final JsonObject in = createSimpleObjectObject(); + final JsonObject check = createEmptyObject(); + final JsonPointer ptr = Json.createPointer(OBJ_PATH); + final JsonObject out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", "Pointer \"" + OBJ_PATH + + "\" REMOVE failed when producing empty JSON object"); + } + } + + /** + * Test pointer REMOVE operation for {@code JsonObject} to produce empty JSON + * array. Only allowed index for empty array is {@code 0}. + * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnEmptyArray(final TestResult result) { + System.out.println(" - for JsonObject to produce empty JSON array"); + final JsonArray in = createEmptyArrayWithObject(); + final JsonArray check = createEmptyArray(); + final JsonPointer ptr = Json.createPointer("/0"); + final JsonArray out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/0\" REMOVE failed when producing empty JSON array"); + } + } + + /** + * Test pointer REMOVE operation for {@code JsonObject} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnSimpleObject(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON object"); + final JsonObject in = createCompoundObjectWithObject(); + final JsonObject check = createCompoundObject(); + final JsonPointer ptr = Json.createPointer(OBJ_PATH); + final JsonObject out = ptr.remove(in); + if (!assertEquals(check, out)) { + result.fail("Pointer REMOVE operation", + "Pointer \"" + OBJ_PATH + "\" REMOVE failed on simple JSON object"); + } + } + + /** + * Test pointer REMOVE operation for {@code JsonObject} on simple JSON array + * of size 2. Using index {@code 0} to remove {@code JsonObject} before + * another existing element and index {@code 1} to remove {@code JsonObject} + * after another existing element. + * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnSimpleArray(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 2"); + final JsonArray inBefore = createSimpleObjectArrayWithObjectBefore(); + final JsonArray inAfter = createSimpleObjectArrayWithObjectAfter(); + final JsonArray check = createObjectArray1(); + final JsonPointer ptrBefore = Json.createPointer("/0"); + final JsonPointer ptrAfter = Json.createPointer("/1"); + final JsonArray outBefore = ptrBefore.remove(inBefore); + final JsonArray outAfter = ptrAfter.remove(inAfter); + if (!assertEquals(check, outBefore)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/0\" REMOVE failed on simple JSON array"); + } + if (!assertEquals(check, outAfter)) { + result.fail("Pointer REMOVE operation", + "Pointer \"/1\" REMOVE failed on simple JSON array"); + } + } + + /** + * Test pointer REMOVE for {@code JsonObject} on simple JSON array of size 5. + * Starting with an array of size 5. + *
    + *
  • Removing {@code JsonObject} at the end, at the middle and at the + * beginning of this array. + *
  • Removing {@code JsonObject} at the beginning, in the middle and at the + * end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testRemoveObjectOnSimpleArray2(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 5"); + final JsonArray in = createSimpleObjectArray5(); + final JsonArray check = createObjectArray2(); + verifyRemoveValues(result, in, check, new String[] { "/4", "/2", "/0" }, + "Pointer REMOVE operation", + "Pointers \"/4\", \"/2\", \"/0\" REMOVE sequence failed on simple JSON array"); + verifyRemoveValues(result, in, check, new String[] { "/0", "/1", "/2" }, + "Pointer REMOVE operation", + "Pointers \"/0\", \"/1\", \"/2\" REMOVE sequence failed on simple JSON array"); + } + + // Tests based on RFC 6902 definitions and examples. + + /** + * Test pointer REMOVE for non existing location in object. + * {@see RFC 6902: + * 4.2. remove} defines:
+ * The target location MUST exist for the operation to be successful. + */ + private void testRemoveFromNonExistingLocationInObject( + final TestResult result) { + System.out.println(" - for non existing location in JsonObject"); + final JsonObject[] objsIn = new JsonObject[] { createEmptyObject(), + createSimpleObject(), createCompoundObject() }; + final String[] paths = new String[] { STR_PATH, INT_PATH, BOOL_PATH, + OBJ_PATH }; + // Go trough all objects + for (int i = 0; i < objsIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + final JsonPointer ptr = Json.createPointer(paths[j]); + try { + final JsonObject out = ptr.remove(objsIn[i]); + result.fail("Pointer REMOVE operation", "Pointer \"" + paths[j] + + "\" REMOVE succeeded on non existing location"); + } catch (JsonException e) { + // There are too many combinations to log them. + } + } + } + } + + /** + * Test pointer REMOVE for non existing location in array. + * {@see RFC 6902: + * 4.2. remove} defines:
+ * The target location MUST exist for the operation to be successful. + */ + private void testRemoveFromNonExistingLocationInArray( + final TestResult result) { + System.out.println(" - for non existing location in JsonArray"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray1(), createIntArray2(), createSimpleBoolArray5(), + createObjectArray2() + + }; + final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", + STR_PATH + "/0" }; + // Go trough all arrays + for (int i = 0; i < arraysIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + final JsonPointer ptr = Json.createPointer(paths[j]); + try { + final JsonArray out = ptr.remove(arraysIn[i]); + result.fail("Pointer REMOVE operation", "Pointer \"" + paths[j] + + "\" REMOVE succeeded on non existing location"); + } catch (JsonException e) { + // There are too many combinations to log them. + } + } + } + } + + /** + * Test helper: Verify set of REMOVE operations on provided JSON array and + * verify result using provided expected JSON value. JSON pointer instance is + * used to modify the array. + * + * @param result + * Test suite result. + * @param in + * JSON array to be modified. + * @param check + * Expected modified JSON array (used for operation check). + * @param paths + * JSON array paths of values to be added. Pairs of {@code paths[i]} + * and {@code values[i]} are used for add operations. + * @param testName + * Name of this test. + * @param errorMessage + * Error message to be added on verification failure. + */ + private void verifyRemoveValues(final TestResult result, final JsonArray in, + final JsonArray check, final String[] paths, final String testName, + final String errorMessage) { + JsonArray out = in; + for (int i = 0; i < paths.length; i++) { + final JsonPointer ptr = Json.createPointer(paths[i]); + out = ptr.remove(out); + } + if (!assertEquals(check, out)) { + result.fail(testName, errorMessage); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerReplace.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerReplace.java new file mode 100644 index 00000000..0d9708dd --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerReplace.java @@ -0,0 +1,438 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.pointertests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonException; +import jakarta.json.JsonObject; +import jakarta.json.JsonPointer; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * {@see RFC 6901}: pointer + * usage for {@see RFC 6902} + * replace operation tests.
+ */ +public class PointerReplace { + + /** + * Creates an instance of RFC 6901 pointer instance usage for RFC 6902 replace + * operation tests. + */ + PointerReplace() { + super(); + } + + /** + * Test RFC 6901 pointer instance usage for RFC 6902 replace operation. Suite + * entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult( + "RFC 6901 pointer usage for RFC 6902 replace operation"); + System.out.println( + "Testing RFC 6901 pointer usage for RFC 6902 replace operation"); + testReplaceStringOnSimpleObject(result); + testReplaceStringOnSimpleArray(result); + testReplaceStringOnSimpleArray2(result); + testReplaceIntOnSimpleObject(result); + testReplaceIntOnSimpleArray(result); + testReplaceIntOnSimpleArray2(result); + testReplaceBoolOnSimpleObject(result); + testReplaceBoolOnSimpleArray(result); + testReplaceBoolOnSimpleArray2(result); + testReplaceObjectOnCompoundObject(result); + testReplaceObjectOnSimpleArray(result); + testReplaceObjectOnSimpleArray2(result); + testReplaceOfNonExistingLocationInObject(result); + testReplaceOfNonExistingLocationInArray(result); + return result; + } + + /** + * Test pointer REPLACE operation for {@code String} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testReplaceStringOnSimpleObject(final TestResult result) { + System.out.println(" - for String on simple JSON object"); + final JsonObject in = createSimpleObjectStr(); + final JsonObject check = createSimpleObjectReplaceStr(); + final JsonPointer ptr = Json.createPointer(STR_PATH); + final JsonObject out = ptr.replace(in, Json.createValue(STR_VALUE2)); + if (!assertEquals(check, out)) { + result.fail("Pointer REPLACE operation", "Pointer \"" + STR_PATH + + "\" REPLACE \"" + STR_VALUE2 + "\" failed on simple JSON object"); + } + } + + /** + * Test pointer REPLACE operation for {@code String} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testReplaceStringOnSimpleArray(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 1"); + final JsonArray in = createStringArray1(); + final JsonArray check = createSimpleStringArrayReplaceStr(); + final JsonPointer ptr = Json.createPointer("/0"); + final JsonArray out = ptr.replace(in, Json.createValue(STR_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer REPLACE operation", "Pointer \"/0\" REPLACE \"" + + STR_VALUE + "\" failed on simple JSON array"); + } + } + + /** + * Test pointer REPLACE operation for {@code String} on simple JSON array of + * size 5. Starting with an array of size 5. + *
    + *
  • Replacing {@code String} items from the end to the beginning of this + * array. + *
  • Replacing {@code String} from the beginning to the end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testReplaceStringOnSimpleArray2(final TestResult result) { + System.out.println(" - for String on simple JSON array of size 5"); + final JsonArray in = createSimpleStringArray5(); + final JsonArray check = createSimpleStringArray5R(); + verifyReplaceValues(result, in, check, + new String[] { "/4", "/3", "/1", "/0" }, + new String[] { STR_VALUE_1, STR_VALUE_2, STR_VALUE_4, STR_VALUE_5 }, + "Pointer REPLACE operation", + "Pointers \"/4\", \"/3\", \"/1\", \"/0\" REPLACE sequence failed on simple JSON array"); + verifyReplaceValues(result, in, check, + new String[] { "/0", "/1", "/3", "/4" }, + new String[] { STR_VALUE_5, STR_VALUE_4, STR_VALUE_2, STR_VALUE_1 }, + "Pointer REPLACE operation", + "Pointers \"/0\", \"/1\", \"/3\", \"/4\" REPLACE sequence failed on simple JSON array"); + } + + /** + * Test pointer REPLACE operation for {@code int} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testReplaceIntOnSimpleObject(final TestResult result) { + System.out.println(" - for int on simple JSON object"); + final JsonObject in = createSimpleObjectInt(); + final JsonObject check = createSimpleObjectReplaceInt(); + final JsonPointer ptr = Json.createPointer(INT_PATH); + final JsonObject out = ptr.replace(in, Json.createValue(INT_VALUE2)); + if (!assertEquals(check, out)) { + result.fail("Pointer REPLACE operation", "Pointer \"" + INT_PATH + + "\" REPLACE \"" + INT_VALUE2 + "\" failed on simple JSON object"); + } + } + + /** + * Test pointer REPLACE operation for {@code int} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testReplaceIntOnSimpleArray(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 1"); + final JsonArray in = createIntArray1(); + final JsonArray check = createSimpleIntArrayReplaceInt(); + final JsonPointer ptr = Json.createPointer("/0"); + final JsonArray out = ptr.replace(in, Json.createValue(INT_VALUE)); + if (!assertEquals(check, out)) { + result.fail("Pointer REPLACE operation", "Pointer \"/0\" REPLACE \"" + + INT_VALUE + "\" failed on simple JSON array"); + } + } + + /** + * Test pointer REPLACE operation for {@code int} on simple JSON array of size + * 5. Starting with an array of size 5. + *
    + *
  • Replacing {@code int} items from the end to the beginning of this + * array. + *
  • Replacing {@code int} from the beginning to the end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testReplaceIntOnSimpleArray2(final TestResult result) { + System.out.println(" - for int on simple JSON array of size 5"); + final JsonArray in = createSimpleIntArray5(); + final JsonArray check = createSimpleIntArray5R(); + verifyReplaceValues(result, in, check, + new String[] { "/4", "/3", "/1", "/0" }, + new Integer[] { INT_VALUE_1, INT_VALUE_2, INT_VALUE_4, INT_VALUE_5 }, + "Pointer REPLACE operation", + "Pointers \"/4\", \"/3\", \"/1\", \"/0\" REPLACE sequence failed on simple JSON array"); + verifyReplaceValues(result, in, check, + new String[] { "/0", "/1", "/3", "/4" }, + new Integer[] { INT_VALUE_5, INT_VALUE_4, INT_VALUE_2, INT_VALUE_1 }, + "Pointer REPLACE operation", + "Pointers \"/0\", \"/1\", \"/3\", \"/4\" REPLACE sequence failed on simple JSON array"); + } + + /** + * Test pointer REPLACE operation for {@code boolean} on simple JSON object. + * + * @param result + * Tests result record. + */ + private void testReplaceBoolOnSimpleObject(final TestResult result) { + System.out.println(" - for boolean on simple JSON object"); + final JsonObject in = createSimpleObjectBool(); + final JsonObject check = createSimpleObjectReplaceBool(); + final JsonPointer ptr = Json.createPointer(BOOL_PATH); + final JsonObject out = ptr.replace(in, toJsonValue(BOOL_VALUE2)); + if (!assertEquals(check, out)) { + result.fail("Pointer REPLACE operation", "Pointer \"" + BOOL_PATH + + "\" REPLACE \"" + BOOL_VALUE2 + "\" failed on simple JSON object"); + } + } + + /** + * Test pointer REPLACE operation for {@code boolean} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testReplaceBoolOnSimpleArray(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 1"); + final JsonArray in = createBoolArray1(); + final JsonArray check = createSimpleBoolArrayReplaceBool(); + final JsonPointer ptr = Json.createPointer("/0"); + final JsonArray out = ptr.replace(in, toJsonValue(BOOL_FALSE)); + if (!assertEquals(check, out)) { + result.fail("Pointer REPLACE operation", "Pointer \"/0\" REPLACE \"" + + BOOL_FALSE + "\" failed on simple JSON array"); + } + } + + /** + * Test pointer REPLACE operation for {@code boolean} on simple JSON array of + * size 5. Starting with an array of size 5. + *
    + *
  • Replacing {@code boolean} items from the end to the beginning of this + * array. + *
  • Replacing {@code boolean} from the beginning to the end of this array. + *
+ * + * @param result + * Tests result record. + */ + private void testReplaceBoolOnSimpleArray2(final TestResult result) { + System.out.println(" - for boolean on simple JSON array of size 5"); + final JsonArray in = createSimpleBoolArray5(); + final JsonArray check = createSimpleBoolArray5R(); + verifyReplaceValues(result, in, check, + new String[] { "/4", "/3", "/1", "/0" }, + new Boolean[] { BOOL_FALSE, BOOL_TRUE, BOOL_FALSE, BOOL_TRUE }, + "Pointer REPLACE operation", + "Pointers \"/4\", \"/3\", \"/1\", \"/0\" REPLACE sequence failed on simple JSON array"); + verifyReplaceValues(result, in, check, + new String[] { "/0", "/1", "/3", "/4" }, + new Boolean[] { BOOL_TRUE, BOOL_FALSE, BOOL_TRUE, BOOL_FALSE }, + "Pointer REPLACE operation", + "Pointers \"/0\", \"/1\", \"/3\", \"/4\" REPLACE sequence failed on simple JSON array"); + } + + /** + * Test pointer REPLACE operation for {@code JsonObject} on compound JSON + * object. + * + * @param result + * Tests result record. + */ + private void testReplaceObjectOnCompoundObject(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON object"); + final JsonObject in = createCompoundObjectWithObject(); + final JsonObject check = createCompoundObjectReplaceObject(); + final JsonPointer ptr = Json.createPointer(OBJ_PATH); + final JsonObject out = ptr.replace(in, OBJ_VALUE2); + if (!assertEquals(check, out)) { + result.fail("Pointer REPLACE operation", "Pointer \"" + OBJ_PATH + + "\" REPLACE \"" + OBJ_VALUE2 + "\" failed on simple JSON object"); + } + } + + /** + * Test pointer REPLACE operation for {@code JsonObject} on simple JSON array. + * + * @param result + * Tests result record. + */ + private void testReplaceObjectOnSimpleArray(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 1"); + final JsonArray in = createObjectArray1(); + final JsonArray check = createSimpleObjectArrayReplaceObject(); + final JsonPointer ptr = Json.createPointer("/0"); + final JsonArray out = ptr.replace(in, OBJ_VALUE); + if (!assertEquals(check, out)) { + result.fail("Pointer REPLACE operation", "Pointer \"/0\" REPLACE \"" + + OBJ_VALUE + "\" failed on simple JSON array"); + } + } + + /** + * Test pointer REPLACE operation for {@code JsonObject} on simple JSON array + * of size 5. Starting with an array of size 5. + *
    + *
  • Replacing {@code JsonObject} items from the end to the beginning of + * this array. + *
  • Replacing {@code JsonObject} from the beginning to the end of this + * array. + *
+ * + * @param result + * Tests result record. + */ + private void testReplaceObjectOnSimpleArray2(final TestResult result) { + System.out.println(" - for JsonObject on simple JSON array of size 5"); + final JsonArray in = createSimpleObjectArray5(); + final JsonArray check = createSimpleObjectArray5R(); + verifyReplaceValues(result, in, check, + new String[] { "/4", "/3", "/1", "/0" }, + new JsonObject[] { OBJ_VALUE_1, OBJ_VALUE_2, OBJ_VALUE_4, OBJ_VALUE_5 }, + "Pointer REPLACE operation", + "Pointers \"/4\", \"/3\", \"/1\", \"/0\" REPLACE sequence failed on simple JSON array"); + verifyReplaceValues(result, in, check, + new String[] { "/0", "/1", "/3", "/4" }, + new JsonObject[] { OBJ_VALUE_5, OBJ_VALUE_4, OBJ_VALUE_2, OBJ_VALUE_1 }, + "Pointer REPLACE operation", + "Pointers \"/0\", \"/1\", \"/3\", \"/4\" REPLACE sequence failed on simple JSON array"); + } + + // Tests based on RFC 6902 definitions and examples. + + /** + * Test pointer REPLACE for non existing location in object. + * {@see RFC 6902: + * 4.3. replace} defines:
+ * The target location MUST exist for the operation to be successful. + */ + private void testReplaceOfNonExistingLocationInObject( + final TestResult result) { + System.out.println(" - for non existing location in JsonObject"); + final JsonObject[] objsIn = new JsonObject[] { createEmptyObject(), + createSimpleObject(), createCompoundObject() }; + final String[] paths = new String[] { STR_PATH, INT_PATH, BOOL_PATH, + OBJ_PATH }; + final JsonValue[] values = new JsonValue[] { Json.createValue(STR_VALUE), + Json.createValue(INT_VALUE), toJsonValue(BOOL_VALUE), OBJ_VALUE }; + // Go trough all objects + for (int i = 0; i < objsIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + final JsonPointer ptr = Json.createPointer(paths[j]); + try { + final JsonObject out = ptr.replace(objsIn[i], values[i]); + result.fail("Pointer REPLACE operation", "Pointer \"" + paths[j] + + "\" REPLACE succeeded on non existing location"); + } catch (JsonException e) { + // There are too many combinations to log them. + } + } + } + } + + /** + * Test pointer REPLACE for non existing location in array. + * {@see RFC 6902: + * 4.2. remove} defines:
+ * The target location MUST exist for the operation to be successful. + */ + private void testReplaceOfNonExistingLocationInArray( + final TestResult result) { + System.out.println(" - for non existing location in JsonArray"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray1(), createIntArray2(), createSimpleBoolArray5(), + createObjectArray2() + + }; + final String[] paths = new String[] { "/", "/-1", "/-", "/5", "/0a", "/42", + STR_PATH + "/0" }; + final JsonValue[] values = new JsonValue[] { Json.createValue(STR_VALUE), + Json.createValue(STR_VALUE), Json.createValue(INT_VALUE), + toJsonValue(BOOL_VALUE), OBJ_VALUE }; + // Go trough all arrays + for (int i = 0; i < arraysIn.length; i++) { + // Go trough all paths + for (int j = 0; j < paths.length; j++) { + final JsonPointer ptr = Json.createPointer(paths[j]); + try { + final JsonArray out = ptr.replace(arraysIn[i], values[i]); + result.fail("Pointer REPLACE operation", "Pointer \"" + paths[j] + + "\" REPLACE succeeded on non existing location"); + } catch (JsonException e) { + // There are too many combinations to log them. + } + } + } + } + + /** + * Test helper: Verify set of REPLACE operations on provided JSON array and + * verify result using provided expected JSON value. JSON pointer instance is + * used to modify the array. + * + * @param result + * Test suite result. + * @param in + * JSON array to be modified. + * @param check + * Expected modified JSON array (used for operation check). + * @param paths + * JSON array paths of values to be added. Pairs of {@code paths[i]} + * and {@code values[i]} are used for add operations. + * @param values + * JSON array values to be added on specified indexes. + * @param testName + * Name of this test. + * @param errorMessage + * Error message to be added on verification failure. + */ + private void verifyReplaceValues(final TestResult result, final JsonArray in, + final JsonArray check, final String[] paths, final Object[] values, + final String testName, final String errorMessage) { + if (paths.length != values.length) { + throw new IllegalArgumentException( + "Number of paths does not match number of indexes"); + } + JsonArray out = in; + for (int i = 0; i < paths.length; i++) { + final JsonPointer ptr = Json.createPointer(paths[i]); + out = ptr.replace(out, toJsonValue(values[i])); + } + if (!assertEquals(check, out)) { + result.fail(testName, errorMessage); + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerResolve.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerResolve.java new file mode 100644 index 00000000..130df0fd --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerResolve.java @@ -0,0 +1,622 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.pointertests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.json.Json; +import jakarta.json.JsonArray; +import jakarta.json.JsonException; +import jakarta.json.JsonObject; +import jakarta.json.JsonPointer; +import jakarta.json.JsonValue; + +import static jakarta.jsonp.tck.api.common.JsonAssert.*; +import static jakarta.jsonp.tck.api.common.PointerRFCObject.*; +import static jakarta.jsonp.tck.api.common.SimpleValues.*; + +// $Id$ +/** + * {@see RFC 6901}: JavaScript + * Object Notation (JSON) Pointer resolving tests.
+ */ +public class PointerResolve { + + /** + * Creates an instance of RFC 6901 JSON Pointer resolver tests. + */ + PointerResolve() { + super(); + } + + /** + * Test RFC 6901 JSON Pointer resolver tests. Suite entry point. + * + * @return Result of all tests in this suite. + */ + TestResult test() { + final TestResult result = new TestResult("RFC 6901 pointer resolving"); + System.out.println("Testing RFC 6901 pointer resolving"); + testResolveWholeDocument(result); + testResolveEmptyName(result); + testResolveSimpleArray(result); + testResolveSimpleArrayItems(result); + testResolvePathWithSlash(result); + testResolvePathWithEncodedSlash(result); + testResolvePathWithPercent(result); + testResolvePathWithCaret(result); + testResolvePathWithVerticalBar(result); + testResolvePathWithBackSlash(result); + testResolvePathWithDoubleQuotes(result); + testResolvePathWithSpace(result); + testResolvePathWithTilde(result); + testResolvePathWithEncodedTilde(result); + testResolvePathWithEncodedTildeOne(result); + testResolveValidNumericIndexInArray(result); + testResolveMemberAfterLastInArray(result); + testResolveNumericIndexWithLeadingZeroInArray(result); + testResolvenonNumericIndexInArray(result); + return result; + } + + /** + * Test RFC 6901 JSON Pointer resolver for the whole document path. + * + * @param result + * Tests result record. + */ + private void testResolveWholeDocument(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_KEY_WHOLE + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = in; + final JsonPointer ptr = Json.createPointer(RFC_KEY_WHOLE); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_KEY_WHOLE + "\"", + "GET operation failed for \"" + RFC_KEY_WHOLE + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_KEY_WHOLE + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "": 0}. + * + * @param result + * Tests result record. + */ + private void testResolveEmptyName(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR2 + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL2); + final JsonPointer ptr = Json.createPointer(RFC_PTR2); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR2 + "\"", + "GET operation failed for \"" + RFC_PTR2 + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_PTR2 + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "foo": ["bar", "baz"]}. + * + * @param result + * Tests result record. + */ + private void testResolveSimpleArray(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR1 + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = RFC_VAL1; + final JsonPointer ptr = Json.createPointer(RFC_PTR1); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR1 + "\"", + "GET operation failed for \"" + RFC_PTR1 + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_PTR1 + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "foo": ["bar", "baz"]} array + * elements. + * + * @param result + * Tests result record. + */ + private void testResolveSimpleArrayItems(final TestResult result) { + final String[] itemPtrs = new String[] { RFC_PTR1_ITEM1, RFC_PTR1_ITEM2 }; + final String[] itemVals = new String[] { RFC_VAL1_ITEM1, RFC_VAL1_ITEM2 }; + final JsonObject in = createRFC6901Object(); + for (int i = 0; i < itemPtrs.length; i++) { + System.out.println(" - resolving of \"" + itemPtrs[i] + "\" pointer"); + final JsonValue check = Json.createValue(itemVals[i]); + final JsonPointer ptr = Json.createPointer(itemPtrs[i]); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + itemPtrs[i] + "\"", + "GET operation failed for \"" + itemPtrs[i] + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + itemPtrs[i] + "\"", + "GET operation exception: " + e.getMessage()); + } + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "a/b": 1}. Character + * {@code '/'} is encoded as {@code "~1"} string. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithEncodedSlash(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR3_ENC + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL3); + final JsonPointer ptr = Json.createPointer(RFC_PTR3_ENC); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR3_ENC + "\"", + "GET operation failed for \"" + RFC_PTR3_ENC + "\" path"); + } + } catch (JsonException e) { + System.out.println(" ! Exception: " + e.getMessage()); + result.fail("GET \"" + RFC_PTR3_ENC + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "a/b": 1}. Character + * {@code '/'} is not encoded as {@code "~1"} string. This results in invalid + * {@code "/a/b"} path and resolving such path must throw an exception. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithSlash(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR3 + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonPointer ptr = Json.createPointer(RFC_PTR3); + try { + final JsonValue out = ptr.getValue(in); + result.fail("GET \"" + RFC_PTR3 + "\"", + "GET operation succeeded for \"" + RFC_PTR3 + "\" path"); + } catch (JsonException e) { + System.out.println(" - Expected exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "c%d": 2}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithPercent(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR4 + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL4); + final JsonPointer ptr = Json.createPointer(RFC_PTR4); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR4 + "\"", + "GET operation failed for \"" + RFC_PTR4 + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_PTR4 + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "e^f": 3}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithCaret(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR5 + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL5); + final JsonPointer ptr = Json.createPointer(RFC_PTR5); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR5 + "\"", + "GET operation failed for \"" + RFC_PTR5 + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_PTR5 + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "g|h": 4}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithVerticalBar(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR6 + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL6); + final JsonPointer ptr = Json.createPointer(RFC_PTR6); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR6 + "\"", + "GET operation failed for \"" + RFC_PTR6 + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_PTR6 + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "i\\j": 5}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithBackSlash(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR7 + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL7); + final JsonPointer ptr = Json.createPointer(RFC_PTR7); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR7 + "\"", + "GET operation failed for \"" + RFC_PTR7 + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_PTR7 + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "k\"l": 6}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithDoubleQuotes(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR8 + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL8); + final JsonPointer ptr = Json.createPointer(RFC_PTR8); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR8 + "\"", + "GET operation failed for \"" + RFC_PTR8 + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_PTR8 + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code " ": 7}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithSpace(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR9 + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL9); + final JsonPointer ptr = Json.createPointer(RFC_PTR9); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR9 + "\"", + "GET operation failed for \"" + RFC_PTR9 + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_PTR9 + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "m~n": 8} without encoding. + * Passing this test is not mandatory. + * {@see RFC 6901: 3. + * Syntax} defines JSON pointer grammar as:
+ * {@code json-pointer = *( "/" reference-token )}
+ * {@code reference-token = *( unescaped / escaped )}
+ * {@code unescaped = %x00-2E / %x30-7D / %x7F-10FFFF}
+ * {@code escaped = "~" ( "0" / "1" )}
+ * Characters {@code '/'} and {@code '~'} are excluded from {@code unescaped}. + * But having {@code '~'} outside escape sequence may be acceptable. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithTilde(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR10 + "\" pointer (optional)"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL10); + final JsonPointer ptr = Json.createPointer(RFC_PTR10); + boolean noError = true; + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + noError = false; + System.out.println(" - Pointer \"" + RFC_KEY10 + + "\" did not return expected value"); + } + } catch (JsonException e) { + noError = false; + System.out.println(" - Expected exception: " + e.getMessage()); + } + if (noError) { + System.out.println( + " - Pointer resolving accepts '~' outside escape sequence"); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "m~n": 8}. Character + * {@code '~'} is encoded as {@code "~0"} string. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithEncodedTilde(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_KEY10_ENC + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL10); + final JsonPointer ptr = Json.createPointer(RFC_KEY10_ENC); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_KEY10_ENC + "\"", + "GET operation failed for \"" + RFC_KEY10_ENC + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_KEY10_ENC + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for {@code "o~1p": 9}. String + * {@code "~1"} is encoded as {@code "~01"} String. Proper encoded sequences + * transformation is described in + * {@see RFC 6901: 4. + * Evaluation} chapter: + * {@code "the string '~01' correctly becomes '~1' after transformation"}. + * + * @param result + * Tests result record. + */ + private void testResolvePathWithEncodedTildeOne(final TestResult result) { + System.out.println(" - resolving of \"" + RFC_PTR11_ENC + "\" pointer"); + final JsonObject in = createRFC6901Object(); + final JsonValue check = Json.createValue(RFC_VAL11); + final JsonPointer ptr = Json.createPointer(RFC_PTR11_ENC); + try { + final JsonValue out = ptr.getValue(in); + if (!assertEquals(out, check)) { + result.fail("GET \"" + RFC_PTR11_ENC + "\"", + "GET operation failed for \"" + RFC_PTR11_ENC + "\" path"); + } + } catch (JsonException e) { + result.fail("GET \"" + RFC_PTR11_ENC + "\"", + "GET operation exception: " + e.getMessage()); + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for existing numeric indexes of an + * array. {@see RFC + * 6901: 4. Evaluation} chapter:
+ * If the currently referenced value is a JSON array, the reference token MUST + * contain either: + *
    + *
  • characters comprised of digits (see ABNF below; note that leading zeros + * are not allowed) that represent an unsigned base-10 integer value, making + * the new referenced value the array element with the zero-based index + * identified by the token
  • + *
+ */ + private void testResolveValidNumericIndexInArray(final TestResult result) { + System.out.println( + " - resolving of pointer containing existing numeric array index"); + final JsonArray[] arraysIn = new JsonArray[] { createSimpleStringArray5(), + createSimpleIntArray5(), createSimpleBoolArray5(), + createSimpleObjectArray5() }; + final JsonValue[] strings = new JsonValue[] { toJsonValue(STR_VALUE_1), + toJsonValue(STR_VALUE_2), toJsonValue(STR_VALUE_3), + toJsonValue(STR_VALUE_4), toJsonValue(STR_VALUE_5) }; + final JsonValue[] ints = new JsonValue[] { toJsonValue(INT_VALUE_1), + toJsonValue(INT_VALUE_2), toJsonValue(INT_VALUE_3), + toJsonValue(INT_VALUE_4), toJsonValue(INT_VALUE_5) }; + final JsonValue[] bools = new JsonValue[] { toJsonValue(BOOL_FALSE), + toJsonValue(BOOL_TRUE), toJsonValue(BOOL_TRUE), toJsonValue(BOOL_FALSE), + toJsonValue(BOOL_TRUE) }; + final JsonValue[] objs = new JsonValue[] { OBJ_VALUE_1, OBJ_VALUE_2, + OBJ_VALUE_3, OBJ_VALUE_4, OBJ_VALUE_5 }; + final JsonValue[][] checks = new JsonValue[][] { strings, ints, bools, + objs }; + // Go trough all array types + for (int i = 0; i < arraysIn.length; i++) { + // Go trough all valid indexes in arrays + for (int j = 0; j < 5; j++) { + final String path = "/" + Integer.toString(j); + final JsonPointer ptr = Json.createPointer(path); + final JsonValue out = ptr.getValue(arraysIn[i]); + if (!assertEquals(out, checks[i][j])) { + JsonValue.ValueType type = checks[i][j].getValueType(); + String typeName = type == JsonValue.ValueType.TRUE + || type == JsonValue.ValueType.FALSE ? "boolean" + : type.toString().toLowerCase(); + result.fail("GET \"" + path + "\"", "GET operation failed for \"" + + path + "\" path on " + typeName + " array"); + } + } + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for character {@code '-'} marking the + * end of an array. + * {@see RFC 6901: 4. + * Evaluation} chapter:
+ * If the currently referenced value is a JSON array, the reference token MUST + * contain either: + *
    + *
  • exactly the single character "-", making the new referenced value the + * (nonexistent) member after the last array element
  • + *
+ * Note that the use of the "-" character to index an array will always result + * in such an error condition because by definition it refers to a nonexistent + * array element. Thus, applications of JSON Pointer need to specify how that + * character is to be handled, if it is to be useful. + */ + private void testResolveMemberAfterLastInArray(final TestResult result) { + System.out.println(" - resolving of array \"/-\" pointer"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray(), createSimpleIntArray5(), createBoolArray2(), + createSimpleObjectArray5() }; + final String[] typeNames = new String[] { "empty", "String", "int", + "boolean", "JsonObject" }; + // Go trough all array types + for (int i = 0; i < arraysIn.length; i++) { + final JsonPointer ptr = Json.createPointer("/-"); + try { + final JsonValue out = ptr.getValue(arraysIn[i]); + result.fail("GET \"/-\"", "GET operation succeeded for \"/-\" key"); + } catch (JsonException e) { + System.out.println(" - Expected exception for \"/-\" path in " + + typeNames[i] + " array: " + e.getMessage()); + } + } + } + + // TODO: Consider whether passing this test is mandatory or optional. + /** + * Test RFC 6901 JSON Pointer resolver for existing index with leading + * {@code '0'} on array. + * {@see RFC 6901: 4. + * Evaluation} chapter:
+ * {@code array-index = %x30 / ( %x31-39 *(%x30-39) )} grammar rule prohibits + * indexes with leading {@code '0'} except the case when index is exactly + * {@code "0"}. Exact case for {@code "0"} is being checked in other tests. + * This test checks illegal values with leading {@code '0'} followed by valid + * index numbers. + */ + private void testResolveNumericIndexWithLeadingZeroInArray( + final TestResult result) { + System.out.println( + " - resolving of pointer containing numeric array index with leading '0' (optional)"); + final JsonArray[] arraysIn = new JsonArray[] { createSimpleStringArray5(), + createSimpleIntArray5(), createSimpleBoolArray5(), + createSimpleObjectArray5() }; + final String[] typeNames = new String[] { "String", "int", "boolean", + "JsonObject" }; + // Go trough all array types + for (int i = 0; i < arraysIn.length; i++) { + // Go trough all valid indexes in arrays + for (int j = 0; j < 5; j++) { + final String path = "/0" + Integer.toString(j); + final JsonPointer ptr = Json.createPointer(path); + try { + final JsonValue out = ptr.getValue(arraysIn[i]); + System.out.println(" ! GET operation succeeded for \"" + path + + "\" path on " + typeNames[i] + " array"); + // result.fail("GET \""+path+"\"", + // "GET operation succeeded for \""+path+"\" key on "+typeNames[i]+" + // array"); + } catch (JsonException e) { + // There are too many combinations to log them. + } + } + } + } + + /** + * Test RFC 6901 JSON Pointer resolver for invalid index containing non + * numeric characters on array. + * {@see RFC 6901: 4. + * Evaluation} chapter:
+ * {@code array-index = %x30 / ( %x31-39 *(%x30-39) )} grammar rule prohibits + * indexes with anything else than sequence of digits. Index {@code '-'} is + * being checked in another tests. The only exception is path for whole + * document ({@code ""}) which must return the whole array. + */ + private void testResolvenonNumericIndexInArray(final TestResult result) { + System.out.println(" - resolving of pointer containing non numeric array index"); + final JsonArray[] arraysIn = new JsonArray[] { createEmptyArray(), + createStringArray(), createSimpleIntArray5(), createBoolArray2(), + createSimpleObjectArray5() }; + final String[] typeNames = new String[] { "empty", "String", "int", + "boolean", "JsonObject" }; + final String wholeDocument = ""; + final String[] paths = new String[] { "/", "/1a", "/b4", "/name" }; + // Go trough all array types + for (int i = 0; i < arraysIn.length; i++) { + final JsonPointer wholeDocPtr = Json.createPointer(wholeDocument); + try { + final JsonValue wholeOut = wholeDocPtr.getValue(arraysIn[i]); + if (!assertEquals(wholeOut, arraysIn[i])) { + result.fail("GET \"" + wholeDocument + "\"", + "GET operation failed for \"" + wholeDocument + "\" path on " + + typeNames[i] + " array"); + } + } catch (JsonException e) { + result.fail("GET \"" + wholeDocument + "\"", + "GET operation failed for \"" + wholeDocument + "\" path on " + + typeNames[i] + " array: " + e.getMessage()); + } + for (int j = 0; j < paths.length; j++) { + final JsonPointer ptr = Json.createPointer(paths[j]); + try { + final JsonValue out = ptr.getValue(arraysIn[i]); + result.fail("GET \"" + paths[j] + "\"", + "GET operation succeeded for \"" + paths[j] + "\" path on " + + typeNames[i] + " array"); + } catch (JsonException e) { + // There are too many combinations to log them. + } + } + } + } + +} diff --git a/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerTests.java b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerTests.java new file mode 100644 index 00000000..571fe471 --- /dev/null +++ b/tck/tck-tests/src/main/java/jakarta/jsonp/tck/api/pointertests/PointerTests.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package jakarta.jsonp.tck.api.pointertests; + +import jakarta.jsonp.tck.api.common.TestResult; +import jakarta.jsonp.tck.lib.harness.Fault; + +import org.jboss.arquillian.container.test.api.Deployment; +import org.jboss.arquillian.junit.Arquillian; +import org.jboss.shrinkwrap.api.ShrinkWrap; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.junit.runner.RunWith; + +// $Id$ +/** + * {@see RFC 6901}: JavaScript + * Object Notation (JSON) Pointer compatibility tests.
+ * JSON-P API defines {@link jakarta.json.JsonPointer} interface to work with RFC + * 6901 JSON Pointer. + */ +@RunWith(Arquillian.class) +public class PointerTests { + + @Deployment + public static WebArchive createTestArchive() { + return ShrinkWrap.create(WebArchive.class) + .addPackages(true, PointerTests.class.getPackage().getName()); + } + /** + * Test JSON-P API response on pointer resolving.
+ * Checks set of JSON pointers from sample object of RFC 6901. + * {@see RFC 6901: 4. + * Evaluation} and + * {@see RFC 6901: 5. + * JSON String Representation}. + * + * @throws Fault + * when this test failed. + * + * @testName: jsonPointerResolveTest + * @assertion_ids: JSONP:JAVADOC:643; JSONP:JAVADOC:582; JSONP:JAVADOC:583; + * JSONP:JAVADOC:584; JSONP:JAVADOC:661; JSONP:JAVADOC:662; + * JSONP:JAVADOC:663; + * @test_Strategy: Test API response on various JSON pointer values. + */ + @Test + public void jsonPointerResolveTest() throws Fault { + PointerResolve resolveTest = new PointerResolve(); + final TestResult result = resolveTest.test(); + result.eval(); + } + + /** + * Test JSON-P API response on + * {@see RFC 6902: + * 4.1. add} operation using RFC 6901 pointer instance.
+ * Checks set of simple JSON values.
+ * + * @throws Fault + * when this test failed. + * + * @testName: jsonPointerAddOperationTest + * @assertion_ids: JSONP:JAVADOC:642; JSONP:JAVADOC:582; JSONP:JAVADOC:583; + * JSONP:JAVADOC:584; JSONP:JAVADOC:661; JSONP:JAVADOC:662; + * JSONP:JAVADOC:663; + * @test_Strategy: Test API response on various JSON pointer values. + */ + @Test + public void jsonPointerAddOperationTest() throws Fault { + PointerAdd addTest = new PointerAdd(); + final TestResult result = addTest.test(); + result.eval(); + } + + /** + * Test JSON-P API response on + * {@see RFC 6902: + * 4.2. remove} operation using RFC 6901 pointer instance.
+ * Checks set of simple JSON values.
+ * + * @throws Fault + * when this test failed. + * + * @testName: jsonPointerRemoveOperationTest + * @assertion_ids: JSONP:JAVADOC:644; JSONP:JAVADOC:582; JSONP:JAVADOC:661; + * @test_Strategy: Test API response on various JSON pointer values. + */ + @Test + public void jsonPointerRemoveOperationTest() throws Fault { + PointerRemove removeTest = new PointerRemove(); + final TestResult result = removeTest.test(); + result.eval(); + } + + /** + * Test JSON-P API response on + * {@see RFC 6902: + * 4.3. replace} operation using RFC 6901 pointer instance.
+ * Checks set of simple JSON values.
+ * + * @throws Fault + * when this test failed. + * + * @testName: jsonPointerReplaceOperationTest + * @assertion_ids: JSONP:JAVADOC:645; JSONP:JAVADOC:582; JSONP:JAVADOC:583; + * JSONP:JAVADOC:584; JSONP:JAVADOC:661; JSONP:JAVADOC:662; + * JSONP:JAVADOC:663; + * @test_Strategy: Test API response on various JSON pointer values. + */ + @Test + public void jsonPointerReplaceOperationTest() throws Fault { + PointerReplace replaceTest = new PointerReplace(); + final TestResult result = replaceTest.test(); + result.eval(); + } + +} diff --git a/tck/tck-tests/src/main/resources/jsonArrayUTF16BE.json b/tck/tck-tests/src/main/resources/jsonArrayUTF16BE.json new file mode 100644 index 00000000..69c0e866 Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonArrayUTF16BE.json differ diff --git a/tck/tck-tests/src/main/resources/jsonArrayUTF8.json b/tck/tck-tests/src/main/resources/jsonArrayUTF8.json new file mode 100644 index 00000000..37368757 --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonArrayUTF8.json @@ -0,0 +1 @@ +["a旨䔬讞斉屗列z"] \ No newline at end of file diff --git a/tck/tck-tests/src/main/resources/jsonArrayWithAllTypesOfData.json b/tck/tck-tests/src/main/resources/jsonArrayWithAllTypesOfData.json new file mode 100644 index 00000000..b7e3a59a --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonArrayWithAllTypesOfData.json @@ -0,0 +1,36 @@ +[ + "", + [], + {}, + "string", + 100, + true, + false, + null, + { + "emptyString" : "", + "emptyArray" : [], + "emptyObject" : {}, + "string" : "string", + "number" : 100, + "true" : true, + "false" : false, + "null" : null, + "object" : { "name" : "value" }, + "array" : [ "one", "two" ] + }, + [ "string", 100, true, false, null, { "name" : "value" }, [ "one", "two" ] ], + 100, + -100, + 9223372036854775807, + -9223372036854775808, + 0.5, + -0.5, + 7e3, + 7e+3, + 9E3, + 9E+3, + 7e-3, + 7E-3, + "!@#$%^&*()_+|~1234567890-=;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" +] diff --git a/tck/tck-tests/src/main/resources/jsonArrayWithAllTypesOfDataUTF16BE.json b/tck/tck-tests/src/main/resources/jsonArrayWithAllTypesOfDataUTF16BE.json new file mode 100644 index 00000000..8263796a Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonArrayWithAllTypesOfDataUTF16BE.json differ diff --git a/tck/tck-tests/src/main/resources/jsonArrayWithEscapeCharsData.json b/tck/tck-tests/src/main/resources/jsonArrayWithEscapeCharsData.json new file mode 100644 index 00000000..4f2084d1 --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonArrayWithEscapeCharsData.json @@ -0,0 +1,3 @@ +[ + "popeye\"\\\/\b\f\n\r\tolive" +] diff --git a/tck/tck-tests/src/main/resources/jsonArrayWithLotsOfNestedArraysData.json b/tck/tck-tests/src/main/resources/jsonArrayWithLotsOfNestedArraysData.json new file mode 100644 index 00000000..9ef74ba2 --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonArrayWithLotsOfNestedArraysData.json @@ -0,0 +1,92 @@ +[ + [ + "name1","value1", + "nested2",[ + "name2","value2", + "nested3",[ + "name3","value3", + "nested4",[ + "name4","value4", + "nested5",[ + "name5","value5", + "nested6",[ + "name6","value6", + "nested7",[ + "name7","value7", + "nested8",[ + "name8","value8", + "nested9",[ + "name9","value9", + "nested10",[ + "name10","value10", + "nested11",[ + "name11","value11", + "nested12",[ + "name12","value12", + "nested13",[ + "name13","value13", + "nested14",[ + "name14","value14", + "nested15",[ + "name15","value15", + "nested16",[ + "name16","value16", + "nested17",[ + "name17","value17", + "nested18",[ + "name18","value18", + "nested19",[ + "name19","value19", + "nested20",[ + "name20","value20", + "nested21",[ + "name21","value21", + "nested22",[ + "name22","value22", + "nested23",[ + "name23","value23", + "nested24",[ + "name24","value24", + "nested25",[ + "name25","value25", + "nested26",[ + "name26","value26", + "nested27",[ + "name27","value27", + "nested28",[ + "name28","value28", + "nested29",[ + "name29","value29", + "nested30",[ + "name30","value30" + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] + ] +] diff --git a/tck/tck-tests/src/main/resources/jsonArrayWithLotsOfNestedObjectsData.json b/tck/tck-tests/src/main/resources/jsonArrayWithLotsOfNestedObjectsData.json new file mode 100644 index 00000000..f97781f9 --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonArrayWithLotsOfNestedObjectsData.json @@ -0,0 +1,92 @@ +[ + { + "name1" : "value1", + "nested2" : { + "name2" : "value2", + "nested3" : { + "name3" : "value3", + "nested4" : { + "name4" : "value4", + "nested5" : { + "name5" : "value5", + "nested6" : { + "name6" : "value6", + "nested7" : { + "name7" : "value7", + "nested8" : { + "name8" : "value8", + "nested9" : { + "name9" : "value9", + "nested10" : { + "name10" : "value10", + "nested11" : { + "name11" : "value11", + "nested12" : { + "name12" : "value12", + "nested13" : { + "name13" : "value13", + "nested14" : { + "name14" : "value14", + "nested15" : { + "name15" : "value15", + "nested16" : { + "name16" : "value16", + "nested17" : { + "name17" : "value17", + "nested18" : { + "name18" : "value18", + "nested19" : { + "name19" : "value19", + "nested20" : { + "name20" : "value20", + "nested21" : { + "name21" : "value21", + "nested22" : { + "name22" : "value22", + "nested23" : { + "name23" : "value23", + "nested24" : { + "name24" : "value24", + "nested25" : { + "name25" : "value25", + "nested26" : { + "name26" : "value26", + "nested27" : { + "name27" : "value27", + "nested28" : { + "name28" : "value28", + "nested29" : { + "name29" : "value29", + "nested30" : { + "name30" : "value30" + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } +] diff --git a/tck/tck-tests/src/main/resources/jsonHelloWorld.json b/tck/tck-tests/src/main/resources/jsonHelloWorld.json new file mode 100644 index 00000000..9049ffdc --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonHelloWorld.json @@ -0,0 +1,4 @@ +{ + "greetingObj":{"hello":"world"}, + "greetingArr":["hello","world"] +} diff --git a/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16.json b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16.json new file mode 100644 index 00000000..fe2f5399 Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16.json differ diff --git a/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16BE.json b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16BE.json new file mode 100644 index 00000000..d1ddcf5b Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16BE.json differ diff --git a/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16LE.json b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16LE.json new file mode 100644 index 00000000..c48ec6f1 Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF16LE.json differ diff --git a/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF32BE.json b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF32BE.json new file mode 100644 index 00000000..cc6e10ec Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF32BE.json differ diff --git a/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF32LE.json b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF32LE.json new file mode 100644 index 00000000..92c853cf Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF32LE.json differ diff --git a/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF8.json b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF8.json new file mode 100644 index 00000000..ef3478f7 --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonObjectEncodingUTF8.json @@ -0,0 +1 @@ +{"stringName":"stringValue","objectName":{"foo":"bar"},"arrayName":[1,2,3]} diff --git a/tck/tck-tests/src/main/resources/jsonObjectUTF16LE.json b/tck/tck-tests/src/main/resources/jsonObjectUTF16LE.json new file mode 100644 index 00000000..9fb29a82 Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonObjectUTF16LE.json differ diff --git a/tck/tck-tests/src/main/resources/jsonObjectUTF8.json b/tck/tck-tests/src/main/resources/jsonObjectUTF8.json new file mode 100644 index 00000000..e40bd762 --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonObjectUTF8.json @@ -0,0 +1 @@ +{"unicodeChars":"a旨䔬讞斉屗列z"} \ No newline at end of file diff --git a/tck/tck-tests/src/main/resources/jsonObjectUnknownEncoding.json b/tck/tck-tests/src/main/resources/jsonObjectUnknownEncoding.json new file mode 100644 index 00000000..f76dd238 Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonObjectUnknownEncoding.json differ diff --git a/tck/tck-tests/src/main/resources/jsonObjectWithAllTypesOfData.json b/tck/tck-tests/src/main/resources/jsonObjectWithAllTypesOfData.json new file mode 100644 index 00000000..1e924775 --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonObjectWithAllTypesOfData.json @@ -0,0 +1,36 @@ +{ + "emptyString" : "", + "emptyArray" : [], + "emptyObject" : {}, + "string" : "string", + "number" : 100, + "true" : true, + "false" : false, + "null" : null, + "object" : { + "emptyString" : "", + "emptyArray" : [], + "emptyObject" : {}, + "string" : "string", + "number" : 100, + "true" : true, + "false" : false, + "null" : null, + "object" : { "name" : "value" }, + "array" : [ "one", "two" ] + }, + "array" : [ "string", 100, true, false, null, { "name" : "value" }, [ "one", "two" ] ], + "intPositive" : 100, + "intNegative" : -100, + "longMax" : 9223372036854775807, + "longMin" : -9223372036854775808, + "fracPositive" : 0.5, + "fracNegative" : -0.5, + "expPositive1" : 7e3, + "expPositive2" : 7e+3, + "expPositive3" : 9E3, + "expPositive4" : 9E+3, + "expNegative1" : 7e-3, + "expNegative2" : 7E-3, + "asciiChars" : "!@#$%^&*()_+|~1234567890-=;',./<>? qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM" +} diff --git a/tck/tck-tests/src/main/resources/jsonObjectWithAllTypesOfDataUTF16LE.json b/tck/tck-tests/src/main/resources/jsonObjectWithAllTypesOfDataUTF16LE.json new file mode 100644 index 00000000..a2c1b53a Binary files /dev/null and b/tck/tck-tests/src/main/resources/jsonObjectWithAllTypesOfDataUTF16LE.json differ diff --git a/tck/tck-tests/src/main/resources/jsonObjectWithEscapeCharsData.json b/tck/tck-tests/src/main/resources/jsonObjectWithEscapeCharsData.json new file mode 100644 index 00000000..b043d7b0 --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonObjectWithEscapeCharsData.json @@ -0,0 +1,3 @@ +{ + "escapeChars" : "popeye\"\\\/\b\f\n\r\tolive" +} diff --git a/tck/tck-tests/src/main/resources/jsonObjectWithLotsOfNestedObjectsData.json b/tck/tck-tests/src/main/resources/jsonObjectWithLotsOfNestedObjectsData.json new file mode 100644 index 00000000..3ac34d63 --- /dev/null +++ b/tck/tck-tests/src/main/resources/jsonObjectWithLotsOfNestedObjectsData.json @@ -0,0 +1,92 @@ +{ + "nested1" : { + "name1" : "value1", + "nested2" : { + "name2" : "value2", + "nested3" : { + "name3" : "value3", + "nested4" : { + "name4" : "value4", + "nested5" : { + "name5" : "value5", + "nested6" : { + "name6" : "value6", + "nested7" : { + "name7" : "value7", + "nested8" : { + "name8" : "value8", + "nested9" : { + "name9" : "value9", + "nested10" : { + "name10" : "value10", + "nested11" : { + "name11" : "value11", + "nested12" : { + "name12" : "value12", + "nested13" : { + "name13" : "value13", + "nested14" : { + "name14" : "value14", + "nested15" : { + "name15" : "value15", + "nested16" : { + "name16" : "value16", + "nested17" : { + "name17" : "value17", + "nested18" : { + "name18" : "value18", + "nested19" : { + "name19" : "value19", + "nested20" : { + "name20" : "value20", + "nested21" : { + "name21" : "value21", + "nested22" : { + "name22" : "value22", + "nested23" : { + "name23" : "value23", + "nested24" : { + "name24" : "value24", + "nested25" : { + "name25" : "value25", + "nested26" : { + "name26" : "value26", + "nested27" : { + "name27" : "value27", + "nested28" : { + "name28" : "value28", + "nested29" : { + "name29" : "value29", + "nested30" : { + "name30" : "value30" + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } +}