This module is deprecated
diff --git a/.asf.yaml b/.asf.yaml
new file mode 100644
index 0000000..6d19048
--- /dev/null
+++ b/.asf.yaml
@@ -0,0 +1,7 @@
+github:
+ description: "Apache Sling Commons JSON (deprecated)"
+ homepage: "https://sling.apache.org/"
+ labels:
+ - java
+ - sling
+ - deprecated
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5b783ed
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,17 @@
+/target
+.idea
+.classpath
+.metadata
+.project
+.settings
+.externalToolBuilders
+maven-eclipse.xml
+*.swp
+*.iml
+*.ipr
+*.iws
+*.bak
+.vlt
+.DS_Store
+jcr.log
+atlassian-ide-plugin.xml
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..a95affe
--- /dev/null
+++ b/README.md
@@ -0,0 +1,9 @@
+[](https://sling.apache.org)
+
+# Apache Sling Commons JSON (deprecated)
+
+[](https://www.apache.org/licenses/LICENSE-2.0)
+
+This module is deprecated. For reference or potential bugfix releases use the [maintenance](https://github.com/apache/sling-org-apache-sling-commons-json/tree/maintenance) branch, which contains this module's code as it was just before deprecating it.
+
+It is recommended to replace it uses with the `jakarta.json` library.
diff --git a/README.txt b/README.txt
deleted file mode 100644
index 42a62cc..0000000
--- a/README.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-Apache Sling JSON Library
-
-The Sling JSON library provides json support.
-
-
-Getting Started
-===============
-
-This component uses a Maven 2 (http://maven.apache.org/) build
-environment. It requires a Java 5 JDK (or higher) and Maven (http://maven.apache.org/)
-2.0.7 or later. We recommend to use the latest Maven version.
-
-If you have Maven 2 installed, you can compile and
-package the jar using the following command:
-
- mvn package
-
-See the Maven 2 documentation for other build features.
-
-The latest source code for this component is available in the
-Subversion (http://subversion.tigris.org/) source repository of
-the Apache Software Foundation. If you have Subversion installed,
-you can checkout the latest source using the following command:
-
- svn checkout http://svn.apache.org/repos/asf/sling/trunk/commons/json
-
-See the Subversion documentation for other source control features.
diff --git a/src/main/java/org/apache/sling/commons/json/JSONArray.java b/src/main/java/org/apache/sling/commons/json/JSONArray.java
deleted file mode 100644
index dd0a6fc..0000000
--- a/src/main/java/org/apache/sling/commons/json/JSONArray.java
+++ /dev/null
@@ -1,813 +0,0 @@
-package org.apache.sling.commons.json;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Map;
-
-import org.apache.sling.commons.json.io.JSONRenderer;
-
-/**
- * A JSONArray is an ordered sequence of values. Its external text form is a
- * string wrapped in square brackets with commas separating the values. The
- * internal form is an object having <code>get</code> and <code>opt</code>
- * methods for accessing the values by index, and <code>put</code> methods for
- * adding or replacing values. The values can be any of these types:
- * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
- * <code>Number</code>, <code>String</code>, or the
- * <code>JSONObject.NULL object</code>.
- * <p>
- * The constructor can convert a JSON text into a Java object. The
- * <code>toString</code> method converts to JSON text.
- * <p>
- * A <code>get</code> method returns a value if one can be found, and throws an
- * exception if one cannot be found. An <code>opt</code> method returns a
- * default value instead of throwing an exception, and so is useful for
- * obtaining optional values.
- * <p>
- * The generic <code>get()</code> and <code>opt()</code> methods return an
- * object which you can cast or query for type. There are also typed
- * <code>get</code> and <code>opt</code> methods that do type checking and type
- * coersion for you.
- * <p>
- * The texts produced by the <code>toString</code> methods strictly conform to
- * JSON syntax rules. The constructors are more forgiving in the texts they will
- * accept:
- * <ul>
- * <li>An extra <code>,</code> <small>(comma)</small> may appear just
- * before the closing bracket.</li>
- * <li>The <code>null</code> value will be inserted when there
- * is <code>,</code> <small>(comma)</small> elision.</li>
- * <li>Strings may be quoted with <code>'</code> <small>(single
- * quote)</small>.</li>
- * <li>Strings do not need to be quoted at all if they do not begin with a quote
- * or single quote, and if they do not contain leading or trailing spaces,
- * and if they do not contain any of these characters:
- * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
- * and if they are not the reserved words <code>true</code>,
- * <code>false</code>, or <code>null</code>.</li>
- * <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as
- * well as by <code>,</code> <small>(comma)</small>.</li>
- * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or
- * <code>0x-</code> <small>(hex)</small> prefix.</li>
- * <li>Comments written in the slashshlash, slashstar, and hash conventions
- * will be ignored.</li>
- * </ul>
-
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class JSONArray {
-
- /** Default renderer */
- private static final JSONRenderer renderer = new JSONRenderer();
-
- /**
- * The arrayList where the JSONArray's properties are kept.
- */
- private ArrayList<Object> myArrayList;
-
-
- /**
- * Construct an empty JSONArray.
- */
- public JSONArray() {
- this.myArrayList = new ArrayList<Object>();
- }
-
- /**
- * Construct a JSONArray from a JSONTokener.
- * @param x A JSONTokener
- * @throws JSONException If there is a syntax error.
- */
- public JSONArray(JSONTokener x) throws JSONException {
- this();
- if (x.nextClean() != '[') {
- throw x.syntaxError("A JSONArray text must start with '['");
- }
- if (x.nextClean() == ']') {
- return;
- }
- x.back();
- for (;;) {
- if (x.nextClean() == ',') {
- x.back();
- this.myArrayList.add(null);
- } else {
- x.back();
- this.myArrayList.add(x.nextValue());
- }
- switch (x.nextClean()) {
- case ';':
- case ',':
- if (x.nextClean() == ']') {
- return;
- }
- x.back();
- break;
- case ']':
- return;
- default:
- throw x.syntaxError("Expected a ',' or ']'");
- }
- }
- }
-
-
- /**
- * Construct a JSONArray from a source sJSON text.
- * @param string A string that begins with
- * <code>[</code> <small>(left bracket)</small>
- * and ends with <code>]</code> <small>(right bracket)</small>.
- * @throws JSONException If there is a syntax error.
- */
- public JSONArray(String string) throws JSONException {
- this(new JSONTokener(string));
- }
-
-
- /**
- * Construct a JSONArray from a Collection.
- * @param collection A Collection.
- */
- public JSONArray(Collection<?> collection) {
- this.myArrayList = (collection == null) ?
- new ArrayList<Object>() :
- new ArrayList<Object>(collection);
- }
-
-
- /**
- * Get the object value associated with an index.
- * @param index
- * The index must be between 0 and length() - 1.
- * @return An object value.
- * @throws JSONException If there is no value for the index.
- */
- public Object get(int index) throws JSONException {
- Object o = opt(index);
- if (o == null) {
- throw new JSONException("JSONArray[" + index + "] not found.");
- }
- return o;
- }
-
-
- /**
- * Get the boolean value associated with an index.
- * The string values "true" and "false" are converted to boolean.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The truth.
- * @throws JSONException If there is no value for the index or if the
- * value is not convertable to boolean.
- */
- public boolean getBoolean(int index) throws JSONException {
- Object o = get(index);
- if (o.equals(Boolean.FALSE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("false"))) {
- return false;
- } else if (o.equals(Boolean.TRUE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("true"))) {
- return true;
- }
- throw new JSONException("JSONArray[" + index + "] is not a Boolean.");
- }
-
-
- /**
- * Get the double value associated with an index.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- * @throws JSONException If the key is not found or if the value cannot
- * be converted to a number.
- */
- public double getDouble(int index) throws JSONException {
- Object o = get(index);
- try {
- return o instanceof Number ?
- ((Number)o).doubleValue() :
- Double.valueOf((String)o).doubleValue();
- } catch (Exception e) {
- throw new JSONException("JSONArray[" + index +
- "] is not a number.");
- }
- }
-
-
- /**
- * Get the int value associated with an index.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- * @throws JSONException If the key is not found or if the value cannot
- * be converted to a number.
- * if the value cannot be converted to a number.
- */
- public int getInt(int index) throws JSONException {
- Object o = get(index);
- return o instanceof Number ?
- ((Number)o).intValue() : (int)getDouble(index);
- }
-
-
- /**
- * Get the JSONArray associated with an index.
- * @param index The index must be between 0 and length() - 1.
- * @return A JSONArray value.
- * @throws JSONException If there is no value for the index. or if the
- * value is not a JSONArray
- */
- public JSONArray getJSONArray(int index) throws JSONException {
- Object o = get(index);
- if (o instanceof JSONArray) {
- return (JSONArray) o;
- } else if (o instanceof String) {
- JSONTokener tokener = new JSONTokener((String) o);
- try {
- return new JSONArray(tokener);
- } catch (JSONException ignore) {
- // will throw the appropriate exception below
- }
- }
-
- throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
- }
-
-
- /**
- * Get the JSONObject associated with an index.
- * @param index subscript
- * @return A JSONObject value.
- * @throws JSONException If there is no value for the index or if the
- * value is not a JSONObject
- */
- public JSONObject getJSONObject(int index) throws JSONException {
- Object o = get(index);
- if (o instanceof JSONObject) {
- return (JSONObject) o;
- } else if (o instanceof String) {
- JSONTokener tokener = new JSONTokener((String) o);
- try {
- return new JSONObject(tokener);
- } catch (JSONException ignore) {
- // will throw the appropriate exception below
- }
- }
-
- throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
- }
-
-
- /**
- * Get the long value associated with an index.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- * @throws JSONException If the key is not found or if the value cannot
- * be converted to a number.
- */
- public long getLong(int index) throws JSONException {
- Object o = get(index);
- return o instanceof Number ?
- ((Number)o).longValue() : (long)getDouble(index);
- }
-
-
- /**
- * Get the string associated with an index.
- * @param index The index must be between 0 and length() - 1.
- * @return A string value.
- * @throws JSONException If there is no value for the index.
- */
- public String getString(int index) throws JSONException {
- return get(index).toString();
- }
-
-
- /**
- * Determine if the value is null.
- * @param index The index must be between 0 and length() - 1.
- * @return true if the value at the index is null, or if there is no value.
- */
- public boolean isNull(int index) {
- return JSONObject.NULL.equals(opt(index));
- }
-
-
- /**
- * Make a string from the contents of this JSONArray
- * using {@link JSONRenderer#join}
- */
- public String join(String separator) throws JSONException {
- return renderer.join(this, separator);
- }
-
-
- /**
- * Get the number of elements in the JSONArray, included nulls.
- *
- * @return The length (or size).
- */
- public int length() {
- return this.myArrayList.size();
- }
-
-
- /**
- * Get the optional object value associated with an index.
- * @param index The index must be between 0 and length() - 1.
- * @return An object value, or null if there is no
- * object at that index.
- */
- public Object opt(int index) {
- return (index < 0 || index >= length()) ?
- null : this.myArrayList.get(index);
- }
-
-
- /**
- * Get the optional boolean value associated with an index.
- * It returns false if there is no value at that index,
- * or if the value is not Boolean.TRUE or the String "true".
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The truth.
- */
- public boolean optBoolean(int index) {
- return optBoolean(index, false);
- }
-
-
- /**
- * Get the optional boolean value associated with an index.
- * It returns the defaultValue if there is no value at that index or if
- * it is not a Boolean or the String "true" or "false" (case insensitive).
- *
- * @param index The index must be between 0 and length() - 1.
- * @param defaultValue A boolean default.
- * @return The truth.
- */
- public boolean optBoolean(int index, boolean defaultValue) {
- try {
- return getBoolean(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
-
- /**
- * Get the optional double value associated with an index.
- * NaN is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- */
- public double optDouble(int index) {
- return optDouble(index, Double.NaN);
- }
-
-
- /**
- * Get the optional double value associated with an index.
- * The defaultValue is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- *
- * @param index subscript
- * @param defaultValue The default value.
- * @return The value.
- */
- public double optDouble(int index, double defaultValue) {
- try {
- return getDouble(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
-
- /**
- * Get the optional int value associated with an index.
- * Zero is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- */
- public int optInt(int index) {
- return optInt(index, 0);
- }
-
-
- /**
- * Get the optional int value associated with an index.
- * The defaultValue is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- * @param index The index must be between 0 and length() - 1.
- * @param defaultValue The default value.
- * @return The value.
- */
- public int optInt(int index, int defaultValue) {
- try {
- return getInt(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
-
- /**
- * Get the optional JSONArray associated with an index.
- * @param index subscript
- * @return A JSONArray value, or null if the index has no value,
- * or if the value is not a JSONArray.
- */
- public JSONArray optJSONArray(int index) {
- try {
- return getJSONArray(index);
- } catch (Exception e) {
- return null;
- }
- }
-
-
- /**
- * Get the optional JSONObject associated with an index.
- * Null is returned if the key is not found, or null if the index has
- * no value, or if the value is not a JSONObject.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return A JSONObject value.
- */
- public JSONObject optJSONObject(int index) {
- try {
- return getJSONObject(index);
- } catch (Exception e) {
- return null;
- }
- }
-
-
- /**
- * Get the optional long value associated with an index.
- * Zero is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- */
- public long optLong(int index) {
- return optLong(index, 0);
- }
-
-
- /**
- * Get the optional long value associated with an index.
- * The defaultValue is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- * @param index The index must be between 0 and length() - 1.
- * @param defaultValue The default value.
- * @return The value.
- */
- public long optLong(int index, long defaultValue) {
- try {
- return getLong(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
-
- /**
- * Get the optional string value associated with an index. It returns an
- * empty string if there is no value at that index. If the value
- * is not a string and is not null, then it is coverted to a string.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return A String value.
- */
- public String optString(int index) {
- return optString(index, "");
- }
-
-
- /**
- * Get the optional string associated with an index.
- * The defaultValue is returned if the key is not found.
- *
- * @param index The index must be between 0 and length() - 1.
- * @param defaultValue The default value.
- * @return A String value.
- */
- public String optString(int index, String defaultValue) {
- Object o = opt(index);
- return o != null ? o.toString() : defaultValue;
- }
-
-
- /**
- * Append a boolean value. This increases the array's length by one.
- *
- * @param value A boolean value.
- * @return this.
- */
- public JSONArray put(boolean value) {
- put(value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
-
-
- /**
- * Put a value in the JSONArray, where the value will be a
- * JSONArray which is produced from a Collection.
- * @param value A Collection value.
- * @return this.
- */
- public JSONArray put(Collection<?> value) {
- put(new JSONArray(value));
- return this;
- }
-
-
- /**
- * Append a double value. This increases the array's length by one.
- *
- * @param value A double value.
- * @throws JSONException if the value is not finite.
- * @return this.
- */
- public JSONArray put(double value) throws JSONException {
- Double d = new Double(value);
- JSONObject.testValidity(d);
- put(d);
- return this;
- }
-
-
- /**
- * Append an int value. This increases the array's length by one.
- *
- * @param value An int value.
- * @return this.
- */
- public JSONArray put(int value) {
- put(new Integer(value));
- return this;
- }
-
-
- /**
- * Append an long value. This increases the array's length by one.
- *
- * @param value A long value.
- * @return this.
- */
- public JSONArray put(long value) {
- put(new Long(value));
- return this;
- }
-
-
- /**
- * Put a value in the JSONArray, where the value will be a
- * JSONObject which is produced from a Map.
- * @param value A Map value.
- * @return this.
- */
- public JSONArray put(Map<String, ?> value) {
- put(new JSONObject(value));
- return this;
- }
-
-
- /**
- * Append an object value. This increases the array's length by one.
- * @param value An object value. The value should be a
- * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
- * JSONObject.NULL object.
- * @return this.
- */
- public JSONArray put(Object value) {
- this.myArrayList.add(value);
- return this;
- }
-
-
- /**
- * Put or replace a boolean value in the JSONArray. If the index is greater
- * than the length of the JSONArray, then null elements will be added as
- * necessary to pad it out.
- * @param index The subscript.
- * @param value A boolean value.
- * @return this.
- * @throws JSONException If the index is negative.
- */
- public JSONArray put(int index, boolean value) throws JSONException {
- put(index, value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
-
-
- /**
- * Put a value in the JSONArray, where the value will be a
- * JSONArray which is produced from a Collection.
- * @param index The subscript.
- * @param value A Collection value.
- * @return this.
- * @throws JSONException If the index is negative or if the value is
- * not finite.
- */
- public JSONArray put(int index, Collection<?> value) throws JSONException {
- put(index, new JSONArray(value));
- return this;
- }
-
-
- /**
- * Put or replace a double value. If the index is greater than the length of
- * the JSONArray, then null elements will be added as necessary to pad
- * it out.
- * @param index The subscript.
- * @param value A double value.
- * @return this.
- * @throws JSONException If the index is negative or if the value is
- * not finite.
- */
- public JSONArray put(int index, double value) throws JSONException {
- put(index, new Double(value));
- return this;
- }
-
-
- /**
- * Put or replace an int value. If the index is greater than the length of
- * the JSONArray, then null elements will be added as necessary to pad
- * it out.
- * @param index The subscript.
- * @param value An int value.
- * @return this.
- * @throws JSONException If the index is negative.
- */
- public JSONArray put(int index, int value) throws JSONException {
- put(index, new Integer(value));
- return this;
- }
-
-
- /**
- * Put or replace a long value. If the index is greater than the length of
- * the JSONArray, then null elements will be added as necessary to pad
- * it out.
- * @param index The subscript.
- * @param value A long value.
- * @return this.
- * @throws JSONException If the index is negative.
- */
- public JSONArray put(int index, long value) throws JSONException {
- put(index, new Long(value));
- return this;
- }
-
-
- /**
- * Put a value in the JSONArray, where the value will be a
- * JSONObject which is produced from a Map.
- * @param index The subscript.
- * @param value The Map value.
- * @return this.
- * @throws JSONException If the index is negative or if the the value is
- * an invalid number.
- */
- public JSONArray put(int index, Map<String, ?> value) throws JSONException {
- put(index, new JSONObject(value));
- return this;
- }
-
-
- /**
- * Put or replace an object value in the JSONArray. If the index is greater
- * than the length of the JSONArray, then null elements will be added as
- * necessary to pad it out.
- * @param index The subscript.
- * @param value The value to put into the array. The value should be a
- * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
- * JSONObject.NULL object.
- * @return this.
- * @throws JSONException If the index is negative or if the the value is
- * an invalid number.
- */
- public JSONArray put(int index, Object value) throws JSONException {
- JSONObject.testValidity(value);
- if (index < 0) {
- throw new JSONException("JSONArray[" + index + "] not found.");
- }
- if (index < length()) {
- this.myArrayList.set(index, value);
- } else {
- while (index != length()) {
- put(JSONObject.NULL);
- }
- put(value);
- }
- return this;
- }
-
-
- /**
- * Produce a JSONObject by combining a JSONArray of names with the values
- * of this JSONArray.
- * @param names A JSONArray containing a list of key strings. These will be
- * paired with the values.
- * @return A JSONObject, or null if there are no names or if this JSONArray
- * has no values.
- * @throws JSONException If any of the names are null.
- */
- public JSONObject toJSONObject(JSONArray names) throws JSONException {
- if (names == null || names.length() == 0 || length() == 0) {
- return null;
- }
- JSONObject jo = new JSONObject();
- for (int i = 0; i < names.length(); i += 1) {
- jo.put(names.getString(i), this.opt(i));
- }
- return jo;
- }
-
-
- /**
- * Make a JSON text of this JSONArray using
- * {@link JSONRenderer#toString(JSONArray)}
- */
- public String toString() {
- return renderer.toString(this);
- }
-
- /**
- * Make a prettyprinted JSON text of this JSONArray.
- * Warning: This method assumes that the data structure is acyclical.
- * @param indentFactor The number of spaces to add to each level of
- * indentation.
- * @return a printable, displayable, transmittable
- * representation of the object, beginning
- * with <code>[</code> <small>(left bracket)</small> and ending
- * with <code>]</code> <small>(right bracket)</small>.
- * @throws JSONException
- */
- public String toString(int indentFactor) throws JSONException {
- return toString(indentFactor, 0);
- }
-
-
- /**
- * Make a prettyprinted JSON text of this JSONArray.
- * Warning: This method assumes that the data structure is acyclical.
- * @param indentFactor The number of spaces to add to each level of
- * indentation.
- * @param indent The indention of the top level.
- * @return a printable, displayable, transmittable
- * representation of the array.
- * @throws JSONException
- */
- String toString(int indentFactor, int indent) throws JSONException {
- return renderer.prettyPrint(this,
- renderer.options().withIndent(indentFactor).withInitialIndent(indent));
- }
-
- /**
- * Write the contents of the JSONObject as JSON text to a writer
- * using {@link JSONRenderer#write(Writer, JSONArray)}
- */
- public Writer write(Writer writer) throws JSONException {
- return renderer.write(writer, this);
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/apache/sling/commons/json/JSONException.java b/src/main/java/org/apache/sling/commons/json/JSONException.java
deleted file mode 100644
index 1d473a5..0000000
--- a/src/main/java/org/apache/sling/commons/json/JSONException.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package org.apache.sling.commons.json;
-
-/**
- * The JSONException is thrown by the JSON.org classes then things are amiss.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class JSONException extends Exception {
- private static final long serialVersionUID = 8262447656274268887L;
-
- /**
- * Constructs a JSONException with an explanatory message.
- * @param message Detail about the reason for the exception.
- */
- public JSONException(String message) {
- super(message);
- }
-
- public JSONException(Throwable t) {
- super(t);
- }
-
- public JSONException(String message, Throwable t) {
- super(message, t);
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/JSONObject.java b/src/main/java/org/apache/sling/commons/json/JSONObject.java
deleted file mode 100644
index 72bc3a2..0000000
--- a/src/main/java/org/apache/sling/commons/json/JSONObject.java
+++ /dev/null
@@ -1,1006 +0,0 @@
-package org.apache.sling.commons.json;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-import java.io.Writer;
-import java.lang.reflect.Field;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import org.apache.sling.commons.json.io.JSONRenderer;
-
-/**
- * A JSONObject is an unordered collection of name/value pairs. Its
- * external form is a string wrapped in curly braces with colons between the
- * names and values, and commas between the values and names. The internal form
- * is an object having <code>get</code> and <code>opt</code> methods for
- * accessing the values by name, and <code>put</code> methods for adding or
- * replacing values by name. The values can be any of these types:
- * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
- * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code>
- * object. A JSONObject constructor can be used to convert an external form
- * JSON text into an internal form whose values can be retrieved with the
- * <code>get</code> and <code>opt</code> methods, or to convert values into a
- * JSON text using the <code>put</code> and <code>toString</code> methods.
- * A <code>get</code> method returns a value if one can be found, and throws an
- * exception if one cannot be found. An <code>opt</code> method returns a
- * default value instead of throwing an exception, and so is useful for
- * obtaining optional values.
- * <p>
- * The generic <code>get()</code> and <code>opt()</code> methods return an
- * object, which you can cast or query for type. There are also typed
- * <code>get</code> and <code>opt</code> methods that do type checking and type
- * coersion for you.
- * <p>
- * The <code>put</code> methods adds values to an object. For example, <pre>
- * myString = new JSONObject().put("JSON", "Hello, World!").toString();</pre>
- * produces the string <code>{"JSON": "Hello, World"}</code>.
- * <p>
- * The texts produced by the <code>toString</code> methods strictly conform to
- * the JSON sysntax rules.
- * The constructors are more forgiving in the texts they will accept:
- * <ul>
- * <li>An extra <code>,</code> <small>(comma)</small> may appear just
- * before the closing brace.</li>
- * <li>Strings may be quoted with <code>'</code> <small>(single
- * quote)</small>.</li>
- * <li>Strings do not need to be quoted at all if they do not begin with a quote
- * or single quote, and if they do not contain leading or trailing spaces,
- * and if they do not contain any of these characters:
- * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
- * and if they are not the reserved words <code>true</code>,
- * <code>false</code>, or <code>null</code>.</li>
- * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as
- * by <code>:</code>.</li>
- * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as
- * well as by <code>,</code> <small>(comma)</small>.</li>
- * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or
- * <code>0x-</code> <small>(hex)</small> prefix.</li>
- * <li>Comments written in the slashshlash, slashstar, and hash conventions
- * will be ignored.</li>
- * </ul>
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class JSONObject {
-
- /** A renderer with default settings, used to avoid having to create
- * one for simple rendering operations
- */
- private static final JSONRenderer renderer = new JSONRenderer();
-
- /**
- * JSONObject.NULL is equivalent to the value that JavaScript calls null,
- * whilst Java's null is equivalent to the value that JavaScript calls
- * undefined.
- */
- private static final class Null {
-
- /**
- * There is only intended to be a single instance of the NULL object,
- * so the clone method returns itself.
- * @return NULL.
- */
- protected final Object clone() {
- return this;
- }
-
-
- /**
- * A Null object is equal to the null value and to itself.
- * @param object An object to test for nullness.
- * @return true if the object parameter is the JSONObject.NULL object
- * or null.
- */
- public boolean equals(Object object) {
- return object == null || object == this;
- }
-
-
- /**
- * Get the "null" string value.
- * @return The string "null".
- */
- public String toString() {
- return "null";
- }
- }
-
-
- /**
- * The hash map where the JSONObject's properties are kept.
- */
- private Map<String, Object> myHashMap;
-
-
- /**
- * It is sometimes more convenient and less ambiguous to have a
- * <code>NULL</code> object than to use Java's <code>null</code> value.
- * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.
- * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
- */
- public static final Object NULL = new Null();
-
-
- /**
- * Construct an empty JSONObject.
- */
- public JSONObject() {
- this.myHashMap = new LinkedHashMap<String, Object>();
- }
-
-
- /**
- * Construct a JSONObject from a subset of another JSONObject.
- * An array of strings is used to identify the keys that should be copied.
- * Missing keys are ignored.
- * @param jo A JSONObject.
- * @param sa An array of strings.
- * @exception JSONException If a value is a non-finite number.
- */
- public JSONObject(JSONObject jo, String[] sa) throws JSONException {
- this(); // basic setup
-
- for (int i = 0; i < sa.length; i += 1) {
- putOpt(sa[i], jo.opt(sa[i]));
- }
- }
-
-
- /**
- * Construct a JSONObject from a JSONTokener.
- * @param x A JSONTokener object containing the source string.
- * @throws JSONException If there is a syntax error in the source string.
- */
- public JSONObject(JSONTokener x) throws JSONException {
- this(); // basic setup
-
- char c;
- String key;
-
- if (x.nextClean() != '{') {
- throw x.syntaxError("A JSONObject text must begin with '{'");
- }
- for (;;) {
- c = x.nextClean();
- switch (c) {
- case 0:
- throw x.syntaxError("A JSONObject text must end with '}'");
- case '}':
- return;
- default:
- x.back();
- key = x.nextValue().toString();
- }
-
- /*
- * The key is followed by ':'. We will also tolerate '=' or '=>'.
- */
-
- c = x.nextClean();
- if (c == '=') {
- if (x.next() != '>') {
- x.back();
- }
- } else if (c != ':') {
- throw x.syntaxError("Expected a ':' after a key");
- }
- put(key, x.nextValue());
-
- /*
- * Pairs are separated by ','. We will also tolerate ';'.
- */
-
- switch (x.nextClean()) {
- case ';':
- case ',':
- if (x.nextClean() == '}') {
- return;
- }
- x.back();
- break;
- case '}':
- return;
- default:
- throw x.syntaxError("Expected a ',' or '}'");
- }
- }
- }
-
-
- /**
- * Construct a JSONObject from a Map.
- * @param map A map object that can be used to initialize the contents of
- * the JSONObject.
- */
- public JSONObject(Map<String, ?> map) {
- this.myHashMap = (map == null) ?
- new LinkedHashMap<String, Object>() :
- new LinkedHashMap<String, Object>(map);
- }
-
-
- /**
- * Construct a JSONObject from an Object, using reflection to find the
- * public members. The resulting JSONObject's keys will be the strings
- * from the names array, and the values will be the field values associated
- * with those keys in the object. If a key is not found or not visible,
- * then it will not be copied into the new JSONObject.
- * @param object An object that has fields that should be used to make a
- * JSONObject.
- * @param names An array of strings, the names of the fields to be used
- * from the object.
- */
- public JSONObject(Object object, String names[]) {
- this(); // basic setup
-
- Class<? extends Object> c = object.getClass();
- for (int i = 0; i < names.length; i += 1) {
- try {
- String name = names[i];
- Field field = c.getField(name);
- Object value = field.get(object);
- this.put(name, value);
- } catch (Exception e) {
- // forget about it
- }
- }
- }
-
-
- /**
- * Construct a JSONObject from a string.
- * This is the most commonly used JSONObject constructor.
- * @param string A string beginning
- * with <code>{</code> <small>(left brace)</small> and ending
- * with <code>}</code> <small>(right brace)</small>.
- * @exception JSONException If there is a syntax error in the source string.
- */
- public JSONObject(String string) throws JSONException {
- this(new JSONTokener(string));
- }
-
-
- /**
- * Accumulate values under a key. It is similar to the put method except
- * that if there is already an object stored under the key then a
- * JSONArray is stored under the key to hold all of the accumulated values.
- * If there is already a JSONArray, then the new value is appended to it.
- * In contrast, the put method replaces the previous value.
- * @param key A key string.
- * @param value An object to be accumulated under the key.
- * @return this.
- * @throws JSONException If the value is an invalid number
- * or if the key is null.
- */
- public JSONObject accumulate(String key, Object value)
- throws JSONException {
- testValidity(value);
- Object o = opt(key);
- if (o == null) {
- put(key, value);
- } else if (o instanceof JSONArray) {
- ((JSONArray)o).put(value);
- } else {
- put(key, new JSONArray().put(o).put(value));
- }
- return this;
- }
-
-
- /**
- * Append values to the array under a key. If the key does not exist in the
- * JSONObject, then the key is put in the JSONObject with its value being a
- * JSONArray containing the value parameter. If the key was already
- * associated with a JSONArray, then the value parameter is appended to it.
- * @param key A key string.
- * @param value An object to be accumulated under the key.
- * @return this.
- * @throws JSONException If the key is null or if the current value
- * associated with the key is not a JSONArray.
- */
- public JSONObject append(String key, Object value)
- throws JSONException {
- testValidity(value);
- Object o = opt(key);
- if (o == null) {
- put(key, new JSONArray().put(value));
- } else if (o instanceof JSONArray) {
- put(key, new JSONArray().put(o).put(value));
- } else {
- throw new JSONException("JSONObject[" + key +
- "] is not a JSONArray.");
- }
- return this;
- }
-
-
- /**
- * Produce a string from a double using {@link JSONRenderer#doubleToString}
- */
- static public String doubleToString(double d) {
- return renderer.doubleToString(d);
- }
-
- /**
- * Get the value object associated with a key.
- *
- * @param key A key string.
- * @return The object associated with the key.
- * @throws JSONException if the key is not found.
- */
- public Object get(String key) throws JSONException {
- Object o = opt(key);
- if (o == null) {
- throw new JSONException("JSONObject[" + quote(key) +
- "] not found.");
- }
- return o;
- }
-
-
- /**
- * Get the boolean value associated with a key.
- *
- * @param key A key string.
- * @return The truth.
- * @throws JSONException
- * if the value is not a Boolean or the String "true" or "false".
- */
- public boolean getBoolean(String key) throws JSONException {
- Object o = get(key);
- if (o.equals(Boolean.FALSE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("false"))) {
- return false;
- } else if (o.equals(Boolean.TRUE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("true"))) {
- return true;
- }
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a Boolean.");
- }
-
-
- /**
- * Get the double value associated with a key.
- * @param key A key string.
- * @return The numeric value.
- * @throws JSONException if the key is not found or
- * if the value is not a Number object and cannot be converted to a number.
- */
- public double getDouble(String key) throws JSONException {
- Object o = get(key);
- try {
- return o instanceof Number ?
- ((Number)o).doubleValue() :
- Double.valueOf((String)o).doubleValue();
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a number.");
- }
- }
-
-
- /**
- * Get the int value associated with a key. If the number value is too
- * large for an int, it will be clipped.
- *
- * @param key A key string.
- * @return The integer value.
- * @throws JSONException if the key is not found or if the value cannot
- * be converted to an integer.
- */
- public int getInt(String key) throws JSONException {
- Object o = get(key);
- return o instanceof Number ?
- ((Number)o).intValue() : (int)getDouble(key);
- }
-
-
- /**
- * Get the JSONArray value associated with a key.
- *
- * @param key A key string.
- * @return A JSONArray which is the value.
- * @throws JSONException if the key is not found or
- * if the value is not a JSONArray.
- */
- public JSONArray getJSONArray(String key) throws JSONException {
- Object o = get(key);
- if (o instanceof JSONArray) {
- return (JSONArray)o;
- }
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a JSONArray.");
- }
-
-
- /**
- * Get the JSONObject value associated with a key.
- *
- * @param key A key string.
- * @return A JSONObject which is the value.
- * @throws JSONException if the key is not found or
- * if the value is not a JSONObject.
- */
- public JSONObject getJSONObject(String key) throws JSONException {
- Object o = get(key);
- if (o instanceof JSONObject) {
- return (JSONObject)o;
- }
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a JSONObject.");
- }
-
-
- /**
- * Get the long value associated with a key. If the number value is too
- * long for a long, it will be clipped.
- *
- * @param key A key string.
- * @return The long value.
- * @throws JSONException if the key is not found or if the value cannot
- * be converted to a long.
- */
- public long getLong(String key) throws JSONException {
- Object o = get(key);
- return o instanceof Number ?
- ((Number)o).longValue() :
- Long.valueOf((String)o).longValue();
- }
-
-
- /**
- * Get the string associated with a key.
- *
- * @param key A key string.
- * @return A string which is the value.
- * @throws JSONException if the key is not found.
- */
- public String getString(String key) throws JSONException {
- return get(key).toString();
- }
-
-
- /**
- * Determine if the JSONObject contains a specific key.
- * @param key A key string.
- * @return true if the key exists in the JSONObject.
- */
- public boolean has(String key) {
- return this.myHashMap.containsKey(key);
- }
-
-
- /**
- * Determine if the value associated with the key is null or if there is
- * no value.
- * @param key A key string.
- * @return true if there is no value associated with the key or if
- * the value is the JSONObject.NULL object.
- */
- public boolean isNull(String key) {
- return JSONObject.NULL.equals(opt(key));
- }
-
-
- /**
- * Get an enumeration of the keys of the JSONObject.
- *
- * @return An iterator of the keys.
- */
- public Iterator<String> keys() {
- return this.myHashMap.keySet().iterator();
- }
-
-
- /**
- * Get the number of keys stored in the JSONObject.
- *
- * @return The number of keys in the JSONObject.
- */
- public int length() {
- return this.myHashMap.size();
- }
-
-
- /**
- * Produce a JSONArray containing the names of the elements of this
- * JSONObject.
- * @return A JSONArray containing the key strings, or null if the JSONObject
- * is empty.
- */
- public JSONArray names() {
- JSONArray ja = new JSONArray();
- Iterator<String> keys = keys();
- while (keys.hasNext()) {
- ja.put(keys.next());
- }
- return ja.length() == 0 ? null : ja;
- }
-
- /**
- * Produce a string from a Number.
- * @param n A Number
- * @return A String.
- * @throws JSONException If n is a non-finite number.
- */
- static public String numberToString(Number n) throws JSONException {
- return renderer.numberToString(n);
- }
-
-
- /**
- * Get an optional value associated with a key.
- * @param key A key string.
- * @return An object which is the value, or null if there is no value.
- */
- public Object opt(String key) {
- return key == null ? null : this.myHashMap.get(key);
- }
-
-
- /**
- * Get an optional boolean associated with a key.
- * It returns false if there is no such key, or if the value is not
- * Boolean.TRUE or the String "true".
- *
- * @param key A key string.
- * @return The truth.
- */
- public boolean optBoolean(String key) {
- return optBoolean(key, false);
- }
-
-
- /**
- * Get an optional boolean associated with a key.
- * It returns the defaultValue if there is no such key, or if it is not
- * a Boolean or the String "true" or "false" (case insensitive).
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return The truth.
- */
- public boolean optBoolean(String key, boolean defaultValue) {
- try {
- return getBoolean(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
-
- /**
- * Put a key/value pair in the JSONObject, where the value will be a
- * JSONArray which is produced from a Collection.
- * @param key A key string.
- * @param value A Collection value.
- * @return this.
- * @throws JSONException
- */
- public JSONObject put(String key, Collection<?> value) throws JSONException {
- put(key, new JSONArray(value));
- return this;
- }
-
-
- /**
- * Get an optional double associated with a key,
- * or NaN if there is no such key or if its value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A string which is the key.
- * @return An object which is the value.
- */
- public double optDouble(String key) {
- return optDouble(key, Double.NaN);
- }
-
-
- /**
- * Get an optional double associated with a key, or the
- * defaultValue if there is no such key or if its value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public double optDouble(String key, double defaultValue) {
- try {
- Object o = opt(key);
- return o instanceof Number ? ((Number)o).doubleValue() :
- new Double((String)o).doubleValue();
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
-
- /**
- * Get an optional int value associated with a key,
- * or zero if there is no such key or if the value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @return An object which is the value.
- */
- public int optInt(String key) {
- return optInt(key, 0);
- }
-
-
- /**
- * Get an optional int value associated with a key,
- * or the default if there is no such key or if the value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public int optInt(String key, int defaultValue) {
- try {
- return getInt(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
-
- /**
- * Get an optional JSONArray associated with a key.
- * It returns null if there is no such key, or if its value is not a
- * JSONArray.
- *
- * @param key A key string.
- * @return A JSONArray which is the value.
- */
- public JSONArray optJSONArray(String key) {
- Object o = opt(key);
- return o instanceof JSONArray ? (JSONArray)o : null;
- }
-
-
- /**
- * Get an optional JSONObject associated with a key.
- * It returns null if there is no such key, or if its value is not a
- * JSONObject.
- *
- * @param key A key string.
- * @return A JSONObject which is the value.
- */
- public JSONObject optJSONObject(String key) {
- Object o = opt(key);
- return o instanceof JSONObject ? (JSONObject)o : null;
- }
-
-
- /**
- * Get an optional long value associated with a key,
- * or zero if there is no such key or if the value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @return An object which is the value.
- */
- public long optLong(String key) {
- return optLong(key, 0);
- }
-
-
- /**
- * Get an optional long value associated with a key,
- * or the default if there is no such key or if the value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public long optLong(String key, long defaultValue) {
- try {
- return getLong(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
-
-
- /**
- * Get an optional string associated with a key.
- * It returns an empty string if there is no such key. If the value is not
- * a string and is not null, then it is coverted to a string.
- *
- * @param key A key string.
- * @return A string which is the value.
- */
- public String optString(String key) {
- return optString(key, "");
- }
-
-
- /**
- * Get an optional string associated with a key.
- * It returns the defaultValue if there is no such key.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return A string which is the value.
- */
- public String optString(String key, String defaultValue) {
- Object o = opt(key);
- return o != null ? o.toString() : defaultValue;
- }
-
-
- /**
- * Put a key/boolean pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A boolean which is the value.
- * @return this.
- * @throws JSONException If the key is null.
- */
- public JSONObject put(String key, boolean value) throws JSONException {
- put(key, value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
-
-
- /**
- * Put a key/double pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A double which is the value.
- * @return this.
- * @throws JSONException If the key is null or if the number is invalid.
- */
- public JSONObject put(String key, double value) throws JSONException {
- put(key, new Double(value));
- return this;
- }
-
-
- /**
- * Put a key/int pair in the JSONObject.
- *
- * @param key A key string.
- * @param value An int which is the value.
- * @return this.
- * @throws JSONException If the key is null.
- */
- public JSONObject put(String key, int value) throws JSONException {
- put(key, new Integer(value));
- return this;
- }
-
-
- /**
- * Put a key/long pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A long which is the value.
- * @return this.
- * @throws JSONException If the key is null.
- */
- public JSONObject put(String key, long value) throws JSONException {
- put(key, new Long(value));
- return this;
- }
-
-
- /**
- * Put a key/value pair in the JSONObject, where the value will be a
- * JSONObject which is produced from a Map.
- * @param key A key string.
- * @param value A Map value.
- * @return this.
- * @throws JSONException
- */
- public JSONObject put(String key, Map<String, ?> value) throws JSONException {
- put(key, new JSONObject(value));
- return this;
- }
-
-
- /**
- * Put a key/value pair in the JSONObject. If the value is null,
- * then the key will be removed from the JSONObject if it is present.
- * @param key A key string.
- * @param value An object which is the value. It should be of one of these
- * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
- * or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException If the value is non-finite number
- * or if the key is null.
- */
- public JSONObject put(String key, Object value) throws JSONException {
- if (key == null) {
- throw new JSONException("Null key.");
- }
- if (value != null) {
- testValidity(value);
- this.myHashMap.put(key, value);
- } else {
- remove(key);
- }
- return this;
- }
-
-
- /**
- * Put a key/value pair in the JSONObject, but only if the
- * key and the value are both non-null.
- * @param key A key string.
- * @param value An object which is the value. It should be of one of these
- * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
- * or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException If the value is a non-finite number.
- */
- public JSONObject putOpt(String key, Object value) throws JSONException {
- if (key != null && value != null) {
- put(key, value);
- }
- return this;
- }
-
-
- /**
- * Produce a string in double quotes with backslash sequences in all the
- * right places. A backslash will be inserted within </, allowing JSON
- * text to be delivered in HTML. In JSON text, a string cannot contain a
- * control character or an unescaped quote or backslash.
- * @param string A String
- * @return A String correctly formatted for insertion in a JSON text.
- */
- public static String quote(String string) {
- return renderer.quote(string);
- }
-
- /**
- * Remove a name and its value, if present.
- * @param key The name to be removed.
- * @return The value that was associated with the name,
- * or null if there was no value.
- */
- public Object remove(String key) {
- return this.myHashMap.remove(key);
- }
-
-
- /**
- * Throw an exception if the object is an NaN or infinite number.
- * @param o The object to test.
- * @throws JSONException If o is a non-finite number.
- */
- static void testValidity(Object o) throws JSONException {
- renderer.testNumberValidity(o);
- }
-
- /**
- * Produce a JSONArray containing the values of the members of this
- * JSONObject.
- * @param names A JSONArray containing a list of key strings. This
- * determines the sequence of the values in the result.
- * @return A JSONArray of values.
- * @throws JSONException If any of the values are non-finite numbers.
- */
- public JSONArray toJSONArray(JSONArray names) throws JSONException {
- if (names == null || names.length() == 0) {
- return null;
- }
- JSONArray ja = new JSONArray();
- for (int i = 0; i < names.length(); i += 1) {
- ja.put(this.opt(names.getString(i)));
- }
- return ja;
- }
-
- /**
- * Make a JSON text of this JSONObject using {@link JSONRenderer#toString}
- */
- public String toString() {
- return renderer.toString(this);
- }
-
- /**
- * Make a prettyprinted JSON text of this JSONObject.
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- * @param indentFactor The number of spaces to add to each level of
- * indentation.
- * @return a printable, displayable, portable, transmittable
- * representation of the object, beginning
- * with <code>{</code> <small>(left brace)</small> and ending
- * with <code>}</code> <small>(right brace)</small>.
- * @throws JSONException If the object contains an invalid number.
- */
- public String toString(int indentFactor) throws JSONException {
- return toString(indentFactor, 0);
- }
-
-
- /**
- * Make a prettyprinted JSON text of this JSONObject using
- * {@link JSONRenderer#prettyPrint}
- */
- String toString(int indentFactor, int initialIndent) throws JSONException {
- return renderer.prettyPrint(this,
- renderer.options().withIndent(indentFactor).withInitialIndent(initialIndent));
- }
-
-
- /**
- * Make a JSON text of an Object value. If the object has an
- * value.toJSONString() method, then that method will be used to produce
- * the JSON text. The method is required to produce a strictly
- * conforming text. If the object does not contain a toJSONString
- * method (which is the most common case), then a text will be
- * produced by the rules.
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- * @param value The value to be serialized.
- * @return a printable, displayable, transmittable
- * representation of the object, beginning
- * with <code>{</code> <small>(left brace)</small> and ending
- * with <code>}</code> <small>(right brace)</small>.
- * @throws JSONException If the value is or contains an invalid number.
- */
- public static String valueToString(Object value) throws JSONException {
- return renderer.valueToString(value);
- }
-
- /**
- * Make a prettyprinted JSON text of an object value
- * using {@link JSONRenderer#valueToString}
- */
- static String valueToString(Object value, int indentFactor, int initialIndent)
- throws JSONException {
- return renderer.valueToString(value,
- renderer.options().withIndent(indentFactor).withInitialIndent(initialIndent));
- }
-
- /**
- * Write the contents of the JSONObject as JSON text to a writer
- * using {@link JSONRenderer#write(Writer, JSONObject)}
- */
- public Writer write(Writer writer) throws JSONException {
- return renderer.write(writer, this);
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/apache/sling/commons/json/JSONString.java b/src/main/java/org/apache/sling/commons/json/JSONString.java
deleted file mode 100644
index aef57c2..0000000
--- a/src/main/java/org/apache/sling/commons/json/JSONString.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package org.apache.sling.commons.json;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-/**
- * The <code>JSONString</code> interface allows a <code>toJSONString()</code>
- * method so that a class can change the behavior of
- * <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>,
- * and <code>JSONWriter.value(</code>Object<code>)</code>. The
- * <code>toJSONString</code> method will be used instead of the default behavior
- * of using the Object's <code>toString()</code> method and quoting the result.
- */
-@Deprecated
-public interface JSONString {
- /**
- * The <code>toJSONString</code> method allows a class to produce its own JSON
- * serialization.
- *
- * @return A strictly syntactically correct JSON text.
- */
- public String toJSONString();
-}
diff --git a/src/main/java/org/apache/sling/commons/json/JSONTokener.java b/src/main/java/org/apache/sling/commons/json/JSONTokener.java
deleted file mode 100644
index 939a8df..0000000
--- a/src/main/java/org/apache/sling/commons/json/JSONTokener.java
+++ /dev/null
@@ -1,461 +0,0 @@
-package org.apache.sling.commons.json;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-/**
- * A JSONTokener takes a source string and extracts characters and tokens from
- * it. It is used by the JSONObject and JSONArray constructors to parse
- * JSON source strings.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class JSONTokener {
-
- /**
- * The index of the next character.
- */
- private int myIndex;
-
-
- /**
- * The source string being tokenized.
- */
- private String mySource;
-
-
- /**
- * Construct a JSONTokener from a string.
- *
- * @param s A source string.
- */
- public JSONTokener(String s) {
- this.myIndex = 0;
- this.mySource = s;
- }
-
-
- /**
- * Back up one character. This provides a sort of lookahead capability,
- * so that you can test for a digit or letter before attempting to parse
- * the next number or identifier.
- */
- public void back() {
- if (this.myIndex > 0) {
- this.myIndex -= 1;
- }
- }
-
-
-
- /**
- * Get the hex value of a character (base16).
- * @param c A character between '0' and '9' or between 'A' and 'F' or
- * between 'a' and 'f'.
- * @return An int between 0 and 15, or -1 if c was not a hex digit.
- */
- public static int dehexchar(char c) {
- if (c >= '0' && c <= '9') {
- return c - '0';
- }
- if (c >= 'A' && c <= 'F') {
- return c - ('A' - 10);
- }
- if (c >= 'a' && c <= 'f') {
- return c - ('a' - 10);
- }
- return -1;
- }
-
-
- /**
- * Determine if the source string still contains characters that next()
- * can consume.
- * @return true if not yet at the end of the source.
- */
- public boolean more() {
- return this.myIndex < this.mySource.length();
- }
-
-
- /**
- * Get the next character in the source string.
- *
- * @return The next character, or 0 if past the end of the source string.
- */
- public char next() {
- if (more()) {
- char c = this.mySource.charAt(this.myIndex);
- this.myIndex += 1;
- return c;
- }
- return 0;
- }
-
-
- /**
- * Consume the next character, and check that it matches a specified
- * character.
- * @param c The character to match.
- * @return The character.
- * @throws JSONException if the character does not match.
- */
- public char next(char c) throws JSONException {
- char n = next();
- if (n != c) {
- throw syntaxError("Expected '" + c + "' and instead saw '" +
- n + "'.");
- }
- return n;
- }
-
-
- /**
- * Get the next n characters.
- *
- * @param n The number of characters to take.
- * @return A string of n characters.
- * @throws JSONException
- * Substring bounds error if there are not
- * n characters remaining in the source string.
- */
- public String next(int n) throws JSONException {
- int i = this.myIndex;
- int j = i + n;
- if (j >= this.mySource.length()) {
- throw syntaxError("Substring bounds error");
- }
- this.myIndex += n;
- return this.mySource.substring(i, j);
- }
-
-
- /**
- * Get the next char in the string, skipping whitespace
- * and comments (slashslash, slashstar, and hash).
- * @throws JSONException
- * @return A character, or 0 if there are no more characters.
- */
- public char nextClean() throws JSONException {
- for (;;) {
- char c = next();
- if (c == '/') {
- switch (next()) {
- case '/':
- do {
- c = next();
- } while (c != '\n' && c != '\r' && c != 0);
- break;
- case '*':
- for (;;) {
- c = next();
- if (c == 0) {
- throw syntaxError("Unclosed comment.");
- }
- if (c == '*') {
- if (next() == '/') {
- break;
- }
- back();
- }
- }
- break;
- default:
- back();
- return '/';
- }
- } else if (c == '#') {
- do {
- c = next();
- } while (c != '\n' && c != '\r' && c != 0);
- } else if (c == 0 || c > ' ') {
- return c;
- }
- }
- }
-
-
- /**
- * Return the characters up to the next close quote character.
- * Backslash processing is done. The formal JSON format does not
- * allow strings in single quotes, but an implementation is allowed to
- * accept them.
- * @param quote The quoting character, either
- * <code>"</code> <small>(double quote)</small> or
- * <code>'</code> <small>(single quote)</small>.
- * @return A String.
- * @throws JSONException Unterminated string.
- */
- public String nextString(char quote) throws JSONException {
- char c;
- StringBuffer sb = new StringBuffer();
- for (;;) {
- c = next();
- switch (c) {
- case 0:
- case '\n':
- case '\r':
- throw syntaxError("Unterminated string");
- case '\\':
- c = next();
- switch (c) {
- case 'b':
- sb.append('\b');
- break;
- case 't':
- sb.append('\t');
- break;
- case 'n':
- sb.append('\n');
- break;
- case 'f':
- sb.append('\f');
- break;
- case 'r':
- sb.append('\r');
- break;
- case 'u':
- sb.append((char)Integer.parseInt(next(4), 16));
- break;
- case 'x' :
- sb.append((char) Integer.parseInt(next(2), 16));
- break;
- default:
- sb.append(c);
- }
- break;
- default:
- if (c == quote) {
- return sb.toString();
- }
- sb.append(c);
- }
- }
- }
-
-
- /**
- * Get the text up but not including the specified character or the
- * end of line, whichever comes first.
- * @param d A delimiter character.
- * @return A string.
- */
- public String nextTo(char d) {
- StringBuffer sb = new StringBuffer();
- for (;;) {
- char c = next();
- if (c == d || c == 0 || c == '\n' || c == '\r') {
- if (c != 0) {
- back();
- }
- return sb.toString().trim();
- }
- sb.append(c);
- }
- }
-
-
- /**
- * Get the text up but not including one of the specified delimeter
- * characters or the end of line, whichever comes first.
- * @param delimiters A set of delimiter characters.
- * @return A string, trimmed.
- */
- public String nextTo(String delimiters) {
- char c;
- StringBuffer sb = new StringBuffer();
- for (;;) {
- c = next();
- if (delimiters.indexOf(c) >= 0 || c == 0 ||
- c == '\n' || c == '\r') {
- if (c != 0) {
- back();
- }
- return sb.toString().trim();
- }
- sb.append(c);
- }
- }
-
-
- /**
- * Get the next value. The value can be a Boolean, Double, Integer,
- * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
- * @throws JSONException If syntax error.
- *
- * @return An object.
- */
- public Object nextValue() throws JSONException {
- char c = nextClean();
- String s;
-
- switch (c) {
- case '"':
- case '\'':
- return nextString(c);
- case '{':
- back();
- return new JSONObject(this);
- case '[':
- back();
- return new JSONArray(this);
- }
-
- /*
- * Handle unquoted text. This could be the values true, false, or
- * null, or it can be a number. An implementation (such as this one)
- * is allowed to also accept non-standard forms.
- *
- * Accumulate characters until we reach the end of the text or a
- * formatting character.
- */
-
- StringBuffer sb = new StringBuffer();
- char b = c;
- while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
- sb.append(c);
- c = next();
- }
- back();
-
- /*
- * If it is true, false, or null, return the proper value.
- */
-
- s = sb.toString().trim();
- if (s.equals("")) {
- throw syntaxError("Missing value.");
- }
- if (s.equalsIgnoreCase("true")) {
- return Boolean.TRUE;
- }
- if (s.equalsIgnoreCase("false")) {
- return Boolean.FALSE;
- }
- if (s.equalsIgnoreCase("null")) {
- return JSONObject.NULL;
- }
-
- /*
- * If it might be a number, try converting it. We support the 0- and 0x-
- * conventions. If a number cannot be produced, then the value will just
- * be a string. Note that the 0-, 0x-, plus, and implied string
- * conventions are non-standard. A JSON parser is free to accept
- * non-JSON forms as long as it accepts all correct JSON forms.
- */
-
- if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
- if (b == '0') {
- if (s.length() > 2 &&
- (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
- try {
- return new Integer(Integer.parseInt(s.substring(2),
- 16));
- } catch (Exception e) {
- /* Ignore the error */
- }
- } else {
- try {
- return new Integer(Integer.parseInt(s, 8));
- } catch (Exception e) {
- /* Ignore the error */
- }
- }
- }
- try {
- return new Integer(s);
- } catch (Exception e) {
- try {
- return new Long(s);
- } catch (Exception f) {
- try {
- return new Double(s);
- } catch (Exception g) {
- return s;
- }
- }
- }
- }
- return s;
- }
-
-
- /**
- * Skip characters until the next character is the requested character.
- * If the requested character is not found, no characters are skipped.
- * @param to A character to skip to.
- * @return The requested character, or zero if the requested character
- * is not found.
- */
- public char skipTo(char to) {
- char c;
- int index = this.myIndex;
- do {
- c = next();
- if (c == 0) {
- this.myIndex = index;
- return c;
- }
- } while (c != to);
- back();
- return c;
- }
-
-
- /**
- * Skip characters until past the requested string.
- * If it is not found, we are left at the end of the source.
- * @param to A string to skip past.
- */
- public void skipPast(String to) {
- this.myIndex = this.mySource.indexOf(to, this.myIndex);
- if (this.myIndex < 0) {
- this.myIndex = this.mySource.length();
- } else {
- this.myIndex += to.length();
- }
- }
-
-
- /**
- * Make a JSONException to signal a syntax error.
- *
- * @param message The error message.
- * @return A JSONException object, suitable for throwing
- */
- public JSONException syntaxError(String message) {
- return new JSONException(message + toString());
- }
-
-
- /**
- * Make a printable string of this JSONTokener.
- *
- * @return " at character [this.myIndex] of [this.mySource]"
- */
- public String toString() {
- return " at character " + this.myIndex + " of " + this.mySource;
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/apache/sling/commons/json/http/Cookie.java b/src/main/java/org/apache/sling/commons/json/http/Cookie.java
deleted file mode 100644
index 95acc8e..0000000
--- a/src/main/java/org/apache/sling/commons/json/http/Cookie.java
+++ /dev/null
@@ -1,174 +0,0 @@
-package org.apache.sling.commons.json.http;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.apache.sling.commons.json.JSONTokener;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-/**
- * Convert a web browser cookie specification to a JSONObject and back.
- * JSON and Cookies are both notations for name/value pairs.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class Cookie {
-
- /**
- * Produce a copy of a string in which the characters '+', '%', '=', ';'
- * and control characters are replaced with "%hh". This is a gentle form
- * of URL encoding, attempting to cause as little distortion to the
- * string as possible. The characters '=' and ';' are meta characters in
- * cookies. By convention, they are escaped using the URL-encoding. This is
- * only a convention, not a standard. Often, cookies are expected to have
- * encoded values. We encode '=' and ';' because we must. We encode '%' and
- * '+' because they are meta characters in URL encoding.
- * @param string The source string.
- * @return The escaped result.
- */
- public static String escape(String string) {
- char c;
- String s = string.trim();
- StringBuffer sb = new StringBuffer();
- int len = s.length();
- for (int i = 0; i < len; i += 1) {
- c = s.charAt(i);
- if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
- sb.append('%');
- sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
- sb.append(Character.forDigit((char)(c & 0x0f), 16));
- } else {
- sb.append(c);
- }
- }
- return sb.toString();
- }
-
-
- /**
- * Convert a cookie specification string into a JSONObject. The string
- * will contain a name value pair separated by '='. The name and the value
- * will be unescaped, possibly converting '+' and '%' sequences. The
- * cookie properties may follow, separated by ';', also represented as
- * name=value (except the secure property, which does not have a value).
- * The name will be stored under the key "name", and the value will be
- * stored under the key "value". This method does not do checking or
- * validation of the parameters. It only converts the cookie string into
- * a JSONObject.
- * @param string The cookie specification string.
- * @return A JSONObject containing "name", "value", and possibly other
- * members.
- * @throws JSONException
- */
- public static JSONObject toJSONObject(String string) throws JSONException {
- String n;
- JSONObject o = new JSONObject();
- Object v;
- JSONTokener x = new JSONTokener(string);
- o.put("name", x.nextTo('='));
- x.next('=');
- o.put("value", x.nextTo(';'));
- x.next();
- while (x.more()) {
- n = unescape(x.nextTo("=;"));
- if (x.next() != '=') {
- if (n.equals("secure")) {
- v = Boolean.TRUE;
- } else {
- throw x.syntaxError("Missing '=' in cookie parameter.");
- }
- } else {
- v = unescape(x.nextTo(';'));
- x.next();
- }
- o.put(n, v);
- }
- return o;
- }
-
-
- /**
- * Convert a JSONObject into a cookie specification string. The JSONObject
- * must contain "name" and "value" members.
- * If the JSONObject contains "expires", "domain", "path", or "secure"
- * members, they will be appended to the cookie specification string.
- * All other members are ignored.
- * @param o A JSONObject
- * @return A cookie specification string
- * @throws JSONException
- */
- public static String toString(JSONObject o) throws JSONException {
- StringBuffer sb = new StringBuffer();
-
- sb.append(escape(o.getString("name")));
- sb.append("=");
- sb.append(escape(o.getString("value")));
- if (o.has("expires")) {
- sb.append(";expires=");
- sb.append(o.getString("expires"));
- }
- if (o.has("domain")) {
- sb.append(";domain=");
- sb.append(escape(o.getString("domain")));
- }
- if (o.has("path")) {
- sb.append(";path=");
- sb.append(escape(o.getString("path")));
- }
- if (o.optBoolean("secure")) {
- sb.append(";secure");
- }
- return sb.toString();
- }
-
- /**
- * Convert <code>%</code><i>hh</i> sequences to single characters, and
- * convert plus to space.
- * @param s A string that may contain
- * <code>+</code> <small>(plus)</small> and
- * <code>%</code><i>hh</i> sequences.
- * @return The unescaped string.
- */
- public static String unescape(String s) {
- int len = s.length();
- StringBuffer b = new StringBuffer();
- for (int i = 0; i < len; ++i) {
- char c = s.charAt(i);
- if (c == '+') {
- c = ' ';
- } else if (c == '%' && i + 2 < len) {
- int d = JSONTokener.dehexchar(s.charAt(i + 1));
- int e = JSONTokener.dehexchar(s.charAt(i + 2));
- if (d >= 0 && e >= 0) {
- c = (char)(d * 16 + e);
- i += 2;
- }
- }
- b.append(c);
- }
- return b.toString();
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/http/CookieList.java b/src/main/java/org/apache/sling/commons/json/http/CookieList.java
deleted file mode 100644
index 1d397f7..0000000
--- a/src/main/java/org/apache/sling/commons/json/http/CookieList.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package org.apache.sling.commons.json.http;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-import java.util.Iterator;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.apache.sling.commons.json.JSONTokener;
-
-/**
- * Convert a web browser cookie list string to a JSONObject and back.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class CookieList {
-
- /**
- * Convert a cookie list into a JSONObject. A cookie list is a sequence
- * of name/value pairs. The names are separated from the values by '='.
- * The pairs are separated by ';'. The names and the values
- * will be unescaped, possibly converting '+' and '%' sequences.
- *
- * To add a cookie to a cooklist,
- * cookielistJSONObject.put(cookieJSONObject.getString("name"),
- * cookieJSONObject.getString("value"));
- * @param string A cookie list string
- * @return A JSONObject
- * @throws JSONException
- */
- public static JSONObject toJSONObject(String string) throws JSONException {
- JSONObject o = new JSONObject();
- JSONTokener x = new JSONTokener(string);
- while (x.more()) {
- String name = Cookie.unescape(x.nextTo('='));
- x.next('=');
- o.put(name, Cookie.unescape(x.nextTo(';')));
- x.next();
- }
- return o;
- }
-
-
- /**
- * Convert a JSONObject into a cookie list. A cookie list is a sequence
- * of name/value pairs. The names are separated from the values by '='.
- * The pairs are separated by ';'. The characters '%', '+', '=', and ';'
- * in the names and values are replaced by "%hh".
- * @param o A JSONObject
- * @return A cookie list string
- * @throws JSONException
- */
- public static String toString(JSONObject o) throws JSONException {
- boolean b = false;
- Iterator<String> keys = o.keys();
- String s;
- StringBuffer sb = new StringBuffer();
- while (keys.hasNext()) {
- s = keys.next();
- if (!o.isNull(s)) {
- if (b) {
- sb.append(';');
- }
- sb.append(Cookie.escape(s));
- sb.append("=");
- sb.append(Cookie.escape(o.getString(s)));
- b = true;
- }
- }
- return sb.toString();
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/http/HTTP.java b/src/main/java/org/apache/sling/commons/json/http/HTTP.java
deleted file mode 100644
index fb53d91..0000000
--- a/src/main/java/org/apache/sling/commons/json/http/HTTP.java
+++ /dev/null
@@ -1,167 +0,0 @@
-package org.apache.sling.commons.json.http;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-import java.util.Iterator;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-
-/**
- * Convert an HTTP header to a JSONObject and back.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class HTTP {
-
- /** Carriage return/line feed. */
- public static final String CRLF = "\r\n";
-
- /**
- * Convert an HTTP header string into a JSONObject. It can be a request
- * header or a response header. A request header will contain
- * <pre>{
- * Method: "POST" (for example),
- * "Request-URI": "/" (for example),
- * "HTTP-Version": "HTTP/1.1" (for example)
- * }</pre>
- * A response header will contain
- * <pre>{
- * "HTTP-Version": "HTTP/1.1" (for example),
- * "Status-Code": "200" (for example),
- * "Reason-Phrase": "OK" (for example)
- * }</pre>
- * In addition, the other parameters in the header will be captured, using
- * the HTTP field names as JSON names, so that <pre>
- * Date: Sun, 26 May 2002 18:06:04 GMT
- * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
- * Cache-Control: no-cache</pre>
- * become
- * <pre>{...
- * Date: "Sun, 26 May 2002 18:06:04 GMT",
- * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
- * "Cache-Control": "no-cache",
- * ...}</pre>
- * It does no further checking or conversion. It does not parse dates.
- * It does not do '%' transforms on URLs.
- * @param string An HTTP header string.
- * @return A JSONObject containing the elements and attributes
- * of the XML string.
- * @throws JSONException
- */
- public static JSONObject toJSONObject(String string) throws JSONException {
- JSONObject o = new JSONObject();
- HTTPTokener x = new HTTPTokener(string);
- String t;
-
- t = x.nextToken();
- if (t.toUpperCase().startsWith("HTTP")) {
-
-// Response
-
- o.put("HTTP-Version", t);
- o.put("Status-Code", x.nextToken());
- o.put("Reason-Phrase", x.nextTo('\0'));
- x.next();
-
- } else {
-
-// Request
-
- o.put("Method", t);
- o.put("Request-URI", x.nextToken());
- o.put("HTTP-Version", x.nextToken());
- }
-
-// Fields
-
- while (x.more()) {
- String name = x.nextTo(':');
- x.next(':');
- o.put(name, x.nextTo('\0'));
- x.next();
- }
- return o;
- }
-
-
- /**
- * Convert a JSONObject into an HTTP header. A request header must contain
- * <pre>{
- * Method: "POST" (for example),
- * "Request-URI": "/" (for example),
- * "HTTP-Version": "HTTP/1.1" (for example)
- * }</pre>
- * A response header must contain
- * <pre>{
- * "HTTP-Version": "HTTP/1.1" (for example),
- * "Status-Code": "200" (for example),
- * "Reason-Phrase": "OK" (for example)
- * }</pre>
- * Any other members of the JSONObject will be output as HTTP fields.
- * The result will end with two CRLF pairs.
- * @param o A JSONObject
- * @return An HTTP header string.
- * @throws JSONException if the object does not contain enough
- * information.
- */
- public static String toString(JSONObject o) throws JSONException {
- Iterator<String> keys = o.keys();
- String s;
- StringBuffer sb = new StringBuffer();
- if (o.has("Status-Code") && o.has("Reason-Phrase")) {
- sb.append(o.getString("HTTP-Version"));
- sb.append(' ');
- sb.append(o.getString("Status-Code"));
- sb.append(' ');
- sb.append(o.getString("Reason-Phrase"));
- } else if (o.has("Method") && o.has("Request-URI")) {
- sb.append(o.getString("Method"));
- sb.append(' ');
- sb.append('"');
- sb.append(o.getString("Request-URI"));
- sb.append('"');
- sb.append(' ');
- sb.append(o.getString("HTTP-Version"));
- } else {
- throw new JSONException("Not enough material for an HTTP header.");
- }
- sb.append(CRLF);
- while (keys.hasNext()) {
- s = keys.next();
- if (!s.equals("HTTP-Version") && !s.equals("Status-Code") &&
- !s.equals("Reason-Phrase") && !s.equals("Method") &&
- !s.equals("Request-URI") && !o.isNull(s)) {
- sb.append(s);
- sb.append(": ");
- sb.append(o.getString(s));
- sb.append(CRLF);
- }
- }
- sb.append(CRLF);
- return sb.toString();
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/http/HTTPTokener.java b/src/main/java/org/apache/sling/commons/json/http/HTTPTokener.java
deleted file mode 100644
index 3d013a6..0000000
--- a/src/main/java/org/apache/sling/commons/json/http/HTTPTokener.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package org.apache.sling.commons.json.http;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONTokener;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-/**
- * The HTTPTokener extends the JSONTokener to provide additional methods
- * for the parsing of HTTP headers.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class HTTPTokener extends JSONTokener {
-
- /**
- * Construct an XMLTokener from a string.
- * @param s A source string.
- */
- public HTTPTokener(String s) {
- super(s);
- }
-
-
- /**
- * Get the next token or string. This is used in parsing HTTP headers.
- * @throws JSONException
- * @return A String.
- */
- public String nextToken() throws JSONException {
- char c;
- char q;
- StringBuffer sb = new StringBuffer();
- do {
- c = next();
- } while (Character.isWhitespace(c));
- if (c == '"' || c == '\'') {
- q = c;
- for (;;) {
- c = next();
- if (c < ' ') {
- throw syntaxError("Unterminated string.");
- }
- if (c == q) {
- return sb.toString();
- }
- sb.append(c);
- }
- }
- for (;;) {
- if (c == 0 || Character.isWhitespace(c)) {
- return sb.toString();
- }
- sb.append(c);
- c = next();
- }
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/http/package-info.java b/src/main/java/org/apache/sling/commons/json/http/package-info.java
deleted file mode 100644
index eb91a16..0000000
--- a/src/main/java/org/apache/sling/commons/json/http/package-info.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-@Version("2.0.5")
-package org.apache.sling.commons.json.http;
-
-import org.osgi.annotation.versioning.Version;
diff --git a/src/main/java/org/apache/sling/commons/json/io/JSONRenderer.java b/src/main/java/org/apache/sling/commons/json/io/JSONRenderer.java
deleted file mode 100644
index 1dec7bf..0000000
--- a/src/main/java/org/apache/sling/commons/json/io/JSONRenderer.java
+++ /dev/null
@@ -1,617 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.io;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.apache.sling.commons.json.JSONString;
-
-/** Various JSON-to-String primitives, used by other classes
- * when outputting/formatting JSON.
- *
- * Streaming variants of some methods are provided.
- * The existing code in this module is often not streaming, but
- * we should write newer code using streams, as much as
- * possible.
- */
-@Deprecated
-public class JSONRenderer {
-
- /** Rendering options */
- static public class Options {
- int indent;
- private boolean indentIsPositive;
- int initialIndent;
- boolean arraysForChildren;
-
- public static final String DEFAULT_CHILDREN_KEY = "__children__";
- public static final String DEFAULT_CHILD_NAME_KEY = "__name__";
-
- String childrenKey = DEFAULT_CHILDREN_KEY;
- String childNameKey = DEFAULT_CHILD_NAME_KEY;
-
- /** Clients use JSONRenderer.options() to create objects */
- private Options() {
- }
-
- Options(Options opt) {
- this.indent = opt.indent;
- this.indentIsPositive = opt.indentIsPositive;
- this.initialIndent = opt.initialIndent;
- this.arraysForChildren = opt.arraysForChildren;
- }
-
- public Options withIndent(int n) {
- indent = n;
- indentIsPositive = indent > 0;
- return this;
- }
-
- public Options withInitialIndent(int n) {
- initialIndent = n;
- return this;
- }
-
- public Options withArraysForChildren(boolean b) {
- arraysForChildren = b;
- return this;
- }
-
- public Options withChildNameKey(String key) {
- childNameKey = key;
- return this;
- }
-
- public Options withChildrenKey(String key) {
- childrenKey = key;
- return this;
- }
-
- boolean hasIndent() {
- return indentIsPositive;
- }
- }
-
- /** JSONObject that has a name - overrides just what we
- * need for our rendering purposes.
- */
- static private class NamedJSONObject extends JSONObject {
- final String name;
- final JSONObject jsonObject;
- final String nameKey;
- final List<String> keysWithName;
-
- NamedJSONObject(String name, JSONObject jsonObject, Options opt) {
- this.name = name;
- this.jsonObject = jsonObject;
- this.nameKey = opt.childNameKey;
- keysWithName = new ArrayList<String>();
- keysWithName.add(nameKey);
- final Iterator<String> it = jsonObject.keys();
- while(it.hasNext()) {
- keysWithName.add(it.next());
- }
- }
-
- @Override
- public int length() {
- return keysWithName.size();
- }
-
- @Override
- public Object get(String key) throws JSONException {
- if(key.equals(nameKey)) {
- return name;
- }
- return jsonObject.get(key);
- }
-
- @Override
- public Iterator<String> keys() {
- return keysWithName.iterator();
- }
- }
-
- /** Return an Options object with default values */
- public Options options() {
- return new Options();
- }
-
- /** Write N spaces to sb for indentation */
- private void indent(StringBuilder sb, int howMuch) {
- for (int i=0; i < howMuch; i++) {
- sb.append(' ');
- }
- }
-
- /** Render the supplied JSONObject to a String, in
- * the simplest possible way.
- */
- public String toString(JSONObject jo) {
- try {
- final Iterator<String> keys = jo.keys();
- final StringBuffer sb = new StringBuffer("{");
-
- while (keys.hasNext()) {
- if (sb.length() > 1) {
- sb.append(',');
- }
- String o = keys.next();
- sb.append(quote(o));
- sb.append(':');
- sb.append(valueToString(jo.opt(o)));
- }
- sb.append('}');
- return sb.toString();
- } catch (Exception e) {
- return null;
- }
- }
-
- /** Make a JSON text of the supplied JSONArray. For compactness, no
- * unnecessary whitespace is added. If it is not possible to produce a
- * syntactically correct JSON text then null will be returned instead. This
- * could occur if the array contains an invalid number.
- * <p>Warning: This method assumes that the data structure is acyclical.
- *
- * @return a printable, displayable, transmittable
- * representation of the array.
- */
- public String toString(JSONArray ja) {
- try {
- return '[' + join(ja,",") + ']';
- } catch (Exception e) {
- return null;
- }
- }
-
- /** Quote the supplied string for JSON */
- public String quote(String string) {
- if (string == null || string.length() == 0) {
- return "\"\"";
- }
-
- char b;
- char c = 0;
- int i;
- int len = string.length();
- StringBuilder sb = new StringBuilder(len + 2);
- String t;
-
- sb.append('"');
- for (i = 0; i < len; i += 1) {
- b = c;
- c = string.charAt(i);
- switch (c) {
- case '\\':
- case '"':
- sb.append('\\');
- sb.append(c);
- break;
- case '/':
- if (b == '<') {
- sb.append('\\');
- }
- sb.append(c);
- break;
- case '\b':
- sb.append("\\b");
- break;
- case '\t':
- sb.append("\\t");
- break;
- case '\n':
- sb.append("\\n");
- break;
- case '\f':
- sb.append("\\f");
- break;
- case '\r':
- sb.append("\\r");
- break;
- default:
- if (c < ' ' || (c >= '\u0080' && c < '\u00a0') ||
- (c >= '\u2000' && c < '\u2100')) {
- t = "000" + Integer.toHexString(c);
- sb.append("\\u").append(t.substring(t.length() - 4));
- } else {
- sb.append(c);
- }
- }
- }
- sb.append('"');
- return sb.toString();
- }
-
- /** Quote the supplied string for JSON, to the supplied Writer */
- public void quote(Writer w, String string) throws IOException {
- w.write(quote(string));
- }
-
- /**
- * Make a JSON text of an Object value. If the object has an
- * value.toJSONString() method, then that method will be used to produce
- * the JSON text. The method is required to produce a strictly
- * conforming text. If the object does not contain a toJSONString
- * method (which is the most common case), then a text will be
- * produced by the rules.
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- * @param value The value to be serialized.
- * @return a printable, displayable, transmittable
- * representation of the object, beginning
- * with <code>{</code> <small>(left brace)</small> and ending
- * with <code>}</code> <small>(right brace)</small>.
- * @throws JSONException If the value is or contains an invalid number.
- */
- public String valueToString(Object value) throws JSONException {
- // TODO call the other valueToString instead
- if (value == null || value.equals(null)) {
- return "null";
- }
- if (value instanceof JSONString) {
- Object o;
- try {
- o = ((JSONString)value).toJSONString();
- } catch (Exception e) {
- throw new JSONException(e);
- }
- if (o instanceof String) {
- return (String)o;
- }
- throw new JSONException("Bad value from toJSONString: " + o);
- }
- if (value instanceof Number) {
- return numberToString((Number) value);
- }
- if (value instanceof Boolean || value instanceof JSONObject ||
- value instanceof JSONArray) {
- return value.toString();
- }
- return quote(value.toString());
- }
-
- /** Make a JSON String of an Object value, with rendering options
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- * @param value The value to be serialized.
- * @return a printable, displayable, transmittable
- * representation of the object, beginning
- * with <code>{</code> <small>(left brace)</small> and ending
- * with <code>}</code> <small>(right brace)</small>.
- * @throws JSONException If the object contains an invalid number.
- */
- public String valueToString(Object value, Options opt) throws JSONException {
- if (value == null || value.equals(null)) {
- return "null";
- }
- try {
- if (value instanceof JSONString) {
- Object o = ((JSONString)value).toJSONString();
- if (o instanceof String) {
- return (String)o;
- }
- }
- } catch (Exception e) {
- /* forget about it */
- }
- if (value instanceof Number) {
- return numberToString((Number) value);
- }
- if (value instanceof Boolean) {
- return value.toString();
- }
- if (value instanceof JSONObject) {
- return prettyPrint((JSONObject)value, opt);
- }
- if (value instanceof JSONArray) {
- return prettyPrint((JSONArray)value, opt);
- }
- return quote(value.toString());
-
- }
-
- /**
- * Produce a string from a Number.
- * @param n A Number
- * @return A String.
- * @throws JSONException If n is a non-finite number.
- */
- public String numberToString(Number n)
- throws JSONException {
- if (n == null) {
- throw new JSONException("Null pointer");
- }
- testNumberValidity(n);
-
- // Shave off trailing zeros and decimal point, if possible.
-
- String s = n.toString();
- if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
- while (s.endsWith("0")) {
- s = s.substring(0, s.length() - 1);
- }
- if (s.endsWith(".")) {
- s = s.substring(0, s.length() - 1);
- }
- }
- return s;
- }
-
- /** Decide whether o must be skipped and added to a, when rendering a JSONObject */
- private boolean skipChildObject(JSONArray a, Options opt, String key, Object value) {
- if(opt.arraysForChildren && (value instanceof JSONObject)) {
- a.put(new NamedJSONObject(key, (JSONObject)value, opt));
- return true;
- }
- return false;
- }
-
- /**
- * Make a prettyprinted JSON text of this JSONObject.
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- * @return a printable, displayable, transmittable
- * representation of the object, beginning
- * with <code>{</code> <small>(left brace)</small> and ending
- * with <code>}</code> <small>(right brace)</small>.
- * @throws JSONException If the object contains an invalid number.
- */
- public String prettyPrint(JSONObject jo, Options opt) throws JSONException {
- int n = jo.length();
- if (n == 0) {
- return "{}";
- }
- final JSONArray children = new JSONArray();
- Iterator<String> keys = jo.keys();
- StringBuilder sb = new StringBuilder("{");
- int newindent = opt.initialIndent + opt.indent;
- String o;
- if (n == 1) {
- o = keys.next();
- final Object v = jo.get(o);
- if(!skipChildObject(children, opt, o, v)) {
- sb.append(quote(o));
- sb.append(": ");
- sb.append(valueToString(v, opt));
- }
- } else {
- while (keys.hasNext()) {
- o = keys.next();
- final Object v = jo.get(o);
- if(skipChildObject(children, opt, o, v)) {
- continue;
- }
- if (sb.length() > 1) {
- sb.append(",\n");
- } else {
- sb.append('\n');
- }
- indent(sb, newindent);
- sb.append(quote(o.toString()));
- sb.append(": ");
- sb.append(valueToString(v,
- options().withIndent(opt.indent).withInitialIndent(newindent)));
- }
- if (sb.length() > 1) {
- sb.append('\n');
- indent(sb, newindent);
- }
- }
-
- /** Render children if any were skipped (in "children in arrays" mode) */
- if(children.length() > 0) {
- if (sb.length() > 1) {
- sb.append(",\n");
- } else {
- sb.append('\n');
- }
- final Options childOpt = new Options(opt);
- childOpt.withInitialIndent(childOpt.initialIndent + newindent);
- indent(sb, childOpt.initialIndent);
- sb.append(quote(opt.childrenKey)).append(":");
- sb.append(prettyPrint(children, childOpt));
- }
-
- sb.append('}');
- return sb.toString();
- }
-
- /** Pretty-print a JSONArray */
- public String prettyPrint(JSONArray ja, Options opt) throws JSONException {
- int len = ja.length();
- if (len == 0) {
- return "[]";
- }
- int i;
- StringBuilder sb = new StringBuilder("[");
- if (len == 1) {
- sb.append(valueToString(ja.get(0), opt));
- } else {
- final int newindent = opt.initialIndent + opt.indent;
- if(opt.hasIndent()) {
- sb.append('\n');
- }
- for (i = 0; i < len; i += 1) {
- if (i > 0) {
- sb.append(',');
- if(opt.hasIndent()) {
- sb.append('\n');
- }
- }
- indent(sb, newindent);
- sb.append(valueToString(ja.get(i), opt));
- }
- if(opt.hasIndent()) {
- sb.append('\n');
- }
- indent(sb, opt.initialIndent);
- }
- sb.append(']');
- return sb.toString();
- }
-
- /**
- * Throw an exception if the object is an NaN or infinite number.
- * @param o The object to test.
- * @throws JSONException If o is a non-finite number.
- */
- public void testNumberValidity(Object o) throws JSONException {
- if (o != null) {
- if (o instanceof Double) {
- if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
- throw new JSONException(
- "JSON does not allow non-finite numbers");
- }
- } else if (o instanceof Float) {
- if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
- throw new JSONException(
- "JSON does not allow non-finite numbers.");
- }
- }
- }
- }
-
- /**
- * Make a string from the contents of this JSONArray. The
- * <code>separator</code> string is inserted between each element.
- * Warning: This method assumes that the data structure is acyclical.
- * @param separator A string that will be inserted between the elements.
- * @return a string.
- * @throws JSONException If the array contains an invalid number.
- */
- public String join(JSONArray ja, String separator) throws JSONException {
- final int len = ja.length();
- StringBuffer sb = new StringBuffer();
-
- for (int i = 0; i < len; i += 1) {
- if (i > 0) {
- sb.append(separator);
- }
- sb.append(JSONObject.valueToString(ja.get(i)));
- }
- return sb.toString();
- }
-
- /**
- * Write the contents of the supplied JSONObject as JSON text to a writer.
- * For compactness, no whitespace is added.
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return The writer.
- * @throws JSONException
- */
- public Writer write(Writer writer, JSONObject jo) throws JSONException {
- try {
- boolean b = false;
- Iterator<String> keys = jo.keys();
- writer.write('{');
-
- while (keys.hasNext()) {
- if (b) {
- writer.write(',');
- }
- String k = keys.next();
- writer.write(quote(k));
- writer.write(':');
- final Object v = jo.get(k);
- if (v instanceof JSONObject) {
- ((JSONObject)v).write(writer);
- } else if (v instanceof JSONArray) {
- ((JSONArray)v).write(writer);
- } else {
- writer.write(valueToString(v));
- }
- b = true;
- }
- writer.write('}');
- return writer;
- } catch (IOException e) {
- throw new JSONException(e);
- }
- }
-
- /**
- * Write the contents of the supplied JSONArray as JSON text to a writer.
- * For compactness, no whitespace is added.
- * <p>
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return The writer.
- * @throws JSONException
- */
- public Writer write(Writer writer, JSONArray ja) throws JSONException {
- try {
- boolean b = false;
- int len = ja.length();
-
- writer.write('[');
-
- for (int i = 0; i < len; i += 1) {
- if (b) {
- writer.write(',');
- }
- final Object v = ja.get(i);
- if (v instanceof JSONObject) {
- ((JSONObject)v).write(writer);
- } else if (v instanceof JSONArray) {
- ((JSONArray)v).write(writer);
- } else {
- writer.write(JSONObject.valueToString(v));
- }
- b = true;
- }
- writer.write(']');
- return writer;
- } catch (IOException e) {
- throw new JSONException(e);
- }
- }
-
- /**
- * Produce a string from a double. The string "null" will be returned if
- * the number is not finite.
- * @param d A double.
- * @return A String.
- */
- public String doubleToString(double d) {
- if (Double.isInfinite(d) || Double.isNaN(d)) {
- return "null";
- }
-
- // Shave off trailing zeros and decimal point, if possible.
-
- String s = Double.toString(d);
- if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
- while (s.endsWith("0")) {
- s = s.substring(0, s.length() - 1);
- }
- if (s.endsWith(".")) {
- s = s.substring(0, s.length() - 1);
- }
- }
- return s;
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/apache/sling/commons/json/io/JSONStringer.java b/src/main/java/org/apache/sling/commons/json/io/JSONStringer.java
deleted file mode 100644
index 104a181..0000000
--- a/src/main/java/org/apache/sling/commons/json/io/JSONStringer.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package org.apache.sling.commons.json.io;
-
-/*
-Copyright (c) 2006 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-import java.io.StringWriter;
-
-
-/**
- * JSONStringer provides a quick and convenient way of producing JSON text.
- * The texts produced strictly conform to JSON syntax rules. No whitespace is
- * added, so the results are ready for transmission or storage. Each instance of
- * JSONStringer can produce one JSON text.
- * <p>
- * A JSONStringer instance provides a <code>value</code> method for appending
- * values to the
- * text, and a <code>key</code>
- * method for adding keys before values in objects. There are <code>array</code>
- * and <code>endArray</code> methods that make and bound array values, and
- * <code>object</code> and <code>endObject</code> methods which make and bound
- * object values. All of these methods return the JSONWriter instance,
- * permitting cascade style. For example, <pre>
- * myString = new JSONStringer()
- * .object()
- * .key("JSON")
- * .value("Hello, World!")
- * .endObject()
- * .toString();</pre> which produces the string <pre>
- * {"JSON":"Hello, World!"}</pre>
- * <p>
- * The first method called must be <code>array</code> or <code>object</code>.
- * There are no methods for adding commas or colons. JSONStringer adds them for
- * you. Objects and arrays can be nested up to 20 levels deep.
- * <p>
- * This can sometimes be easier than using a JSONObject to build a string.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class JSONStringer extends JSONWriter {
- /**
- * Make a fresh JSONStringer. It can be used to build one JSON text.
- */
- public JSONStringer() {
- super(new StringWriter());
- }
-
- /**
- * Return the JSON text. This method is used to obtain the product of the
- * JSONStringer instance. It will return <code>null</code> if there was a
- * problem in the construction of the JSON text (such as the calls to
- * <code>array</code> were not properly balanced with calls to
- * <code>endArray</code>).
- * @return The JSON text.
- */
- public String toString() {
- return this.mode == 'd' ? this.writer.toString() : null;
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/io/JSONWriter.java b/src/main/java/org/apache/sling/commons/json/io/JSONWriter.java
deleted file mode 100644
index 2b1a1c3..0000000
--- a/src/main/java/org/apache/sling/commons/json/io/JSONWriter.java
+++ /dev/null
@@ -1,445 +0,0 @@
-package org.apache.sling.commons.json.io;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Iterator;
-
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-
-/*
-Copyright (c) 2006 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-/**
- * JSONWriter provides a quick and convenient way of producing JSON text.
- * The texts produced strictly conform to JSON syntax rules. No whitespace is
- * added, so the results are ready for transmission or storage. Each instance of
- * JSONWriter can produce one JSON text.
- * <p>
- * A JSONWriter instance provides a <code>value</code> method for appending
- * values to the
- * text, and a <code>key</code>
- * method for adding keys before values in objects. There are <code>array</code>
- * and <code>endArray</code> methods that make and bound array values, and
- * <code>object</code> and <code>endObject</code> methods which make and bound
- * object values. All of these methods return the JSONWriter instance,
- * permitting a cascade style. For example, <pre>
- * new JSONWriter(myWriter)
- * .object()
- * .key("JSON")
- * .value("Hello, World!")
- * .endObject();</pre> which writes <pre>
- * {"JSON":"Hello, World!"}</pre>
- * <p>
- * The first method called must be <code>array</code> or <code>object</code>.
- * There are no methods for adding commas or colons. JSONWriter adds them for
- * you. Objects and arrays can be nested up to 20 levels deep.
- * <p>
- * This can sometimes be easier than using a JSONObject to build a string.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class JSONWriter {
-
- // This was previously 20 - increased while creating
- // the JsonRenderingTest.testRecursiveInfinity test
- private static final int maxdepth = 50;
-
- /**
- * indentations
- */
- private static final String[] INDENTS = new String[maxdepth];
- static {
- StringBuffer indent = new StringBuffer();
- for (int i=0; i<INDENTS.length; i++) {
- INDENTS[i] = indent.toString();
- indent.append(" ");
- }
- }
-
- /**
- * flag indicates that output should be nicely formatted
- */
- private boolean tidy;
-
- /**
- * The comma flag determines if a comma should be output before the next
- * value.
- */
- private boolean comma;
-
- /**
- * The current mode. Values:
- * 'a' (array),
- * 'd' (done),
- * 'i' (initial),
- * 'k' (key),
- * 'o' (object).
- */
- protected char mode;
-
- /**
- * The object/array stack.
- */
- private char stack[];
-
- /**
- * The stack top index. A value of 0 indicates that the stack is empty.
- */
- private int top;
-
- /**
- * The writer that will receive the output.
- */
- protected Writer writer;
-
- /**
- * Make a fresh JSONWriter. It can be used to build one JSON text.
- */
- public JSONWriter(Writer w) {
- this.comma = false;
- this.mode = 'i';
- this.stack = new char[maxdepth];
- this.top = 0;
- this.writer = w;
- }
-
- /**
- * Checks if the output is nicely formatted.
- * @return <code>true</code> if nicely formatted
- */
- public boolean isTidy() {
- return tidy;
- }
-
- /**
- * Controls if output should be nicely formatted.
- * @param tidy <code>true</code> to nicely format.
- */
- public void setTidy(boolean tidy) {
- this.tidy = tidy;
- }
-
- /**
- * Append a value.
- * @param s A string value.
- * @return this
- * @throws JSONException If the value is out of sequence.
- */
- private JSONWriter append(String s) throws JSONException {
- if (s == null) {
- throw new JSONException("Null pointer");
- }
- if (this.mode == 'o' || this.mode == 'a') {
- try {
- if (this.comma && this.mode == 'a') {
- this.writer.write(',');
- }
- if (tidy && this.mode == 'a' && !"{".equals(s) && !"[".equals(s)) {
- this.writer.write('\n');
- this.writer.write(INDENTS[top]);
- }
- this.writer.write(s);
- } catch (IOException e) {
- throw new JSONException(e);
- }
- if (this.mode == 'o') {
- this.mode = 'k';
- }
- this.comma = true;
- return this;
- }
- throw new JSONException("Value out of sequence.");
- }
-
- /**
- * Begin appending a new array. All values until the balancing
- * <code>endArray</code> will be appended to this array. The
- * <code>endArray</code> method must be called to mark the array's end.
- * @return this
- * @throws JSONException If the nesting is too deep, or if the object is
- * started in the wrong place (for example as a key or after the end of the
- * outermost array or object).
- */
- public JSONWriter array() throws JSONException {
- if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
- this.push('a');
- this.append("[");
- this.comma = false;
- return this;
- }
- throw new JSONException("Misplaced array.");
- }
-
- /**
- * End something.
- * @param m Mode
- * @param c Closing character
- * @return this
- * @throws JSONException If unbalanced.
- */
- private JSONWriter end(char m, char c) throws JSONException {
- if (this.mode != m) {
- throw new JSONException(m == 'o' ? "Misplaced endObject." :
- "Misplaced endArray.");
- }
- this.pop(m);
- try {
- if (tidy) {
- this.writer.write('\n');
- this.writer.write(INDENTS[top]);
- }
- this.writer.write(c);
- } catch (IOException e) {
- throw new JSONException(e);
- }
- this.comma = true;
- return this;
- }
-
- /**
- * End an array. This method most be called to balance calls to
- * <code>array</code>.
- * @return this
- * @throws JSONException If incorrectly nested.
- */
- public JSONWriter endArray() throws JSONException {
- return this.end('a', ']');
- }
-
- /**
- * End an object. This method most be called to balance calls to
- * <code>object</code>.
- * @return this
- * @throws JSONException If incorrectly nested.
- */
- public JSONWriter endObject() throws JSONException {
- return this.end('k', '}');
- }
-
- /**
- * Append a key. The key will be associated with the next value. In an
- * object, every value must be preceded by a key.
- * @param s A key string.
- * @return this
- * @throws JSONException If the key is out of place. For example, keys
- * do not belong in arrays or if the key is null.
- */
- public JSONWriter key(String s) throws JSONException {
- if (s == null) {
- throw new JSONException("Null key.");
- }
- if (this.mode == 'k') {
- try {
- if (this.comma) {
- this.writer.write(',');
- }
- if (tidy) {
- this.writer.write('\n');
- this.writer.write(INDENTS[top]);
- }
- this.writer.write(JSONObject.quote(s));
- this.writer.write(':');
- if (tidy) {
- this.writer.write(' ');
- }
- this.comma = false;
- this.mode = 'o';
- return this;
- } catch (IOException e) {
- throw new JSONException(e);
- }
- }
- throw new JSONException("Misplaced key.");
- }
-
-
- /**
- * Begin appending a new object. All keys and values until the balancing
- * <code>endObject</code> will be appended to this object. The
- * <code>endObject</code> method must be called to mark the object's end.
- * @return this
- * @throws JSONException If the nesting is too deep, or if the object is
- * started in the wrong place (for example as a key or after the end of the
- * outermost array or object).
- */
- public JSONWriter object() throws JSONException {
- if (this.mode == 'i') {
- this.mode = 'o';
- }
- if (this.mode == 'o' || this.mode == 'a') {
- this.append("{");
- this.push('k');
- this.comma = false;
- return this;
- }
- throw new JSONException("Misplaced object.");
-
- }
-
-
- /**
- * Pop an array or object scope.
- * @param c The scope to close.
- * @throws JSONException If nesting is wrong.
- */
- private void pop(char c) throws JSONException {
- if (this.top <= 0 || this.stack[this.top - 1] != c) {
- throw new JSONException("Nesting error.");
- }
- this.top -= 1;
- this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1];
- }
-
- /**
- * Push an array or object scope.
- * @param c The scope to open.
- * @throws JSONException If nesting is too deep.
- */
- private void push(char c) throws JSONException {
- if (this.top >= maxdepth) {
- throw new JSONException("Nesting too deep (maximum is " + maxdepth + " levels)");
- }
- this.stack[this.top] = c;
- this.mode = c;
- this.top += 1;
- }
-
-
- /**
- * Append either the value <code>true</code> or the value
- * <code>false</code>.
- * @param b A boolean.
- * @return this
- * @throws JSONException
- */
- public JSONWriter value(boolean b) throws JSONException {
- return this.append(b ? "true" : "false");
- }
-
- /**
- * Append a double value.
- * @param d A double.
- * @return this
- * @throws JSONException If the number is not finite.
- */
- public JSONWriter value(double d) throws JSONException {
- return this.value(new Double(d));
- }
-
- /**
- * Append a long value.
- * @param l A long.
- * @return this
- * @throws JSONException
- */
- public JSONWriter value(long l) throws JSONException {
- return this.append(Long.toString(l));
- }
-
-
- /**
- * Append an object value.
- * @param o The object to append. It can be null, or a Boolean, Number,
- * String, JSONObject, or JSONArray, or an object with a toJSONString()
- * method.
- * @return this
- * @throws JSONException If the value is out of sequence.
- */
- public JSONWriter value(Object o) throws JSONException {
- return this.append(JSONObject.valueToString(o));
- }
-
- /**
- * Append a JSON Object
- *
- * @param o
- * @return
- * @throws JSONException
- */
- public JSONWriter writeObject(JSONObject o) throws JSONException {
- Iterator<String> keys = o.keys();
-
- this.object();
-
- while (keys.hasNext()) {
- String key = keys.next();
-
- this.key(key);
-
- JSONObject objVal = o.optJSONObject(key);
- if (objVal != null) {
- this.writeObject(objVal);
- continue;
- }
-
- JSONArray arrVal = o.optJSONArray(key);
- if (arrVal != null) {
- this.writeArray(arrVal);
- continue;
- }
-
- Object obj = o.opt(key);
- this.value(obj);
- }
-
- this.endObject();
-
- return this;
- }
-
- /**
- * Append a JSON Array
- *
- * @param a
- * @return
- * @throws JSONException
- */
- public JSONWriter writeArray(JSONArray a) throws JSONException {
- this.array();
-
- for (int i = 0; i < a.length(); i++) {
- JSONObject objVal = a.optJSONObject(i);
- if (objVal != null) {
- this.writeObject(objVal);
- continue;
- }
-
- JSONArray arrVal = a.optJSONArray(i);
- if (arrVal != null) {
- this.writeArray(arrVal);
- continue;
- }
-
- Object obj = a.opt(i);
- this.value(obj);
- }
-
- this.endArray();
-
- return this;
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/io/package-info.java b/src/main/java/org/apache/sling/commons/json/io/package-info.java
deleted file mode 100644
index e007c6f..0000000
--- a/src/main/java/org/apache/sling/commons/json/io/package-info.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-@Version("2.2.1")
-package org.apache.sling.commons.json.io;
-
-import org.osgi.annotation.versioning.Version;
diff --git a/src/main/java/org/apache/sling/commons/json/jcr/JsonItemWriter.java b/src/main/java/org/apache/sling/commons/json/jcr/JsonItemWriter.java
deleted file mode 100644
index dd6ca90..0000000
--- a/src/main/java/org/apache/sling/commons/json/jcr/JsonItemWriter.java
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.jcr;
-
-import java.io.Writer;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Locale;
-import java.util.Set;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Value;
-import javax.jcr.ValueFormatException;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.io.JSONWriter;
-
-/**
- * Dumps JCR Items as JSON data. The dump methods are threadsafe.
- */
-@Deprecated
-public class JsonItemWriter {
-
- private static DateFormat calendarFormat;
-
- private final Set<String> propertyNamesToIgnore;
-
- /** Used to format date values */
- public static final String ECMA_DATE_FORMAT = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
-
- /** Used to format date values */
- public static final Locale DATE_FORMAT_LOCALE = Locale.US;
-
-
- /**
- * Create a JsonItemWriter
- *
- * @param propertyNamesToIgnore if not null, a property having a name from
- * this set of values is ignored. TODO we should use a filtering
- * interface to make the selection of which Nodes and Properties
- * to dump more flexible.
- */
- public JsonItemWriter(Set<String> propertyNamesToIgnore) {
- this.propertyNamesToIgnore = propertyNamesToIgnore;
- }
-
- /**
- * Dump all Nodes of given NodeIterator in JSON
- *
- * @throws JSONException
- */
- public void dump(NodeIterator it, Writer out) throws RepositoryException,
- JSONException {
- final JSONWriter w = new JSONWriter(out);
- w.array();
- while (it.hasNext()) {
- dump(it.nextNode(), w, 1, 1);
- }
- w.endArray();
- }
-
- /** Dump given node in JSON, optionally recursing into its child nodes */
- public void dump(Node node, Writer w, int maxRecursionLevels)
- throws RepositoryException, JSONException {
- dump(node, w, maxRecursionLevels, false);
- }
-
- /**
- * Dump given node in JSON, optionally recursing into its child nodes
- * @param tidy if <code>true</code> the json dump is nicely formatted
- */
- public void dump(Node node, Writer w, int maxRecursionLevels, boolean tidy)
- throws RepositoryException, JSONException {
- JSONWriter jw = new JSONWriter(w);
- jw.setTidy(tidy);
- dump(node, jw, 0, maxRecursionLevels);
- }
-
- /** Dump given property in JSON */
- public void dump(Property p, Writer w) throws JSONException,
- ValueFormatException, RepositoryException {
- final JSONWriter jw = new JSONWriter(w);
- jw.object();
- writeProperty(jw, p);
- jw.endObject();
- }
-
- /** Dump given node in JSON, optionally recursing into its child nodes */
- protected void dump(Node node, JSONWriter w, int currentRecursionLevel,
- int maxRecursionLevels) throws RepositoryException, JSONException {
-
- w.object();
- PropertyIterator props = node.getProperties();
-
- // the node's actual properties
- while (props.hasNext()) {
- Property prop = props.nextProperty();
-
- if (propertyNamesToIgnore != null
- && propertyNamesToIgnore.contains(prop.getName())) {
- continue;
- }
-
- writeProperty(w, prop);
- }
-
- // the child nodes
- if (recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
- final NodeIterator children = node.getNodes();
- while (children.hasNext()) {
- final Node n = children.nextNode();
- dumpSingleNode(n, w, currentRecursionLevel, maxRecursionLevels);
- }
- }
-
- w.endObject();
- }
-
- /** Dump a single node */
- protected void dumpSingleNode(Node n, JSONWriter w,
- int currentRecursionLevel, int maxRecursionLevels)
- throws RepositoryException, JSONException {
- if (recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
- w.key(n.getName());
- dump(n, w, currentRecursionLevel + 1, maxRecursionLevels);
- }
- }
-
- /** true if the current recursion level is active */
- protected boolean recursionLevelActive(int currentRecursionLevel,
- int maxRecursionLevels) {
- return maxRecursionLevels < 0
- || currentRecursionLevel < maxRecursionLevels;
- }
-
- /**
- * Write a single property
- */
- protected void writeProperty(JSONWriter w, Property p)
- throws ValueFormatException, RepositoryException, JSONException {
- // special handling for binaries: we dump the length and not the length
- if (p.getType() == PropertyType.BINARY) {
- // TODO for now we mark binary properties with an initial colon in
- // their name
- // (colon is not allowed as a JCR property name)
- // in the name, and the value should be the size of the binary data
- w.key(":" + p.getName());
- if (!p.isMultiple()) {
- w.value(p.getLength());
- } else {
- final long[] sizes = p.getLengths();
- w.array();
- for (int i = 0; i < sizes.length; i++) {
- w.value(sizes[i]);
- }
- w.endArray();
- }
- return;
- }
- w.key(p.getName());
-
- if (!p.isMultiple()) {
- dumpValue(w, p.getValue());
- } else {
- w.array();
- for (Value v : p.getValues()) {
- dumpValue(w, v);
- }
- w.endArray();
- }
- }
-
- /**
- * Writes the given value to the JSON writer. currently the following
- * conversions are done: <table><caption></caption>
- * <tr>
- * <th>JSR Property Type</th>
- * <th>JSON Value Type</th>
- * </tr>
- * <tr>
- * <td>BINARY</td>
- * <td>always 0 as long</td>
- * </tr>
- * <tr>
- * <td>DATE</td>
- * <td>converted date string as defined by ECMA</td>
- * </tr>
- * <tr>
- * <td>BOOLEAN</td>
- * <td>boolean</td>
- * </tr>
- * <tr>
- * <td>LONG</td>
- * <td>long</td>
- * </tr>
- * <tr>
- * <td>DOUBLE</td>
- * <td>double</td>
- * </tr>
- * <tr>
- * <td><i>all other</i>
- * </td>
- * <td>string</td>
- * </tr>
- * </table> <sup>1</sup> Currently not implemented and uses 0 as default.
- *
- * @param w json writer
- * @param v value to dump
- */
- protected void dumpValue(JSONWriter w, Value v)
- throws ValueFormatException, IllegalStateException,
- RepositoryException, JSONException {
-
- switch (v.getType()) {
- case PropertyType.BINARY:
- w.value(0);
- break;
-
- case PropertyType.DATE:
- w.value(format(v.getDate()));
- break;
-
- case PropertyType.BOOLEAN:
- w.value(v.getBoolean());
- break;
-
- case PropertyType.LONG:
- w.value(v.getLong());
- break;
-
- case PropertyType.DOUBLE:
- w.value(v.getDouble());
-
- break;
- default:
- w.value(v.getString());
- }
- }
-
- public static synchronized String format(Calendar date) {
- if (calendarFormat == null) {
- calendarFormat = new SimpleDateFormat(ECMA_DATE_FORMAT, DATE_FORMAT_LOCALE);
- }
- return calendarFormat.format(date.getTime());
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/jcr/JsonJcrNode.java b/src/main/java/org/apache/sling/commons/json/jcr/JsonJcrNode.java
deleted file mode 100644
index 02df934..0000000
--- a/src/main/java/org/apache/sling/commons/json/jcr/JsonJcrNode.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.jcr;
-
-import org.apache.sling.commons.json.JSONObject;
-import org.apache.sling.commons.json.JSONException;
-
-import javax.jcr.Node;
-import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
-import javax.jcr.PropertyType;
-import javax.jcr.RepositoryException;
-import javax.jcr.Value;
-import javax.jcr.ValueFormatException;
-import java.util.Set;
-import java.util.List;
-import java.util.ArrayList;
-
-/**
- * This class makes it easy to create a JSON object out of a JCR node. It is a shameless copy of {@link JsonItemWriter},
- * but instead of writing the resulting JSON directly to an output, you get a JSONObject that you can deal with.
- *
- * @author vidar@idium.no
- * @since Apr 17, 2009 6:55:30 PM
- */
-@Deprecated
-public class JsonJcrNode extends JSONObject {
-
- private Node node;
- private Set<String> propertyNamesToIgnore;
-
- /**
- * Creates a JSONObject out of <code>node</code>. All <code>node</code>'s properties will be reflected in the JSON
- * object. In addition, properties <code>jcr:path</code> and <code>jcr:name</code> are added. Their values are
- * those returned by <code>node.getPath()</code> and <code>node.getName()</code>, respectively.
- * @param node The JCR node to use
- * @throws JSONException If there's a problem generating the JSON object
- * @throws RepositoryException If there's a problem reading data from the JCR repository
- */
- public JsonJcrNode(Node node) throws JSONException, RepositoryException {
- this(node, null);
- }
-
- /**
- * Creates a <code>JSONObject</code> out of <code>node</code>. All <code>node</code>'s properties will be reflected
- * in the JSON object, except those in <code>propertyNamesToIgnore</code>. In addition, properties
- * <code>jcr:path</code> and <code>jcr:name</code> are added. Their values are those returned by
- * <code>node.getPath()</code> and <code>node.getName()</code>, respectively.
- * @param node The JCR node to use
- * @param propertyNamesToIgnore A set of property names that should <em>not</em> be reflected in the resulting
- * JSON object.
- * @throws JSONException If there's a problem generating the JSON object
- * @throws RepositoryException If there's a problem reading data from the JCR repository
- */
- public JsonJcrNode(Node node, Set<String> propertyNamesToIgnore) throws JSONException, RepositoryException {
- this.node = node;
- this.propertyNamesToIgnore = propertyNamesToIgnore;
- this.populate();
- }
-
- private void populate() throws JSONException, RepositoryException {
- PropertyIterator properties = node.getProperties();
- addNative("jcr:path", node.getPath());
- addNative("jcr:name", node.getName());
- while (properties.hasNext()) {
- Property prop = properties.nextProperty();
- String name = prop.getName();
- if (propertyNamesToIgnore != null && propertyNamesToIgnore.contains(name)) {
- continue;
- }
- addProperty(prop);
- }
- }
-
- private void addNative(String key, String value) throws JSONException, RepositoryException {
- if (propertyNamesToIgnore == null || !propertyNamesToIgnore.contains(key)) {
- this.put(key, value);
- }
- }
-
- protected void addProperty(Property p)
- throws ValueFormatException, RepositoryException, JSONException {
- // special handling for binaries: we dump the length and not the length
- if (p.getType() == PropertyType.BINARY) {
- // TODO for now we mark binary properties with an initial colon in
- // their name
- // (colon is not allowed as a JCR property name)
- // in the name, and the value should be the size of the binary data
- String key = ":" + p.getName();
- if (!p.isMultiple()) {
- this.put(key, p.getLength());
- } else {
- final long[] sizes = p.getLengths();
- List<Long> list = new ArrayList<Long>();
- for (long value : sizes) {
- list.add(value);
- }
- this.put(key, list);
- }
- } else {
- String key = p.getName();
-
- if (!p.isMultiple()) {
- addValue(key, p.getValue());
- } else {
- for (Value v : p.getValues()) {
- addValue(key, v);
- }
- }
- }
- }
-
- protected void addValue(String key, Value v) throws IllegalStateException, RepositoryException, JSONException {
-
- switch (v.getType()) {
- case PropertyType.BINARY:
- this.accumulate(key, 0);
- break;
-
- case PropertyType.DATE:
- this.accumulate(key, JsonItemWriter.format(v.getDate()));
- break;
-
- case PropertyType.BOOLEAN:
- this.accumulate(key, v.getBoolean());
- break;
-
- case PropertyType.LONG:
- this.accumulate(key, v.getLong());
- break;
-
- case PropertyType.DOUBLE:
- this.accumulate(key, v.getDouble());
- break;
- default:
- this.accumulate(key, v.getString());
- }
- }
-
-
-}
diff --git a/src/main/java/org/apache/sling/commons/json/jcr/package-info.java b/src/main/java/org/apache/sling/commons/json/jcr/package-info.java
deleted file mode 100644
index 7e5fc96..0000000
--- a/src/main/java/org/apache/sling/commons/json/jcr/package-info.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-@Version("2.0.5")
-package org.apache.sling.commons.json.jcr;
-
-import org.osgi.annotation.versioning.Version;
diff --git a/src/main/java/org/apache/sling/commons/json/package-info.java b/src/main/java/org/apache/sling/commons/json/package-info.java
deleted file mode 100644
index a775301..0000000
--- a/src/main/java/org/apache/sling/commons/json/package-info.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-@Version("2.0.5")
-package org.apache.sling.commons.json;
-
-import org.osgi.annotation.versioning.Version;
diff --git a/src/main/java/org/apache/sling/commons/json/sling/JsonObjectCreator.java b/src/main/java/org/apache/sling/commons/json/sling/JsonObjectCreator.java
deleted file mode 100644
index 302493a..0000000
--- a/src/main/java/org/apache/sling/commons/json/sling/JsonObjectCreator.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.sling;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.Array;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Map;
-
-import org.apache.sling.api.resource.Resource;
-import org.apache.sling.api.resource.ResourceUtil;
-import org.apache.sling.api.resource.ValueMap;
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-
-/**
- * Creates a JSONObject from a resource
- *
- */
-@Deprecated
-public abstract class JsonObjectCreator {
-
- /**
- * Dump given resource in JSON, optionally recursing into its objects
- */
- public static JSONObject create(final Resource resource, final int maxRecursionLevels)
- throws JSONException {
- return create(resource, 0, maxRecursionLevels);
- }
-
-
- /** Dump given resource in JSON, optionally recursing into its objects */
- private static JSONObject create(final Resource resource,
- final int currentRecursionLevel,
- final int maxRecursionLevels)
- throws JSONException {
- final ValueMap valueMap = resource.adaptTo(ValueMap.class);
-
- final Map propertyMap = (valueMap != null)
- ? valueMap
- : resource.adaptTo(Map.class);
-
- final JSONObject obj = new JSONObject();
-
- if (propertyMap == null) {
-
- // no map available, try string
- final String value = resource.adaptTo(String.class);
- if (value != null) {
-
- // single value property or just plain String resource or...
- obj.put(ResourceUtil.getName(resource), value);
-
- } else {
-
- // Try multi-value "property"
- final String[] values = resource.adaptTo(String[].class);
- if (values != null) {
- obj.put(ResourceUtil.getName(resource), new JSONArray(Arrays.asList(values)));
- }
-
- }
-
- } else {
-
- @SuppressWarnings("unchecked")
- final Iterator<Map.Entry> props = propertyMap.entrySet().iterator();
-
- // the node's actual properties
- while (props.hasNext()) {
- final Map.Entry prop = props.next();
-
- if ( prop.getValue() != null ) {
- createProperty(obj, valueMap, prop.getKey().toString(),
- prop.getValue());
- }
- }
- }
-
- // the child nodes
- if (recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
- final Iterator<Resource> children = ResourceUtil.listChildren(resource);
- while (children.hasNext()) {
- final Resource n = children.next();
- createSingleResource(n, obj, currentRecursionLevel,
- maxRecursionLevels);
- }
- }
-
- return obj;
- }
-
- /** Used to format date values */
- private static final String ECMA_DATE_FORMAT = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
-
- /** The Locale used to format date values */
- static final Locale DATE_FORMAT_LOCALE = Locale.US;
-
-
- private static String format(final Calendar date) {
- DateFormat formatter = new SimpleDateFormat(ECMA_DATE_FORMAT, DATE_FORMAT_LOCALE);
- formatter.setTimeZone(date.getTimeZone());
- return formatter.format(date.getTime());
- }
-
- /** Dump only a value in the correct format */
- private static Object getValue(final Object value) {
- if ( value instanceof InputStream ) {
- // input stream is already handled
- return 0;
- } else if ( value instanceof Calendar ) {
- return format((Calendar)value);
- } else if ( value instanceof Boolean ) {
- return value;
- } else if ( value instanceof Long ) {
- return value;
- } else if ( value instanceof Integer ) {
- return value;
- } else if ( value instanceof Double ) {
- return value;
- } else if ( value != null ) {
- return value.toString();
- } else {
- return ""; // assume empty string
- }
- }
-
- /** Dump a single node */
- private static void createSingleResource(final Resource n, final JSONObject parent,
- final int currentRecursionLevel, final int maxRecursionLevels)
- throws JSONException {
- if (recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
- parent.put(ResourceUtil.getName(n), create(n, currentRecursionLevel + 1, maxRecursionLevels));
- }
- }
-
- /** true if the current recursion level is active */
- private static boolean recursionLevelActive(final int currentRecursionLevel,
- final int maxRecursionLevels) {
- return maxRecursionLevels < 0
- || currentRecursionLevel < maxRecursionLevels;
- }
-
- /**
- * Write a single property
- */
- private static void createProperty(final JSONObject obj,
- final ValueMap valueMap,
- final String key,
- final Object value)
- throws JSONException {
- Object[] values = null;
- if (value.getClass().isArray()) {
- final int length = Array.getLength(value);
- // write out empty array
- if ( length == 0 ) {
- obj.put(key, new JSONArray());
- return;
- }
- values = new Object[Array.getLength(value)];
- for(int i=0; i<length; i++) {
- values[i] = Array.get(value, i);
- }
- }
-
- // special handling for binaries: we dump the length and not the data!
- if (value instanceof InputStream
- || (values != null && values[0] instanceof InputStream)) {
- // TODO for now we mark binary properties with an initial colon in
- // their name
- // (colon is not allowed as a JCR property name)
- // in the name, and the value should be the size of the binary data
- if (values == null) {
- obj.put(":" + key, getLength(valueMap, -1, key, (InputStream)value));
- } else {
- final JSONArray result = new JSONArray();
- for (int i = 0; i < values.length; i++) {
- result.put(getLength(valueMap, i, key, (InputStream)values[i]));
- }
- obj.put(":" + key, result);
- }
- return;
- }
-
- if (!value.getClass().isArray()) {
- obj.put(key, getValue(value));
- } else {
- final JSONArray result = new JSONArray();
- for (Object v : values) {
- result.put(getValue(v));
- }
- obj.put(key, result);
- }
- }
-
- private static long getLength(final ValueMap valueMap,
- final int index,
- final String key,
- final InputStream stream) {
- try {
- stream.close();
- } catch (IOException ignore) {}
- long length = -1;
- if ( valueMap != null ) {
- if ( index == -1 ) {
- length = valueMap.get(key, length);
- } else {
- Long[] lengths = valueMap.get(key, Long[].class);
- if ( lengths != null && lengths.length > index ) {
- length = lengths[index];
- }
- }
- }
- return length;
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/sling/ResourceTraversor.java b/src/main/java/org/apache/sling/commons/json/sling/ResourceTraversor.java
deleted file mode 100644
index d0cb2c9..0000000
--- a/src/main/java/org/apache/sling/commons/json/sling/ResourceTraversor.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.sling.commons.json.sling;
-
-import java.util.Iterator;
-import java.util.LinkedList;
-
-import org.apache.sling.api.request.RecursionTooDeepException;
-import org.apache.sling.api.resource.Resource;
-import org.apache.sling.api.resource.ResourceUtil;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-
-@Deprecated
-public class ResourceTraversor {
-
- public static final class Entry {
- public final Resource resource;
- public final JSONObject json;
-
- public Entry(final Resource r, final JSONObject o) {
- this.resource = r;
- this.json = o;
- }
- }
-
- private long count;
-
- private long maxResources;
-
- private final int maxRecursionLevels;
-
- private final JSONObject startObject;
-
- private LinkedList<Entry> currentQueue;
-
- private LinkedList<Entry> nextQueue;
-
- private final Resource startResource;
-
- /** Create a ResourceTraversor, optionally limiting recursion and total number of resources
- * @param levels recursion levels limit, -1 means no limit
- * @param maxResources maximum number of resources to collect, ignored if levels == 1
- * @param resource the root resource to traverse
- * @param tidy not used
- * @throws JSONException
- */
- public ResourceTraversor(final int levels, final long maxResources, final Resource resource, final boolean tidy)
- throws JSONException {
- this.maxResources = maxResources;
- this.maxRecursionLevels = levels;
- this.startResource = resource;
- currentQueue = new LinkedList<Entry>();
- nextQueue = new LinkedList<Entry>();
- this.startObject = this.adapt(resource);
- }
-
- /**
- * Recursive descent from startResource, collecting JSONObjects into
- * startObject. Throws a RecursionTooDeepException if the maximum number of
- * nodes is reached on a "deep" traversal (where "deep" === level greater
- * than 1).
- *
- * @return -1 if everything went fine, a positive valuew when the resource
- * has more child nodes then allowed.
- * @throws JSONException
- */
- public int collectResources() throws RecursionTooDeepException, JSONException {
- return collectChildren(startResource, this.startObject, 0);
- }
-
- /**
- * @param resource
- * @param currentLevel
- * @throws JSONException
- */
- private int collectChildren(final Resource resource,
- final JSONObject jsonObj,
- int currentLevel)
- throws JSONException {
-
- if (maxRecursionLevels == -1 || currentLevel < maxRecursionLevels) {
- final Iterator<Resource> children = ResourceUtil.listChildren(resource);
- while (children.hasNext()) {
- count++;
- final Resource res = children.next();
- // SLING-2320: always allow enumeration of one's children;
- // DOS-limitation is for deeper traversals.
- if (count > maxResources && maxRecursionLevels != 1) {
- return currentLevel;
- }
- final JSONObject json = collectResource(res, jsonObj);
- nextQueue.addLast(new Entry(res, json));
- }
- }
-
- // do processing only at first level to avoid unnecessary recursion
- if (currentLevel > 0) {
- return -1;
- }
-
- while (!currentQueue.isEmpty() || !nextQueue.isEmpty()) {
- if (currentQueue.isEmpty()) {
- currentLevel++;
- currentQueue = nextQueue;
- nextQueue = new LinkedList<Entry>();
- }
- final Entry nextResource = currentQueue.removeFirst();
- final int maxLevel = collectChildren(nextResource.resource, nextResource.json, currentLevel);
- if ( maxLevel != -1 ) {
- return maxLevel;
- }
- }
- return -1;
- }
-
- /**
- * Adds a resource in the JSON tree.
- *
- * @param resource The resource to add
- * @param level The level where this resource is located.
- * @throws JSONException
- */
- private JSONObject collectResource(Resource resource, final JSONObject parent)
- throws JSONException {
- final JSONObject o = adapt(resource);
- parent.put(ResourceUtil.getName(resource), o);
- return o;
- }
-
- /**
- * Adapt a Resource to a JSON Object.
- *
- * @param resource The resource to adapt.
- * @return The JSON representation of the Resource
- * @throws JSONException
- */
- private JSONObject adapt(final Resource resource) throws JSONException {
- return JsonObjectCreator.create(resource, 0);
- }
-
- /**
- * @return The number of resources this visitor found.
- */
- public long getCount() {
- return count;
- }
-
- public JSONObject getJSONObject() {
- return startObject;
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/sling/package-info.java b/src/main/java/org/apache/sling/commons/json/sling/package-info.java
deleted file mode 100644
index 5d15b9e..0000000
--- a/src/main/java/org/apache/sling/commons/json/sling/package-info.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-@Version("1.0.1")
-package org.apache.sling.commons.json.sling;
-
-import org.osgi.annotation.versioning.Version;
diff --git a/src/main/java/org/apache/sling/commons/json/util/CDL.java b/src/main/java/org/apache/sling/commons/json/util/CDL.java
deleted file mode 100644
index f06223b..0000000
--- a/src/main/java/org/apache/sling/commons/json/util/CDL.java
+++ /dev/null
@@ -1,267 +0,0 @@
-package org.apache.sling.commons.json.util;
-
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.apache.sling.commons.json.JSONTokener;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-/**
- * This provides static methods to convert comma delimited text into a
- * JSONArray, and to covert a JSONArray into comma delimited text. Comma
- * delimited text is a very popular format for data interchange. It is
- * understood by most database, spreadsheet, and organizer programs.
- * <p>
- * Each row of text represents a row in a table or a data record. Each row
- * ends with a NEWLINE character. Each row contains one or more values.
- * Values are separated by commas. A value can contain any character except
- * for comma, unless is is wrapped in single quotes or double quotes.
- * <p>
- * The first row usually contains the names of the columns.
- * <p>
- * A comma delimited list can be converted into a JSONArray of JSONObjects.
- * The names for the elements in the JSONObjects can be taken from the names
- * in the first row.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class CDL {
-
- /**
- * Get the next value. The value can be wrapped in quotes. The value can
- * be empty.
- * @param x A JSONTokener of the source text.
- * @return The value string, or null if empty.
- * @throws JSONException if the quoted string is badly formed.
- */
- private static String getValue(JSONTokener x) throws JSONException {
- char c;
- do {
- c = x.next();
- } while (c <= ' ' && c != 0);
- switch (c) {
- case 0:
- return null;
- case '"':
- case '\'':
- return x.nextString(c);
- case ',':
- x.back();
- return "";
- default:
- x.back();
- return x.nextTo(',');
- }
- }
-
- /**
- * Produce a JSONArray of strings from a row of comma delimited values.
- * @param x A JSONTokener of the source text.
- * @return A JSONArray of strings.
- * @throws JSONException
- */
- public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
- JSONArray ja = new JSONArray();
- for (;;) {
- String value = getValue(x);
- if (value == null) {
- return null;
- }
- ja.put(value);
- for (;;) {
- char c = x.next();
- if (c == ',') {
- break;
- }
- if (c != ' ') {
- if (c == '\n' || c == '\r' || c == 0) {
- return ja;
- }
- throw x.syntaxError("Bad character '" + c + "' (" +
- (int)c + ").");
- }
- }
- }
- }
-
- /**
- * Produce a JSONObject from a row of comma delimited text, using a
- * parallel JSONArray of strings to provides the names of the elements.
- * @param names A JSONArray of names. This is commonly obtained from the
- * first row of a comma delimited text file using the rowToJSONArray
- * method.
- * @param x A JSONTokener of the source text.
- * @return A JSONObject combining the names and values.
- * @throws JSONException
- */
- public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
- throws JSONException {
- JSONArray ja = rowToJSONArray(x);
- return ja != null ? ja.toJSONObject(names) : null;
- }
-
- /**
- * Produce a JSONArray of JSONObjects from a comma delimited text string,
- * using the first row as a source of names.
- * @param string The comma delimited text.
- * @return A JSONArray of JSONObjects.
- * @throws JSONException
- */
- public static JSONArray toJSONArray(String string) throws JSONException {
- return toJSONArray(new JSONTokener(string));
- }
-
- /**
- * Produce a JSONArray of JSONObjects from a comma delimited text string,
- * using the first row as a source of names.
- * @param x The JSONTokener containing the comma delimited text.
- * @return A JSONArray of JSONObjects.
- * @throws JSONException
- */
- public static JSONArray toJSONArray(JSONTokener x) throws JSONException {
- return toJSONArray(rowToJSONArray(x), x);
- }
-
- /**
- * Produce a JSONArray of JSONObjects from a comma delimited text string
- * using a supplied JSONArray as the source of element names.
- * @param names A JSONArray of strings.
- * @param string The comma delimited text.
- * @return A JSONArray of JSONObjects.
- * @throws JSONException
- */
- public static JSONArray toJSONArray(JSONArray names, String string)
- throws JSONException {
- return toJSONArray(names, new JSONTokener(string));
- }
-
- /**
- * Produce a JSONArray of JSONObjects from a comma delimited text string
- * using a supplied JSONArray as the source of element names.
- * @param names A JSONArray of strings.
- * @param x A JSONTokener of the source text.
- * @return A JSONArray of JSONObjects.
- * @throws JSONException
- */
- public static JSONArray toJSONArray(JSONArray names, JSONTokener x)
- throws JSONException {
- if (names == null || names.length() == 0) {
- return null;
- }
- JSONArray ja = new JSONArray();
- for (;;) {
- JSONObject jo = rowToJSONObject(names, x);
- if (jo == null) {
- break;
- }
- ja.put(jo);
- }
- if (ja.length() == 0) {
- return null;
- }
- return ja;
- }
-
-
- /**
- * Produce a comma delimited text row from a JSONArray. Values containing
- * the comma character will be quoted.
- * @param ja A JSONArray of strings.
- * @return A string ending in NEWLINE.
- */
- public static String rowToString(JSONArray ja) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < ja.length(); i += 1) {
- if (i > 0) {
- sb.append(',');
- }
- Object o = ja.opt(i);
- if (o != null) {
- String s = o.toString();
- if (s.indexOf(',') >= 0) {
- if (s.indexOf('"') >= 0) {
- sb.append('\'');
- sb.append(s);
- sb.append('\'');
- } else {
- sb.append('"');
- sb.append(s);
- sb.append('"');
- }
- } else {
- sb.append(s);
- }
- }
- }
- sb.append('\n');
- return sb.toString();
-
- }
-
- /**
- * Produce a comma delimited text from a JSONArray of JSONObjects. The
- * first row will be a list of names obtained by inspecting the first
- * JSONObject.
- * @param ja A JSONArray of JSONObjects.
- * @return A comma delimited text.
- * @throws JSONException
- */
- public static String toString(JSONArray ja) throws JSONException {
- JSONObject jo = ja.optJSONObject(0);
- if (jo != null) {
- JSONArray names = jo.names();
- if (names != null) {
- return rowToString(names) + toString(names, ja);
- }
- }
- return null;
- }
-
- /**
- * Produce a comma delimited text from a JSONArray of JSONObjects using
- * a provided list of names. The list of names is not included in the
- * output.
- * @param names A JSONArray of strings.
- * @param ja A JSONArray of JSONObjects.
- * @return A comma delimited text.
- * @throws JSONException
- */
- public static String toString(JSONArray names, JSONArray ja)
- throws JSONException {
- if (names == null || names.length() == 0) {
- return null;
- }
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < ja.length(); i += 1) {
- JSONObject jo = ja.optJSONObject(i);
- if (jo != null) {
- sb.append(rowToString(jo.toJSONArray(names)));
- }
- }
- return sb.toString();
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/util/Validator.java b/src/main/java/org/apache/sling/commons/json/util/Validator.java
deleted file mode 100644
index 20a82d0..0000000
--- a/src/main/java/org/apache/sling/commons/json/util/Validator.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.util;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONTokener;
-
-/**
- * Utility class for validating JSON text.
- */
-@Deprecated
-public class Validator {
-
- /**
- * Strictly validate the JSON text
- * @param text The text to check.
- * @throws JSONException If the text is not valid.
- */
- public static void validate(final String text) throws JSONException {
- JSONTokener x = new JSONTokener(text);
- validate(x);
-
- // make sure nothing more is present after last array or object
- char c = x.nextClean();
- if ( c != 0 ) {
- throw x.syntaxError("Unexpected '" + c + "' at end of file.");
- }
- }
-
- /**
- * Strictly validate the JSON text
- * @param x The tokener to check.
- * @throws JSONException If the text is not valid.
- */
- public static void validate(JSONTokener x) throws JSONException {
- char c = x.nextClean();
- if ( c == 0 ) {
- // no tokens at all - we consider this valid
- return;
- } else if (c == '[') {
- char nextChar = x.nextClean();
- if (nextChar == ']') {
- return;
- }
- else if (nextChar == 0) {
- throw x.syntaxError("Detected unclosed array.");
- }
- x.back();
- for (;;) {
- if (x.nextClean() == ',') {
- x.back();
- } else {
- x.back();
- c = x.nextClean();
- x.back();
- if ( c == '{' || c == '[') {
- // recursive validation for object and array
- validate(x);
- } else {
- x.nextValue();
- }
- }
- switch (x.nextClean()) {
- case ',': if (x.nextClean() == ']') {
- throw x.syntaxError("Trailing separator ',' in array.");
- }
- x.back();
- break;
- case ']': return;
- default: throw x.syntaxError("Expected a ',' or ']'");
- }
- }
- } else if ( c == '{') {
- final Set<String> keys = new HashSet<String>();
- for (;;) {
- String key;
- c = x.nextClean();
- switch (c) {
- case 0 : throw x.syntaxError("A JSONObject text must end with '}'");
- case '}': return;
- default : x.back();
- key = x.nextValue().toString();
- }
-
- c = x.nextClean();
- if (c != ':') {
- throw x.syntaxError("Expected a ':' after a key");
- }
- if ( keys.contains(key) ) {
- throw x.syntaxError("JSONObject contains key '" + key + "' multiple times.");
- }
- keys.add(key);
- // get the value
- c = x.nextClean();
- x.back();
- if ( c == '{' || c == '[') {
- // recursiv validation for object and array
- validate(x);
- } else {
- x.nextValue();
- }
-
- switch (x.nextClean()) {
- case ',': if (x.nextClean() == '}') {
- throw x.syntaxError("Trailing separator ',' in object.");
- }
- x.back();
- break;
- case '}': return;
- default: throw x.syntaxError("Expected a ',' or '}'");
- }
- }
-
- } else {
- throw x.syntaxError("A JSON text must begin with '{' (for an object) or '[' (for an array).");
- }
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/util/package-info.java b/src/main/java/org/apache/sling/commons/json/util/package-info.java
deleted file mode 100644
index 6123868..0000000
--- a/src/main/java/org/apache/sling/commons/json/util/package-info.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-@Version("2.0.5")
-package org.apache.sling.commons.json.util;
-
-import org.osgi.annotation.versioning.Version;
diff --git a/src/main/java/org/apache/sling/commons/json/xml/XML.java b/src/main/java/org/apache/sling/commons/json/xml/XML.java
deleted file mode 100644
index 9373dd1..0000000
--- a/src/main/java/org/apache/sling/commons/json/xml/XML.java
+++ /dev/null
@@ -1,406 +0,0 @@
-package org.apache.sling.commons.json.xml;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-import java.util.Iterator;
-
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-
-
-/**
- * This provides static methods to convert an XML text into a JSONObject,
- * and to covert a JSONObject into an XML text.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class XML {
-
- /** The Character '&'. */
- public static final Character AMP = new Character('&');
-
- /** The Character '''. */
- public static final Character APOS = new Character('\'');
-
- /** The Character '!'. */
- public static final Character BANG = new Character('!');
-
- /** The Character '='. */
- public static final Character EQ = new Character('=');
-
- /** The Character '>'. */
- public static final Character GT = new Character('>');
-
- /** The Character '<'. */
- public static final Character LT = new Character('<');
-
- /** The Character '?'. */
- public static final Character QUEST = new Character('?');
-
- /** The Character '"'. */
- public static final Character QUOT = new Character('"');
-
- /** The Character '/'. */
- public static final Character SLASH = new Character('/');
-
- /**
- * Replace special characters with XML escapes:
- * <pre>
- * & <i>(ampersand)</i> is replaced by &amp;
- * < <i>(less than)</i> is replaced by &lt;
- * > <i>(greater than)</i> is replaced by &gt;
- * " <i>(double quote)</i> is replaced by &quot;
- * </pre>
- * @param string The string to be escaped.
- * @return The escaped string.
- */
- public static String escape(String string) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0, len = string.length(); i < len; i++) {
- char c = string.charAt(i);
- switch (c) {
- case '&':
- sb.append("&");
- break;
- case '<':
- sb.append("<");
- break;
- case '>':
- sb.append(">");
- break;
- case '"':
- sb.append(""");
- break;
- default:
- sb.append(c);
- }
- }
- return sb.toString();
- }
-
- /**
- * Scan the content following the named tag, attaching it to the context.
- * @param x The XMLTokener containing the source string.
- * @param context The JSONObject that will include the new material.
- * @param name The tag name.
- * @return true if the close tag is processed.
- * @throws JSONException
- */
- private static boolean parse(XMLTokener x, JSONObject context,
- String name) throws JSONException {
- char c;
- int i;
- String n;
- JSONObject o = null;
- String s;
- Object t;
-
-// Test for and skip past these forms:
-// <!-- ... -->
-// <! ... >
-// <![ ... ]]>
-// <? ... ?>
-// Report errors for these forms:
-// <>
-// <=
-// <<
-
- t = x.nextToken();
-
-// <!
-
- if (t == BANG) {
- c = x.next();
- if (c == '-') {
- if (x.next() == '-') {
- x.skipPast("-->");
- return false;
- }
- x.back();
- } else if (c == '[') {
- t = x.nextToken();
- if (t.equals("CDATA")) {
- if (x.next() == '[') {
- s = x.nextCDATA();
- if (s.length() > 0) {
- context.accumulate("content", s);
- }
- return false;
- }
- }
- throw x.syntaxError("Expected 'CDATA['");
- }
- i = 1;
- do {
- t = x.nextMeta();
- if (t == null) {
- throw x.syntaxError("Missing '>' after '<!'.");
- } else if (t == LT) {
- i += 1;
- } else if (t == GT) {
- i -= 1;
- }
- } while (i > 0);
- return false;
- } else if (t == QUEST) {
-
-// <?
-
- x.skipPast("?>");
- return false;
- } else if (t == SLASH) {
-
-// Close tag </
-
- if (name == null || !x.nextToken().equals(name)) {
- throw x.syntaxError("Mismatched close tag");
- }
- if (x.nextToken() != GT) {
- throw x.syntaxError("Misshaped close tag");
- }
- return true;
-
- } else if (t instanceof Character) {
- throw x.syntaxError("Misshaped tag");
-
-// Open tag <
-
- } else {
- n = (String)t;
- t = null;
- o = new JSONObject();
- for (;;) {
- if (t == null) {
- t = x.nextToken();
- }
-
-// attribute = value
-
- if (t instanceof String) {
- s = (String)t;
- t = x.nextToken();
- if (t == EQ) {
- t = x.nextToken();
- if (!(t instanceof String)) {
- throw x.syntaxError("Missing value");
- }
- o.accumulate(s, t);
- t = null;
- } else {
- o.accumulate(s, "");
- }
-
-// Empty tag <.../>
-
- } else if (t == SLASH) {
- if (x.nextToken() != GT) {
- throw x.syntaxError("Misshaped tag");
- }
- context.accumulate(n, o);
- return false;
-
-// Content, between <...> and </...>
-
- } else if (t == GT) {
- for (;;) {
- t = x.nextContent();
- if (t == null) {
- if (name != null) {
- throw x.syntaxError("Unclosed tag " + name);
- }
- return false;
- } else if (t instanceof String) {
- s = (String)t;
- if (s.length() > 0) {
- o.accumulate("content", s);
- }
-
-// Nested element
-
- } else if (t == LT) {
- if (parse(x, o, n)) {
- if (o.length() == 0) {
- context.accumulate(n, "");
- } else if (o.length() == 1 &&
- o.opt("content") != null) {
- context.accumulate(n, o.opt("content"));
- } else {
- context.accumulate(n, o);
- }
- return false;
- }
- }
- }
- } else {
- throw x.syntaxError("Misshaped tag");
- }
- }
- }
- }
-
-
- /**
- * Convert a well-formed (but not necessarily valid) XML string into a
- * JSONObject. Some information may be lost in this transformation
- * because JSON is a data format and XML is a document format. XML uses
- * elements, attributes, and content text, while JSON uses unordered
- * collections of name/value pairs and arrays of values. JSON does not
- * does not like to distinguish between elements and attributes.
- * Sequences of similar elements are represented as JSONArrays. Content
- * text may be placed in a "content" member. Comments, prologs, DTDs, and
- * <code><[ [ ]]></code> are ignored.
- * @param string The source string.
- * @return A JSONObject containing the structured data from the XML string.
- * @throws JSONException
- */
- public static JSONObject toJSONObject(String string) throws JSONException {
- JSONObject o = new JSONObject();
- XMLTokener x = new XMLTokener(string);
- while (x.more()) {
- x.skipPast("<");
- parse(x, o, null);
- }
- return o;
- }
-
-
- /**
- * Convert a JSONObject into a well-formed, element-normal XML string.
- * @param o A JSONObject.
- * @return A string.
- * @throws JSONException
- */
- public static String toString(Object o) throws JSONException {
- return toString(o, null);
- }
-
-
- /**
- * Convert a JSONObject into a well-formed, element-normal XML string.
- * @param o A JSONObject.
- * @param tagName The optional name of the enclosing tag.
- * @return A string.
- * @throws JSONException
- */
- public static String toString(Object o, String tagName)
- throws JSONException {
- StringBuffer b = new StringBuffer();
- int i;
- JSONArray ja;
- JSONObject jo;
- String k;
- Iterator<String> keys;
- int len;
- String s;
- Object v;
- if (o instanceof JSONObject) {
-
-// Emit <tagName>
-
- if (tagName != null) {
- b.append('<');
- b.append(tagName);
- b.append('>');
- }
-
-// Loop thru the keys.
-
- jo = (JSONObject)o;
- keys = jo.keys();
- while (keys.hasNext()) {
- k = keys.next();
- v = jo.get(k);
- if (v instanceof String) {
- s = (String)v;
- } else {
- s = null;
- }
-
-// Emit content in body
-
- if (k.equals("content")) {
- if (v instanceof JSONArray) {
- ja = (JSONArray)v;
- len = ja.length();
- for (i = 0; i < len; i += 1) {
- if (i > 0) {
- b.append('\n');
- }
- b.append(escape(ja.get(i).toString()));
- }
- } else {
- b.append(escape(v.toString()));
- }
-
-// Emit an array of similar keys
-
- } else if (v instanceof JSONArray) {
- ja = (JSONArray)v;
- len = ja.length();
- for (i = 0; i < len; i += 1) {
- b.append(toString(ja.get(i), k));
- }
- } else if (v.equals("")) {
- b.append('<');
- b.append(k);
- b.append("/>");
-
-// Emit a new tag <k>
-
- } else {
- b.append(toString(v, k));
- }
- }
- if (tagName != null) {
-
-// Emit the </tagname> close tag
-
- b.append("</");
- b.append(tagName);
- b.append('>');
- }
- return b.toString();
-
-// XML does not have good support for arrays. If an array appears in a place
-// where XML is lacking, synthesize an <array> element.
-
- } else if (o instanceof JSONArray) {
- ja = (JSONArray)o;
- len = ja.length();
- for (i = 0; i < len; ++i) {
- b.append(toString(
- ja.opt(i), (tagName == null) ? "array" : tagName));
- }
- return b.toString();
- } else {
- s = (o == null) ? "null" : escape(o.toString());
- return (tagName == null) ? "\"" + s + "\"" :
- (s.length() == 0) ? "<" + tagName + "/>" :
- "<" + tagName + ">" + s + "</" + tagName + ">";
- }
- }
-}
\ No newline at end of file
diff --git a/src/main/java/org/apache/sling/commons/json/xml/XMLTokener.java b/src/main/java/org/apache/sling/commons/json/xml/XMLTokener.java
deleted file mode 100644
index 8032818..0000000
--- a/src/main/java/org/apache/sling/commons/json/xml/XMLTokener.java
+++ /dev/null
@@ -1,296 +0,0 @@
-package org.apache.sling.commons.json.xml;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONTokener;
-
-/*
-Copyright (c) 2002 JSON.org
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-The Software shall be used for Good, not Evil.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-*/
-
-/**
- * The XMLTokener extends the JSONTokener to provide additional methods
- * for the parsing of XML texts.
- * @author JSON.org
- * @version 2
- */
-@Deprecated
-public class XMLTokener extends JSONTokener {
-
-
- /** The table of entity values. It initially contains Character values for
- * amp, apos, gt, lt, quot.
- */
- public static final java.util.HashMap<String, Character> entity;
-
- static {
- entity = new java.util.HashMap<String, Character>(8);
- entity.put("amp", XML.AMP);
- entity.put("apos", XML.APOS);
- entity.put("gt", XML.GT);
- entity.put("lt", XML.LT);
- entity.put("quot", XML.QUOT);
- }
-
- /**
- * Construct an XMLTokener from a string.
- * @param s A source string.
- */
- public XMLTokener(String s) {
- super(s);
- }
-
- /**
- * Get the text in the CDATA block.
- * @return The string up to the <code>]]></code>.
- * @throws JSONException If the <code>]]></code> is not found.
- */
- public String nextCDATA() throws JSONException {
- char c;
- int i;
- StringBuffer sb = new StringBuffer();
- for (;;) {
- c = next();
- if (c == 0) {
- throw syntaxError("Unclosed CDATA.");
- }
- sb.append(c);
- i = sb.length() - 3;
- if (i >= 0 && sb.charAt(i) == ']' &&
- sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
- sb.setLength(i);
- return sb.toString();
- }
- }
- }
-
-
- /**
- * Get the next XML outer token, trimming whitespace. There are two kinds
- * of tokens: the '<' character which begins a markup tag, and the content
- * text between markup tags.
- *
- * @return A string, or a '<' Character, or null if there is no more
- * source text.
- * @throws JSONException
- */
- public Object nextContent() throws JSONException {
- char c;
- StringBuffer sb;
- do {
- c = next();
- } while (Character.isWhitespace(c));
- if (c == 0) {
- return null;
- }
- if (c == '<') {
- return XML.LT;
- }
- sb = new StringBuffer();
- for (;;) {
- if (c == '<' || c == 0) {
- back();
- return sb.toString().trim();
- }
- if (c == '&') {
- sb.append(nextEntity(c));
- } else {
- sb.append(c);
- }
- c = next();
- }
- }
-
-
- /**
- * Return the next entity. These entities are translated to Characters:
- * <code>&amp; &apos; &gt; &lt; &quot;</code>.
- * @param a An ampersand character.
- * @return A Character or an entity String if the entity is not recognized.
- * @throws JSONException If missing ';' in XML entity.
- */
- public Object nextEntity(char a) throws JSONException {
- StringBuffer sb = new StringBuffer();
- for (;;) {
- char c = next();
- if (Character.isLetterOrDigit(c) || c == '#') {
- sb.append(Character.toLowerCase(c));
- } else if (c == ';') {
- break;
- } else {
- throw syntaxError("Missing ';' in XML entity: &" + sb);
- }
- }
- String s = sb.toString();
- Object e = entity.get(s);
- return e != null ? e : a + s + ";";
- }
-
-
- /**
- * Returns the next XML meta token. This is used for skipping over <!...>
- * and <?...?> structures.
- * @return Syntax characters (<code>< > / = ! ?</code>) are returned as
- * Character, and strings and names are returned as Boolean. We don't care
- * what the values actually are.
- * @throws JSONException If a string is not properly closed or if the XML
- * is badly structured.
- */
- public Object nextMeta() throws JSONException {
- char c;
- char q;
- do {
- c = next();
- } while (Character.isWhitespace(c));
- switch (c) {
- case 0:
- throw syntaxError("Misshaped meta tag.");
- case '<':
- return XML.LT;
- case '>':
- return XML.GT;
- case '/':
- return XML.SLASH;
- case '=':
- return XML.EQ;
- case '!':
- return XML.BANG;
- case '?':
- return XML.QUEST;
- case '"':
- case '\'':
- q = c;
- for (;;) {
- c = next();
- if (c == 0) {
- throw syntaxError("Unterminated string.");
- }
- if (c == q) {
- return Boolean.TRUE;
- }
- }
- default:
- for (;;) {
- c = next();
- if (Character.isWhitespace(c)) {
- return Boolean.TRUE;
- }
- switch (c) {
- case 0:
- case '<':
- case '>':
- case '/':
- case '=':
- case '!':
- case '?':
- case '"':
- case '\'':
- back();
- return Boolean.TRUE;
- }
- }
- }
- }
-
-
- /**
- * Get the next XML Token. These tokens are found inside of angle
- * brackets. It may be one of these characters: <code>/ > = ! ?</code> or it
- * may be a string wrapped in single quotes or double quotes, or it may be a
- * name.
- * @return a String or a Character.
- * @throws JSONException If the XML is not well formed.
- */
- public Object nextToken() throws JSONException {
- char c;
- char q;
- StringBuffer sb;
- do {
- c = next();
- } while (Character.isWhitespace(c));
- switch (c) {
- case 0:
- throw syntaxError("Misshaped element.");
- case '<':
- throw syntaxError("Misplaced '<'.");
- case '>':
- return XML.GT;
- case '/':
- return XML.SLASH;
- case '=':
- return XML.EQ;
- case '!':
- return XML.BANG;
- case '?':
- return XML.QUEST;
-
-// Quoted string
-
- case '"':
- case '\'':
- q = c;
- sb = new StringBuffer();
- for (;;) {
- c = next();
- if (c == 0) {
- throw syntaxError("Unterminated string.");
- }
- if (c == q) {
- return sb.toString();
- }
- if (c == '&') {
- sb.append(nextEntity(c));
- } else {
- sb.append(c);
- }
- }
- default:
-
-// Name
-
- sb = new StringBuffer();
- for (;;) {
- sb.append(c);
- c = next();
- if (Character.isWhitespace(c)) {
- return sb.toString();
- }
- switch (c) {
- case 0:
- case '>':
- case '/':
- case '=':
- case '!':
- case '?':
- case '[':
- case ']':
- back();
- return sb.toString();
- case '<':
- case '"':
- case '\'':
- throw syntaxError("Bad character in a name.");
- }
- }
- }
- }
-}
diff --git a/src/main/java/org/apache/sling/commons/json/xml/package-info.java b/src/main/java/org/apache/sling/commons/json/xml/package-info.java
deleted file mode 100644
index 1c3bf0b..0000000
--- a/src/main/java/org/apache/sling/commons/json/xml/package-info.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-@Version("2.0.5")
-package org.apache.sling.commons.json.xml;
-
-import org.osgi.annotation.versioning.Version;
diff --git a/src/test/java/org/apache/sling/commons/json/JSONArrayToStringTest.java b/src/test/java/org/apache/sling/commons/json/JSONArrayToStringTest.java
deleted file mode 100644
index 445b808..0000000
--- a/src/test/java/org/apache/sling/commons/json/JSONArrayToStringTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json;
-
-import static org.junit.Assert.assertEquals;
-
-import org.apache.sling.commons.json.util.DespacedRendering;
-import org.junit.Test;
-
-/** Test the String formatting functionality of JSONObject */
-public class JSONArrayToStringTest {
- @Test
- public void testJsonArraySingle() throws JSONException {
- final JSONArray a = new JSONArray();
- a.put("foo");
- assertEquals("[\"foo\"]", a.toString());
- }
-
- @Test
- public void testJsonArrayTwo() throws JSONException {
- final JSONArray a = new JSONArray();
- a.put("foo").put(42);
- final DespacedRendering r = new DespacedRendering("{array:" + a.toString(2) + "}");
- r.expect("[-nl-_foo_,-nl-42-nl-]");
- }
-
-}
diff --git a/src/test/java/org/apache/sling/commons/json/JSONObjectTest.java b/src/test/java/org/apache/sling/commons/json/JSONObjectTest.java
deleted file mode 100644
index c32a74a..0000000
--- a/src/test/java/org/apache/sling/commons/json/JSONObjectTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import org.junit.Test;
-
-/**
- * @since Apr 17, 2009 6:04:00 PM
- */
-public class JSONObjectTest {
-
- private static final String KEY = "key";
-
- /**
- * See <a href="https://issues.apache.org/jira/browse/SLING-929">SLING-929</a>
- */
- @Test public void testAppend() throws JSONException {
- JSONObject obj = new JSONObject();
- obj.append(KEY, "value1");
- obj.append(KEY, "value2");
- Object result = obj.get(KEY);
- assertTrue("Did not create an array", result instanceof JSONArray);
- }
-
- /**
- * See <a href="https://issues.apache.org/jira/browse/SLING-929">SLING-929</a>
- */
- @Test public void testFailAppend() throws JSONException {
- JSONObject obj = new JSONObject();
- obj.put(KEY, "value1");
- try {
- obj.append(KEY, "value2");
- TestCase.fail("Accepted append() to a non-array property");
- } catch (JSONException ignore) {
- // this is expected
- }
- }
-
- @Test public void testNull() throws JSONException {
- JSONObject obj = new JSONObject();
- obj.put(KEY, JSONObject.NULL);
-
- TestCase.assertTrue(obj.has(KEY));
- TestCase.assertTrue(obj.get(KEY).equals(null));
- TestCase.assertEquals("{\"" + KEY + "\":null}", obj.toString());
- }
-
- @Test public void testParseLong() throws JSONException {
- String jsonStr = "{\"longvalue\":\"13857270119014401\"}";
- JSONObject obj = new JSONObject(jsonStr);
- TestCase.assertEquals(13857270119014401L, obj.getLong("longvalue"));
- }
-
- @Test public void testNullValueInMap() throws JSONException {
- Map<String,Object> map=new LinkedHashMap<String,Object>();
- map.put("abc", "123456");
- List<String> list = new ArrayList<String>();
- list.add("Admin");
- list.add("password");
- map.put("groups", list);
- map.put("id", null);
- JSONObject response=new JSONObject();
- response.put("key", map);
- assertNotNull(response.get("key"));
- assertEquals("{\"abc\":\"123456\",\"groups\":\"[Admin, password]\",\"id\":null}", response.get("key").toString());
- assertEquals("123456", response.getJSONObject("key").get("abc"));
- assertEquals(list, response.getJSONObject("key").get("groups"));
- }
-}
diff --git a/src/test/java/org/apache/sling/commons/json/JSONObjectToStringTest.java b/src/test/java/org/apache/sling/commons/json/JSONObjectToStringTest.java
deleted file mode 100644
index 7768058..0000000
--- a/src/test/java/org/apache/sling/commons/json/JSONObjectToStringTest.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.Writer;
-
-import org.apache.sling.commons.json.util.DespacedRendering;
-import org.apache.sling.commons.json.util.TestJSONObject;
-import org.junit.Before;
-import org.junit.Test;
-
-/** Test the String formatting functionality of JSONObject */
-public class JSONObjectToStringTest {
- private JSONObject j;
-
- static class FailingWriter extends Writer {
- public void write(char[] cbuf, int off, int len) throws IOException {
- throw new IOException("write");
- }
-
- public void flush() throws IOException {
- throw new IOException("flush");
- }
-
- public void close() throws IOException {
- throw new IOException("close");
- }
- }
-
- @Before
- public void setup() throws JSONException {
- j = new TestJSONObject();
- }
-
- @Test
- public void testToString() throws JSONException {
- final DespacedRendering r = new DespacedRendering(j.toString());
- r.expect(
- "_long_:42",
- "_string_:_thisstring_",
- "_int_:12",
- "_k0_:{",
- "_name_:_k0_",
- "_thisis_:_k0_",
- "_k1_:{",
- "_name_:_k1_",
- "_thisis_:_k1_",
- "_boolean_:true",
- "_JSONString_:json.stringhere",
- "_array_:[true,_hello_,52,212]",
- "_double_:45.67",
- "_float_:12.34"
- );
- }
-
- @Test
- public void testToStringWithIndents() throws JSONException {
- final DespacedRendering r = new DespacedRendering(j.toString(2));
- r.expect(
- "_long_:42,-nl-",
- "_string_:_thisstring_,-nl-",
- "_int_:12,-nl-",
- "_k0_:{",
- "_name_:_k0_",
- "_thisis_:_k0_",
- "_k1_:{",
- "_name_:_k1_",
- "_thisis_:_k1_",
- "_boolean_:true",
- "_JSONString_:json.stringhere",
- "_array_:[-nl-true",
- "_double_:45.67",
- "_float_:12.34"
- );
- }
-
- @Test
- public void testToStringWithInitialIndent() throws JSONException {
- final DespacedRendering r = new DespacedRendering(j.toString(2, 3), "S_");
- r.expect(
- "{-nl-S_S_S_S_S_",
- "_long_:42,-nl-",
- "_string_:_thisstring_,-nl-",
- "_int_:12,-nl-",
- "_k0_:{",
- "_name_:_k0_",
- "_thisis_:_k0_",
- "_k1_:{",
- "_name_:_k1_",
- "_thisis_:_k1_",
- "_array_:[-nl-S_S_S_S_S_S_S_true"
- );
- }
-
- @Test
- public void testToStringEmpty() throws JSONException {
- final DespacedRendering r = new DespacedRendering(new JSONObject().toString(2));
- r.assertExactMatch("{}");
- }
-
- @Test
- public void testToStringSingle() throws JSONException {
- j = new JSONObject();
- j.put("foo", "bar");
- final DespacedRendering r = new DespacedRendering(j.toString(2));
- r.assertExactMatch("{_foo_:_bar_}");
- }
-
- @Test
- public void testJSONStringException() throws JSONException {
- final JSONString js = new JSONString() {
- @Override
- public String toString() {
- return toJSONString();
- }
- public String toJSONString() {
- throw new UnsupportedOperationException("toJSONString");
- }
-
- };
- j.put("should.fail", js);
-
- // if any exception, toString returns null.
- // Not sure why but that's what it is
- assertNull("Expecting null output for toString()", j.toString());
-
- // but toString(s) rethrows...
- try {
- assertNull("Expecting null output for toString(2)", j.toString(2));
- fail("Expected UnsupportedOperationException");
- } catch(UnsupportedOperationException uso) {
- // as expected
- }
- }
-
- @Test
- public void testQuote() {
- final String inp = "<tag/></thing>\\\\0\"A/B\bT\tN\nF\fT\r\u0082";
- final String out = "\"<tag/><\\/thing>\\\\\\\\0\\\"A/B\\bT\\tN\\nF\\fT\\r\\u0082\"";
- assertEquals(out, JSONObject.quote(inp));
- }
-
- @Test
- public void testQuoteNull() {
- assertEquals("\"\"", JSONObject.quote(null));
- assertEquals("\"\"", JSONObject.quote(""));
- }
-
- @Test
- public void testToJsonArray() throws JSONException {
- final DespacedRendering r = new DespacedRendering("{array:" + j.toJSONArray(j.names()).toString() + "}");
- r.expect("_thisstring_","12","42","true","json.stringhere");
- }
-
- @Test
- public void testWriteJsonArray() throws JSONException {
- final JSONArray a = j.toJSONArray(j.names());
- final StringWriter w = new StringWriter();
- a.write(w);
- final DespacedRendering r = new DespacedRendering("{array:" + w.toString() + "}");
- r.expect("_thisstring_","12","42","true","json.stringhere");
- }
-
- @Test(expected=JSONException.class)
- public void testWriteJsonArrayException() throws JSONException {
- final JSONArray a = j.toJSONArray(j.names());
- a.write(new FailingWriter());
- }
-
- @Test
- public void testWrite() throws JSONException {
- final StringWriter w = new StringWriter();
- j.write(w);
- final DespacedRendering r = new DespacedRendering(w.toString());
- r.expect(
- "_long_:42",
- "_string_:_thisstring_",
- "_int_:12",
- "_k0_:{",
- "_name_:_k0_",
- "_thisis_:_k0_",
- "_k1_:{",
- "_name_:_k1_",
- "_thisis_:_k1_",
- "_boolean_:true",
- "_JSONString_:json.stringhere",
- "_array_:[true,_hello_,52,212]",
- "_double_:45.67",
- "_float_:12.34"
- );
- }
-
- @Test(expected=JSONException.class)
- public void testWriteException() throws JSONException {
- j.write(new FailingWriter());
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/commons/json/JSONWriterTest.java b/src/test/java/org/apache/sling/commons/json/JSONWriterTest.java
deleted file mode 100644
index fd3225f..0000000
--- a/src/test/java/org/apache/sling/commons/json/JSONWriterTest.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.StringWriter;
-
-import org.apache.sling.commons.json.io.JSONWriter;
-import org.apache.sling.commons.json.util.DespacedRendering;
-import org.junit.Before;
-import org.junit.Test;
-
-/** Test the String formatting functionality of JSONObject */
-public class JSONWriterTest {
- private JSONWriter w;
- private StringWriter output;
-
- @Before
- public void setup() {
- output = new StringWriter();
- w = new JSONWriter(output);
- }
-
- private DespacedRendering write() throws JSONException {
- w.object();
- w.key("foo").value("bar");
- w.key("array");
- w.array().value(1).value("two").value(3.0).value(false).endArray();
- w.key("last").value("one");
- w.endObject();
- return new DespacedRendering(output.toString());
- }
-
- private DespacedRendering writeObject() throws JSONException {
- JSONArray arr = new JSONArray();
- arr.put(1).put("two").put(3.0).put(false);
-
- w.writeObject(
- new JSONObject()
- .put("foo", "bar")
- .put("array", arr)
- );
-
- return new DespacedRendering(output.toString());
- }
-
- @Test
- public void testSetTidy() {
- assertFalse(w.isTidy());
- w.setTidy(true);
- assertTrue(w.isTidy());
- }
-
- @Test
- public void testStandardWrite() throws JSONException {
- final DespacedRendering r = write();
- r.expect(
- "_foo_:_bar_",
- "_array_:[1,_two_,3,false]");
- }
-
- @Test
- public void testStandardObjectWrite() throws JSONException {
- final DespacedRendering r = writeObject();
- r.expect(
- "_foo_:_bar_",
- "_array_:[1,_two_,3,false]");
- }
-
- @Test
- public void testTidyWrite() throws JSONException {
- w.setTidy(true);
- final DespacedRendering r = write();
- r.expect(
- "-nl-_foo_:_bar_",
- "-nl-_array_:[-nl-1,-nl-_two_,-nl-3,-nl-false-nl-]");
- }
-
- @Test
- public void testTidyObjectWrite() throws JSONException {
- w.setTidy(true);
- final DespacedRendering r = writeObject();
- r.expect(
- "-nl-_foo_:_bar_",
- "-nl-_array_:[-nl-1,-nl-_two_,-nl-3,-nl-false-nl-]");
- }
-
- @Test
- public void testEmpty() throws JSONException {
- assertTrue(output.toString().length() == 0);
- }
-
- @Test(expected=JSONException.class)
- public void testMisplacedArray() throws JSONException {
- w.object().array();
- }
-
- @Test(expected=JSONException.class)
- public void testMisplacedKey() throws JSONException {
- w.array().key("foo");
- }
-
- @Test(expected=JSONException.class)
- public void testMisplacedEndObjectA() throws JSONException {
- w.object().endObject().endObject();
- }
-
- @Test(expected=JSONException.class)
- public void testMisplacedEndObjectB() throws JSONException {
- w.endObject();
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/commons/json/io/JSONRendererTest.java b/src/test/java/org/apache/sling/commons/json/io/JSONRendererTest.java
deleted file mode 100644
index 4d88a32..0000000
--- a/src/test/java/org/apache/sling/commons/json/io/JSONRendererTest.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.io;
-
-import static org.junit.Assert.assertEquals;
-
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.apache.sling.commons.json.util.DespacedRendering;
-import org.apache.sling.commons.json.util.TestJSONObject;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.io.StringWriter;
-
-
-/** Most of the JSONRenderer code is tested indirectly
- * via existing JSONObject and JSONArray tests - this
- * tests what's left */
-public class JSONRendererTest {
- private final JSONRenderer renderer = new JSONRenderer();
-
- @Test
- public void testA() {
- assertEquals("12.34", renderer.doubleToString(12.34));
- }
-
- @Test
- public void testB() {
- assertEquals("123", renderer.doubleToString(123));
- }
-
- @Test
- public void testC() {
- assertEquals("null", renderer.doubleToString(Double.POSITIVE_INFINITY));
- }
-
- @Test
- public void testD() {
- assertEquals("null", renderer.doubleToString(Double.NEGATIVE_INFINITY));
- }
-
- @Test
- public void testE() {
- assertEquals("null", renderer.doubleToString(Double.NaN));
- }
-
- @Test(expected=JSONException.class)
- public void testF() throws JSONException {
- renderer.numberToString(null);
- }
-
- @Test
- public void testEmptyJSONArray() throws JSONException {
- assertEquals("[]", renderer.prettyPrint(new JSONArray(), renderer.options()));
- }
-
- @Test
- public void testSingleJSONArray() throws JSONException {
- final JSONArray ja = new JSONArray();
- ja.put(42);
- assertEquals("[42]", renderer.prettyPrint(ja, renderer.options()));
- }
-
- @Test
- public void testDefaultArrayOutput() throws JSONException {
- final JSONObject jo = new TestJSONObject();
- final String pp = renderer.prettyPrint(jo.getJSONArray("array"), renderer.options());
- final DespacedRendering r = new DespacedRendering("{array:" + pp + "}");
- r.expect("[true,_hello_,52,212]");
- }
-
- @Test
- public void testArraysPrettyPrint() throws JSONException {
- final JSONObject jo = new TestJSONObject();
-
- // Verify that we get an array for children, by re-parsing the output
- final String json = renderer.prettyPrint(jo, renderer.options().withArraysForChildren(true));
- final JSONObject copy = new JSONObject(json);
- final JSONArray a = copy.getJSONArray(JSONRenderer.Options.DEFAULT_CHILDREN_KEY);
- final String str = renderer.toString(a);
- final String expected = "[{\"__name__\":\"k0\",\"name\":\"k0\",\"this is\":\"k0\"},{\"__name__\":\"k1\",\"name\":\"k1\",\"this is\":\"k1\"}]";
- assertEquals(expected, str);
- }
-
- @Test
- public void testCustomNamesArraysPrettyPrint() throws JSONException {
- final JSONObject jo = new TestJSONObject();
- final JSONRenderer.Options opt = renderer.options();
- opt.withArraysForChildren(true).withIndent(2).withChildrenKey("KIDS").withChildNameKey("KID.NAME");
- final DespacedRendering r = new DespacedRendering(renderer.prettyPrint(jo, opt));
- r.expect(
- "-nl-_string_:_thisstring_,-nl-_int_:12,-nl-_long_:42,-nl-_boolean_:true,",
- "_array_:[-nl-true,-nl-_hello_,-nl-52,-nl-212-nl-]-nl-,",
- "-nl-_KIDS_:[-nl-{-nl-_KID.NAME_:_k0_,-nl-_name_:_k0_",
- "-nl-_thisis_:_k0_-nl-},-nl-{-nl-_KID.NAME_:_k1_,-nl-_name_:_k1_,-nl-_thisis_:_k1_-nl-}-nl-]"
- );
- }
-
- @Test
- public void testIndentedArraysPrettyPrint() throws JSONException {
- final JSONObject jo = new TestJSONObject();
- final JSONRenderer.Options opt = renderer.options().withArraysForChildren(true).withIndent(2);
- final DespacedRendering r = new DespacedRendering(renderer.prettyPrint(jo, opt));
- r.expect(
- "-nl-_string_:_thisstring_,-nl-_int_:12,-nl-_long_:42,-nl-_boolean_:true,",
- "_array_:[-nl-true,-nl-_hello_,-nl-52,-nl-212-nl-]-nl-,",
- "-nl-___children___:[-nl-{-nl-___name___:_k0_,-nl-_name_:_k0_",
- "-nl-_thisis_:_k0_-nl-},-nl-{-nl-___name___:_k1_,-nl-_name_:_k1_,-nl-_thisis_:_k1_-nl-}-nl-]"
- );
- }
-
- /**
- * Just to make sure that quote(writer, string) which is not indirectly tested anymore still works. For other quote
- * tests see JSONObjectToStringTest.testQuote*
- */
- @Test
- public void testQuoteWriter() throws IOException {
- StringWriter writer = new StringWriter();
- renderer.quote(writer, "\\");
- renderer.quote(writer, "");
- renderer.quote(writer, null);
- assertEquals("\"\\\\\"\"\"\"\"", writer.toString());
- }
-
-}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/commons/json/jcr/JsonItemWriterTest.java b/src/test/java/org/apache/sling/commons/json/jcr/JsonItemWriterTest.java
deleted file mode 100644
index da1bae0..0000000
--- a/src/test/java/org/apache/sling/commons/json/jcr/JsonItemWriterTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.jcr;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.StringWriter;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.jcr.Node;
-import javax.jcr.NodeIterator;
-import javax.jcr.RepositoryException;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.testing.jcr.MockNode;
-import org.apache.sling.commons.testing.jcr.MockNodeIterator;
-import org.junit.Test;
-
-/** Test the JsonItemWriter */
-public class JsonItemWriterTest {
-
- private final JsonItemWriter writer = new JsonItemWriter(null);
-
- private String getJson(Node n, int levels) throws RepositoryException, JSONException {
- final StringWriter sw = new StringWriter();
- writer.dump(n, sw, 0);
- return sw.toString();
- }
-
- @Test
- public void testBasicJson() throws RepositoryException, JSONException {
- final Node n = new MockNode("/test");
- n.setProperty("testprop", "1234");
- assertEquals("{\"testprop\":\"1234\"}",getJson(n, 0));
- }
-
- @Test
- public void testMultivalued() throws RepositoryException, JSONException {
- final Node n = new MockNode("/test");
- final String [] values = { "1234", "yes" };
- n.setProperty("testprop", values);
- assertEquals("{\"testprop\":[\"1234\",\"yes\"]}",getJson(n, 0));
- }
-
- /**
- * See <a href="https://issues.apache.org/jira/browse/SLING-924">SLING-924</a>
- */
- @Test
- public void testOutputIterator() throws JSONException, RepositoryException {
- MockNode node1 = new MockNode("/node1");
- MockNode node2 = new MockNode("/node2");
- node1.addNode("node3");
- node1.setProperty("name", "node1");
- node2.setProperty("name", "node2");
- final NodeIterator it = new MockNodeIterator(new Node[]{node1, node2});
- final StringWriter sw = new StringWriter();
- writer.dump(it, sw);
- Pattern testPattern = Pattern.compile("\\{(.[^\\}]*)\\}"); // Pattern to look for a {...}
- Matcher matcher = testPattern.matcher(sw.toString());
- assertTrue("Did not produce a JSON object", matcher.find()); // Find first JSON object
- assertTrue("Did not produce a 2nd JSON object", matcher.find()); // Find second JSON object
- assertFalse("Produced a JSON object for a child node", matcher.find()); // Assert no child node has been created
- }
-}
diff --git a/src/test/java/org/apache/sling/commons/json/jcr/JsonJcrNodeTest.java b/src/test/java/org/apache/sling/commons/json/jcr/JsonJcrNodeTest.java
deleted file mode 100644
index 9b8648b..0000000
--- a/src/test/java/org/apache/sling/commons/json/jcr/JsonJcrNodeTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.jcr;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.jcr.RepositoryException;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.testing.jcr.MockNode;
-import org.junit.Test;
-
-/**
- * @author vidar@idium.no
- * @since Apr 17, 2009 6:57:04 PM
- */
-public class JsonJcrNodeTest {
-
- @Test
- public void testJcrJsonObject() throws RepositoryException, JSONException {
- MockNode node = new MockNode("/node1");
- node.setProperty("prop1", "value1");
- node.setProperty("prop2", "value2");
- Set<String> ignoredProperties = new HashSet<String>();
- ignoredProperties.add("prop2");
- JsonJcrNode json = new JsonJcrNode(node, ignoredProperties);
- assertTrue("Did not create property", json.has("prop1"));
- assertFalse("Created ignored property", json.has("prop2"));
- assertTrue("Did not create jcr:name", json.has("jcr:name"));
- assertTrue("Did not create jcr:path", json.has("jcr:path"));
- }
-
-}
diff --git a/src/test/java/org/apache/sling/commons/json/sling/JsonObjectCreatorTest.java b/src/test/java/org/apache/sling/commons/json/sling/JsonObjectCreatorTest.java
deleted file mode 100644
index ad96442..0000000
--- a/src/test/java/org/apache/sling/commons/json/sling/JsonObjectCreatorTest.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.sling;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.when;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.TimeZone;
-import java.util.UUID;
-
-import org.apache.sling.api.resource.Resource;
-import org.apache.sling.api.resource.ResourceResolver;
-import org.apache.sling.api.resource.ValueMap;
-import org.apache.sling.api.wrappers.ValueMapDecorator;
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-
-@RunWith(MockitoJUnitRunner.class)
-public class JsonObjectCreatorTest {
-
- @Mock
- private Resource resource;
-
- @Mock
- private ResourceResolver resourceResolver;
-
- @Mock
- private ResourceResolver childResourceResolver;
-
- private Map<String, Object> props;
- private static final String RESOURCE_NAME = "testResource";
- private static final String PATH = "/" + RESOURCE_NAME;
-
- private static final Object SAME = new Object();
- private static final int NCHILDREN = 3;
- private static final String ECMA_DATE_FORMAT = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
-
- @Before
- public void setup() {
- props = new HashMap<String, Object>();
- props.put("defaultProperty", "defaultValue");
-
- final List<Resource> empty = new ArrayList<Resource>();
- when(childResourceResolver.listChildren(any(Resource.class))).thenReturn(empty.iterator());
-
- final List<Resource> children = new ArrayList<Resource>();
- for(int i=0; i < NCHILDREN; i++) {
- final Map<String, Object> childProps = new HashMap<String, Object>();
- final String id = "child" + i;
- childProps.put("id", id);
- final Resource r = Mockito.mock(Resource.class);
- when(r.adaptTo(ValueMap.class)).thenReturn(new ValueMapDecorator(childProps));
- when(r.getResourceResolver()).thenReturn(childResourceResolver);
- when(r.getPath()).thenReturn(PATH + "/" + id);
- children.add(r);
- }
-
- when(resourceResolver.listChildren(any(Resource.class))).thenReturn(children.iterator());
- when(resource.getResourceResolver()).thenReturn(resourceResolver);
- when(resource.getPath()).thenReturn(PATH);
- }
-
- private void assertGet(Object data) throws JSONException {
- assertGet(data, SAME);
- }
-
- private void assertGet(Object data, Object expected) throws JSONException {
- final String key = UUID.randomUUID().toString();
- props.clear();
- props.put(key, data);
- when(resource.adaptTo(ValueMap.class)).thenReturn(new ValueMapDecorator(props));
- final JSONObject j = JsonObjectCreator.create(resource, 1);
-
- final String getKey = data instanceof InputStream ? ":" + key : key;
- final Object toExpect = expected == SAME ? data : expected;
- if(toExpect instanceof String) {
- assertEquals(toExpect, j.get(getKey).toString());
- } else {
- assertEquals(toExpect, j.get(getKey));
- }
- }
-
- @Test
- public void testSimpleTypes() throws JSONException {
- assertGet("bar");
- assertGet(true);
- assertGet(123);
- assertGet(456.78);
- assertGet(System.currentTimeMillis());
- }
-
- @Test
- public void testStringValue() throws JSONException {
- final String value = "the string";
- when(resource.adaptTo(String.class)).thenReturn(value);
- final JSONObject j = JsonObjectCreator.create(resource, 1);
- assertEquals(value, j.get(RESOURCE_NAME));
- }
-
- @Test
- public void testStringArray() throws JSONException {
- final String [] values = { "A", "B" };
- when(resource.adaptTo(String[].class)).thenReturn(values);
- final JSONObject j = JsonObjectCreator.create(resource, 1);
- assertEquals("A", j.getJSONArray(RESOURCE_NAME).get(0));
- assertEquals("B", j.getJSONArray(RESOURCE_NAME).get(1));
- }
-
- @Test
- public void testArray() throws JSONException {
- final String [] values = { "C", "D" };
- final JSONArray a = new JSONArray().put("C").put("D");
- assertGet(values, a.toString());
- }
-
- @Test
- public void testEmptyArray() throws JSONException {
- final Long [] values = {};
- assertGet(values, "[]");
- }
-
- @Test
- public void testCalendar() throws JSONException {
- final Calendar nowCalendar = Calendar.getInstance();
- final String nowString = new SimpleDateFormat(ECMA_DATE_FORMAT, JsonObjectCreator.DATE_FORMAT_LOCALE).format(nowCalendar.getTime());
- assertGet(nowCalendar, nowString);
- }
-
- @Test
- public void testCalendarTimezones() throws JSONException {
- final int[] offsets = { -14400000, -4200000, 14400000, 4300000 };
- for (int offset : offsets) {
- for (String tzId : TimeZone.getAvailableIDs(offset)) {
- final TimeZone tz = TimeZone.getTimeZone(tzId);
- final Calendar cal = Calendar.getInstance(tz);
- DateFormat fmt = new SimpleDateFormat(ECMA_DATE_FORMAT, Locale.ENGLISH);
- fmt.setTimeZone(tz);
- final String nowString = fmt.format(cal.getTime());
- assertGet(cal, nowString);
- }
- }
- }
-
- @Test
- public void testStream() throws JSONException {
- final byte [] bytes = "Hello there".getBytes();
- final InputStream stream = new ByteArrayInputStream(bytes);
- // TODO not sure why we don't get the actual length here
- assertGet(stream, -1L);
- }
-
- @Test
- public void testChildren() throws JSONException {
- when(resource.adaptTo(ValueMap.class)).thenReturn(new ValueMapDecorator(props));
- final JSONObject j = JsonObjectCreator.create(resource, 2);
- for(int i=0 ; i < NCHILDREN; i++) {
- final String id = "child" + i;
- assertEquals(id, j.getJSONObject(id).get("id"));
- }
- }
-
-}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/commons/json/sling/ResourceTraversorTest.java b/src/test/java/org/apache/sling/commons/json/sling/ResourceTraversorTest.java
deleted file mode 100644
index 0a45eb5..0000000
--- a/src/test/java/org/apache/sling/commons/json/sling/ResourceTraversorTest.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.sling.commons.json.sling;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Iterator;
-
-import org.apache.sling.api.resource.ModifiableValueMap;
-import org.apache.sling.api.resource.PersistenceException;
-import org.apache.sling.api.resource.Resource;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.apache.sling.testing.mock.sling.junit.SlingContext;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-
-public class ResourceTraversorTest {
- private static final String RESOURCE_NAME = "R";
- private static final String ID = "id";
-
- // Before revision 1744381 the tests would fail with this set to 20'000
- private final int MANY = Integer.getInteger("sling.test.ResourceTraversor.count", 100000);
-
- private final int FEW = 5;
- private final int LEVELS = 3;
- private Resource root;
-
- @Rule
- public final SlingContext context = new SlingContext();
-
- private void addChildren(Resource parent, int resourcesPerLevel, int nLevels) throws PersistenceException {
- for(int i=0; i < resourcesPerLevel; i++) {
- final String id = makePath(nLevels, i);
- final Resource child = parent.getResourceResolver().create(parent, id, null);
- ModifiableValueMap vm = child.adaptTo(ModifiableValueMap.class);
- vm.put(ID, id);
- child.getResourceResolver().commit();
- if(nLevels > 1) {
- addChildren(child, resourcesPerLevel, nLevels - 1);
- }
- }
- }
-
- private static String makePath(int nLevels, int index) {
- return RESOURCE_NAME + "_" + nLevels + "_" + index;
- }
-
- private String describe(JSONObject o) {
- int maxKeys = 5;
- final StringBuilder b = new StringBuilder();
- b.append("JSONOBject having ");
- final Iterator<String> k = o.keys();
- int count = 0;
- if(!k.hasNext()) {
- b.append("no properties");
- }
- while(k.hasNext()) {
- b.append(k.next()).append(",");
- if(++count >= maxKeys) {
- b.append("...");
- break;
- }
- }
- return b.toString();
- }
-
- @Before
- public void setup() {
- root = null;
- }
-
- public void createTree(int resourcesPerLevel, int depth) throws PersistenceException {
- root = context.resourceResolver().getResource("/");
- addChildren(root, resourcesPerLevel, depth);
- }
-
- @Test
- public void collectNLevelsNoLimit() throws JSONException, PersistenceException {
- createTree(FEW, LEVELS);
- ResourceTraversor traversor = new ResourceTraversor(-1, Integer.MAX_VALUE, root, true);
- traversor.collectResources();
- assertTraversalResult(root.getPath(), traversor.getJSONObject(), FEW, LEVELS);
- }
-
- @Test
- public void collectNLevelsWithLimit() throws JSONException, PersistenceException {
- createTree(FEW, LEVELS);
- final String [] ids = { "R_3_0", "R_3_1" };
- final int limit = ids.length;
- ResourceTraversor traversor = new ResourceTraversor(-1, limit, root, true);
- traversor.collectResources();
- final int expectedCount = limit + 1;
- assertEquals(expectedCount, traversor.getCount());
- final JSONObject jso = traversor.getJSONObject();
- for(String id : ids) {
- assertTrue("Expecting " + id + " on " + describe(jso), jso.has(id));
- }
- }
-
- @Test
- public void collectWithLimitInChildren() throws JSONException, PersistenceException {
- createTree(2, 2);
- final String [] ids = { "R_2_0", "R_2_1" };
- final int limit = ids.length;
- ResourceTraversor traversor = new ResourceTraversor(-1, limit, root, true);
- traversor.collectResources();
- final int expectedCount = limit + 1;
- assertEquals(expectedCount, traversor.getCount());
- final JSONObject jso = traversor.getJSONObject();
- for(String id : ids) {
- assertTrue("Expecting " + id + " on " + describe(jso), jso.has(id));
- }
- }
-
- @Test
- public void collectOneLevelNoLimit() throws JSONException, PersistenceException {
- createTree(MANY, 1);
- ResourceTraversor traversor = new ResourceTraversor(1, MANY * 10, root, true);
- traversor.collectResources();
- assertTraversalResult(root.getPath(), traversor.getJSONObject(), MANY, 1);
- assertEquals(MANY, traversor.getCount());
- }
-
- @Test
- public void collectOneLevelLimitIgnoredAtLevelOne() throws JSONException, PersistenceException {
- createTree(MANY, 1);
- ResourceTraversor traversor = new ResourceTraversor(1, 1, root, true);
- traversor.collectResources();
- assertTraversalResult(root.getPath(), traversor.getJSONObject(), MANY, 1);
- assertEquals(MANY, traversor.getCount());
- }
-
- void assertTraversalResult(String parentPath, JSONObject jso, int childrenPerLevel, int nLevels) throws JSONException {
- for(int i=0; i < childrenPerLevel; i++) {
- final String key = makePath(nLevels, i);
- assertTrue("Expecting " + key + " on " + describe(jso), jso.has(key));
- final JSONObject child = jso.getJSONObject(key);
- assertTrue("Expecting property " + ID, child.has(ID));
- assertEquals("Expecting value " + key, key, child.get(ID));
- if(nLevels > 1) {
- assertTraversalResult(key, child, childrenPerLevel, nLevels - 1);
- }
- }
- int keysCount = 0;
- final Iterator<String> k = jso.keys();
- while(k.hasNext()) {
- k.next();
- keysCount++;
- }
- // Sling mocks add an extra property
- assertEquals("Expecting " + childrenPerLevel + " keys on " + describe(jso), childrenPerLevel + 1, keysCount);
- }
-}
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/commons/json/test/JSONAssert.java b/src/test/java/org/apache/sling/commons/json/test/JSONAssert.java
deleted file mode 100644
index dfde82d..0000000
--- a/src/test/java/org/apache/sling/commons/json/test/JSONAssert.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.test;
-
-import java.util.Iterator;
-
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.junit.Assert;
-
-/**
- * Provides assertions on equality for JSON Arrays and Objects.
- *
- * Based on code written by Andres Almiray <aalmiray@users.sourceforge.net> as
- * part of the json-lib project - http://json-lib.sourceforge.net/
- */
-public class JSONAssert extends Assert {
- /**
- * Asserts that two JSONArrays are equal.
- */
- public static void assertEquals(JSONArray expected, JSONArray actual)
- throws JSONException {
- assertEquals(null, expected, actual);
- }
-
- /**
- * Asserts that two JSONObjects are equal.
- */
- public static void assertEquals(JSONObject expected, JSONObject actual)
- throws JSONException {
- assertEquals(null, expected, actual);
- }
-
- /**
- * Asserts that two JSONArrays are equal.
- */
- public static void assertEquals(String message, JSONArray expected,
- JSONArray actual) throws JSONException {
- String header = message == null ? "" : message + ": ";
- if (expected == null) {
- fail(header + "expected array was null");
- }
- if (actual == null) {
- fail(header + "actual array was null");
- }
- if (expected == actual || expected.equals(actual)) {
- return;
- }
- if (actual.length() != expected.length()) {
- fail(header + "arrays sizes differed, expected.length()="
- + expected.length() + " actual.length()=" + actual.length());
- }
-
- int max = expected.length();
- for (int i = 0; i < max; i++) {
- Object o1 = expected.get(i);
- Object o2 = actual.get(i);
-
- // handle nulls
- if (JSONObject.NULL.equals(o1)) {
- if (JSONObject.NULL.equals(o2)) {
- continue;
- }
- fail(header + "arrays first differed at element [" + i
- + "];");
- } else {
- if (JSONObject.NULL.equals(o2)) {
- fail(header + "arrays first differed at element [" + i
- + "];");
- }
- }
-
- if (o1 instanceof JSONArray && o2 instanceof JSONArray) {
- JSONArray e = (JSONArray) o1;
- JSONArray a = (JSONArray) o2;
- assertEquals(header + "arrays first differed at element " + i
- + ";", e, a);
- } else if (o1 instanceof JSONObject && o2 instanceof JSONObject) {
- assertEquals(header + "arrays first differed at element [" + i
- + "];", (JSONObject) o1, (JSONObject) o2);
- } else if (o1 instanceof String) {
- assertEquals(header + "arrays first differed at element [" + i
- + "];", (String) o1, String.valueOf(o2));
- } else if (o2 instanceof String) {
- assertEquals(header + "arrays first differed at element [" + i
- + "];", String.valueOf(o1), (String) o2);
- } else {
- assertEquals(header + "arrays first differed at element [" + i
- + "];", o1, o2);
- }
- }
- }
-
- /**
- * Asserts that two JSONObjects are equal.
- */
- public static void assertEquals(String message, JSONObject expected,
- JSONObject actual) throws JSONException {
- String header = message == null ? "" : message + ": ";
- if (expected == null) {
- fail(header + "expected object was null");
- }
- if (actual == null) {
- fail(header + "actual object was null");
- }
- if (expected == actual /* || expected.equals( actual ) */) {
- return;
- }
-
- JSONArray expectedNames = expected.names();
- JSONArray actualNames = actual.names();
-
- if (expectedNames == null && actualNames == null) {
- return;
- }
-
- if (expectedNames == null) {
- expectedNames = new JSONArray();
- }
-
- if (actualNames == null) {
- actualNames = new JSONArray();
- }
-
- assertEquals(header
- + "names sizes differed, expected.names().length()="
- + expectedNames.length() + " actual.names().length()="
- + actualNames.length(), expectedNames.length(), actualNames
- .length());
- for (Iterator<String> keys = expected.keys(); keys.hasNext();) {
- String key = keys.next();
- Object o1 = expected.opt(key);
- Object o2 = actual.opt(key);
-
- if (JSONObject.NULL.equals(o1)) {
- if (JSONObject.NULL.equals(o2)) {
- continue;
- }
- fail(header + "objects differed at key [" + key + "];");
- } else {
- if (JSONObject.NULL.equals(o2)) {
- fail(header + "objects differed at key [" + key + "];");
- }
- }
-
- if (o1 instanceof JSONObject && o2 instanceof JSONObject) {
- assertEquals(header + "objects differed at key [" + key + "];",
- (JSONObject) o1, (JSONObject) o2);
- } else if (o1 instanceof JSONArray && o2 instanceof JSONArray) {
- assertEquals(header + "objects differed at key [" + key + "];",
- (JSONArray) o1, (JSONArray) o2);
- } else if (o1 instanceof String) {
- assertEquals(header + "objects differed at key [" + key + "];",
- (String) o1, String.valueOf(o2));
- } else if (o2 instanceof String) {
- assertEquals(header + "objects differed at key [" + key + "];",
- String.valueOf(o1), (String) o2);
- } else {
- assertEquals(header + "objects differed at key [" + key + "];",
- o1, o2);
- }
- }
- }
-
-}
diff --git a/src/test/java/org/apache/sling/commons/json/util/DespacedRendering.java b/src/test/java/org/apache/sling/commons/json/util/DespacedRendering.java
deleted file mode 100644
index 8cb088d..0000000
--- a/src/test/java/org/apache/sling/commons/json/util/DespacedRendering.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.util;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-
-/** Test the String formatting functionality of JSONObject */
-public class DespacedRendering {
- private final String despaced;
-
- /** Simplify whitespace in str and replace quotes
- * to make it easier to compare the output
- * @param spaceReplacement replaces spaces after the first one
- * */
- public DespacedRendering(String str, String spaceReplacement) throws JSONException {
-
- boolean previousWasSpace = false;
-
- // Verify that str parses
- new JSONObject(str);
-
- // And convert whitespace and quotes to
- // make comparisons easier
- final StringBuilder sb = new StringBuilder();
- for(int i=0; i < str.length(); i++) {
- final Character c = str.charAt(i);
- final boolean isWhitespace = Character.isWhitespace(c);
- if(c == '\n') {
- sb.append("-nl-");
- } else if(isWhitespace) {
- if(previousWasSpace && spaceReplacement != null) {
- sb.append(spaceReplacement);
- }
- } else if(c == '\"') {
- sb.append("_");
- } else if(c == '\"') {
- sb.append("-dq-");
- } else {
- sb.append(c);
- }
- previousWasSpace = isWhitespace;
- }
- despaced = sb.toString();
- }
-
- public DespacedRendering(String str) throws JSONException {
- this(str, null);
- }
-
-
- public DespacedRendering expect(String ...expected) {
- for(String e : expected) {
- assertTrue("Expecting " + e + " to be contained in " + despaced, despaced.contains(e));
- }
- return this;
- }
-
- public DespacedRendering assertExactMatch(String expected) {
- assertEquals("Expecting an exact match with " + expected + " at " + despaced, expected, despaced);
- return this;
- }
-
- public DespacedRendering expectLength(int n) {
- assertEquals("Expecting a String length of " + n + " for " + despaced, n, despaced.length());
- return this;
- }
-};
\ No newline at end of file
diff --git a/src/test/java/org/apache/sling/commons/json/util/TestJSONObject.java b/src/test/java/org/apache/sling/commons/json/util/TestJSONObject.java
deleted file mode 100644
index 5bba608..0000000
--- a/src/test/java/org/apache/sling/commons/json/util/TestJSONObject.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.util;
-
-import java.math.BigInteger;
-
-import org.apache.sling.commons.json.JSONArray;
-import org.apache.sling.commons.json.JSONException;
-import org.apache.sling.commons.json.JSONObject;
-import org.apache.sling.commons.json.JSONString;
-
-/** JSONObject with typical test data, used
- * for tests.
- */
-public class TestJSONObject extends JSONObject {
-
- public TestJSONObject() throws JSONException {
- put("string", "this string");
- put("int", 12);
- put("long", 42L);
- put("boolean", true);
- put("float", 12.34f);
- put("double", 45.67d);
-
- final JSONString js = new JSONString() {
- public String toJSONString() {
- return "json.string here";
- }
-
- };
- put("JSONString", js);
-
- for(int i=0; i<2; i++) {
- final JSONObject k = new JSONObject();
- final String name = "k" + i;
- k.put("name", name);
- k.put("this is", name);
- put(name, k);
- }
-
- final JSONArray a = new JSONArray();
- a.put(true).put("hello").put(52.0).put(new BigInteger("212"));
- put("array", a);
- }
-}
diff --git a/src/test/java/org/apache/sling/commons/json/util/ValidatorTest.java b/src/test/java/org/apache/sling/commons/json/util/ValidatorTest.java
deleted file mode 100644
index a7273cd..0000000
--- a/src/test/java/org/apache/sling/commons/json/util/ValidatorTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.sling.commons.json.util;
-
-import org.apache.sling.commons.json.JSONException;
-import org.junit.Test;
-
-/**
- * Test the Validator.
- */
-public class ValidatorTest {
-
- @Test
- public void testEmptyString() throws JSONException {
- Validator.validate("");
- }
-
- @Test
- public void testEmptyArray() throws JSONException {
- Validator.validate("[]");
- }
-
- @Test
- public void testEmptyObject() throws JSONException {
- Validator.validate("{}");
- }
-
- @Test
- public void testSimpleArray() throws JSONException {
- Validator.validate("[1,true,\"hallo\"]");
- }
-
- @Test
- public void testSimpleObject() throws JSONException {
- Validator.validate("{a:\"you\", b:2, c:true}");
- }
-
- @Test
- public void testNestedJSONArray() throws JSONException {
- Validator.validate("[1,true,\"hallo\", {a:1}, [1,2]]");
- }
-
- @Test
- public void testNestedJSONObject() throws JSONException {
- Validator.validate("{a:\"you\", b:2, c:true, d: {d:1}, e: []}");
- }
-
- @Test(expected=JSONException.class)
- public void testTrailingCharsArray() throws JSONException {
- Validator.validate("[1,true,\"hallo\",]");
- //---------------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTrailingCharsObject() throws JSONException {
- Validator.validate("{a:\"you\", b:2, c:true,}");
- //---------------------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyClosingBracketsArray1() throws JSONException {
- Validator.validate("[1,true,\"hallo\"]]");
- //----------------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyClosingBracketsArray2() throws JSONException {
- Validator.validate("[1,true,\"hallo\"]}");
- //----------------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyClosingBracketsArrayNested() throws JSONException {
- Validator.validate("{myobj:[1,true,\"hallo\"]],myobj2:5}");
- //-----------------------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyClosingBracketsObject1() throws JSONException {
- Validator.validate("{a:\"you\", b:2, c:true}}");
- //----------------------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyClosingBracketsObject2() throws JSONException {
- Validator.validate("{a:\"you\", b:2, c:true}]");
- //----------------------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyClosingBracketsObjectNested() throws JSONException {
- Validator.validate("{myobj:{a:\"you\", b:2, c:true}},myobj2:5}");
- //-----------------------------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyOpeningBracketsArray() throws JSONException {
- Validator.validate("[[1,true,\"hallo\"]");
- //-----------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyOpeningBracketsArrayNested() throws JSONException {
- Validator.validate("{myobj:[[1,true,\"hallo\"],myobj2:5}");
- //------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyOpeningBracketsObject() throws JSONException {
- Validator.validate("{{a:\"you\", b:2, c:true}");
- //-----------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testTooManyOpeningBracketsObjectNested() throws JSONException {
- Validator.validate("{myobj:{{a:\"you\", b:2, c:true},myobj2:5}");
- //------------------invalid ^
- }
-
- @Test(expected=JSONException.class)
- public void testOpeningBrackedOnlyArray() throws JSONException {
- Validator.validate("[");
- }
-
- @Test(expected=JSONException.class)
- public void testOpeningBrackedOnlyObject() throws JSONException {
- Validator.validate("{");
- }
-
- @Test(expected=JSONException.class)
- public void testUnclosedArray() throws JSONException {
- Validator.validate("[1,true,\"hallo\"");
- }
-
- @Test(expected=JSONException.class)
- public void testUnclosedObject() throws JSONException {
- Validator.validate("{a:\"you\", b:2, c:true");
- }
-
-}