From ed9686a5e403c06fac588c2fe82a840c89b61e30 Mon Sep 17 00:00:00 2001 From: "John D. Ament" Date: Sun, 17 Jul 2016 19:05:19 -0400 Subject: [PATCH] ARTEMIS-565 Replace json.org with javax.json Javax.json is a newer JSR, but has an ASF compliant version, is pretty close to the original JSON.org API and will support a standard annotation based JSON-B solution at some point soon. Updated integration tests and removed JSON.org from license. --- LICENSE | 28 - .../artemis/utils/StringEscapeUtils.java | 108 ++ artemis-core-client/pom.xml | 8 + .../activemq/artemis/api/core/JsonUtil.java | 306 ++++ .../api/core/TransportConfiguration.java | 12 + .../core/management/AddressSettingsInfo.java | 22 +- .../api/core/management/DayCounterInfo.java | 46 +- .../api/core/management/ManagementHelper.java | 209 +-- .../artemis/api/core/management/RoleInfo.java | 19 +- .../activemq/artemis/core/security/Role.java | 16 + .../artemis/utils/json/JSONArray.java | 931 ---------- .../artemis/utils/json/JSONException.java | 56 - .../artemis/utils/json/JSONObject.java | 1540 ----------------- .../artemis/utils/json/JSONString.java | 43 - .../artemis/utils/json/JSONTokener.java | 414 ----- .../management/AddressSettingsInfoTest.java | 77 + artemis-distribution/pom.xml | 8 + .../src/main/assembly/dep.xml | 2 + artemis-jms-client/pom.xml | 1 - .../api/jms/management/JMSConnectionInfo.java | 18 +- .../api/jms/management/JMSConsumerInfo.java | 19 +- .../api/jms/management/JMSSessionInfo.java | 20 +- .../api/jms/management/SubscriptionInfo.java | 19 +- artemis-jms-server/pom.xml | 8 + .../management/impl/JMSQueueControlImpl.java | 11 +- .../management/impl/JMSServerControlImpl.java | 133 +- .../management/impl/JMSTopicControlImpl.java | 34 +- .../jms/server/impl/JMSServerManagerImpl.java | 25 +- .../core/management/MessageCounterInfo.java | 35 +- .../impl/ActiveMQServerControlImpl.java | 101 +- .../management/impl/AddressControlImpl.java | 8 +- .../impl/BroadcastGroupControlImpl.java | 9 +- .../impl/ClusterConnectionControlImpl.java | 15 +- .../management/impl/QueueControlImpl.java | 57 +- .../artemis/core/server/ServerSession.java | 4 +- .../core/server/impl/ServerSessionImpl.java | 27 +- .../core/transaction/TransactionDetail.java | 41 +- pom.xml | 17 +- tests/integration-tests/pom.xml | 10 + .../aerogear/AeroGearBasicServerTest.java | 50 +- .../management/JMSQueueControlTest.java | 19 +- .../management/JMSServerControlTest.java | 11 +- .../server/management/TopicControlTest.java | 21 +- .../management/ActiveMQServerControlTest.java | 23 +- .../management/BroadcastGroupControlTest.java | 7 +- .../ClusterConnectionControlTest.java | 7 +- .../management/ManagementHelperTest.java | 81 - .../ManagementWithPagingServerTest.java | 17 +- .../management/QueueControlTest.java | 49 +- 49 files changed, 1036 insertions(+), 3706 deletions(-) create mode 100644 artemis-commons/src/main/java/org/apache/activemq/artemis/utils/StringEscapeUtils.java create mode 100644 artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JsonUtil.java delete mode 100644 artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONArray.java delete mode 100644 artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONException.java delete mode 100644 artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONObject.java delete mode 100644 artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONString.java delete mode 100644 artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONTokener.java create mode 100644 artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfoTest.java diff --git a/LICENSE b/LICENSE index 695ea182db8..f5d288d0510 100644 --- a/LICENSE +++ b/LICENSE @@ -201,34 +201,6 @@ See the License for the specific language governing permissions and limitations under the License. -=============================================================== -= For json processor files. = -= See: src/main/java/org/apache/activemq/utils/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. - - =============================================================== = For Base64.java file = =============================================================== diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/StringEscapeUtils.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/StringEscapeUtils.java new file mode 100644 index 00000000000..ecff4da0da5 --- /dev/null +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/StringEscapeUtils.java @@ -0,0 +1,108 @@ +/* + * 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.activemq.artemis.utils; + +public abstract class StringEscapeUtils { + /** + * Adapted from commons lang StringEscapeUtils, escapes a string + * + * @param str + * @return an escaped version of the input string. + */ + public static String escapeString(String str) { + if (str == null) { + return str; + } + int sz = str.length(); + StringBuilder stringBuilder = new StringBuilder(str.length()); + for (int i = 0; i < sz; i++) { + char ch = str.charAt(i); + + // handle unicode + if (ch > 0xfff) { + stringBuilder.append("\\u").append(hex(ch)); + } + else if (ch > 0xff) { + stringBuilder.append("\\u0").append(hex(ch)); + } + else if (ch > 0x7f) { + stringBuilder.append("\\u00").append(hex(ch)); + } + else if (ch < 32) { + switch (ch) { + case '\b': + stringBuilder.append('\\').append('b'); + break; + case '\n': + stringBuilder.append('\\').append('n'); + break; + case '\t': + stringBuilder.append('\\').append('t'); + break; + case '\f': + stringBuilder.append('\\').append('f'); + break; + case '\r': + stringBuilder.append('\\').append('r'); + break; + default : + if (ch > 0xf) { + stringBuilder.append("\\u00").append(hex(ch)); + } + else { + stringBuilder.append("\\u000").append(hex(ch)); + } + break; + } + } + else { + switch (ch) { + case '\'': + stringBuilder.append('\\').append('\''); + break; + case '"': + stringBuilder.append('\\').append('"'); + break; + case '\\': + stringBuilder.append('\\').append('\\'); + break; + case '/': + stringBuilder.append('\\').append('/'); + break; + default : + stringBuilder.append(ch); + break; + } + } + } + return stringBuilder.toString(); + } + + /** + *

Returns an upper case hexadecimal String for the given + * character.

+ * + * @param ch The character to convert. + * @return An upper case hexadecimal String + */ + private static String hex(char ch) { + return Integer.toHexString(ch).toUpperCase(); + } +} diff --git a/artemis-core-client/pom.xml b/artemis-core-client/pom.xml index 57bbe85c143..4ec156373e0 100644 --- a/artemis-core-client/pom.xml +++ b/artemis-core-client/pom.xml @@ -68,6 +68,14 @@ junit test + + org.apache.geronimo.specs + geronimo-json_1.0_spec + + + org.apache.johnzon + johnzon-core + diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JsonUtil.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JsonUtil.java new file mode 100644 index 00000000000..dbfec9aae91 --- /dev/null +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/JsonUtil.java @@ -0,0 +1,306 @@ +/* + * 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.activemq.artemis.api.core; + +import org.apache.activemq.artemis.core.client.ActiveMQClientMessageBundle; +import org.apache.activemq.artemis.utils.Base64; +import org.apache.activemq.artemis.utils.StringEscapeUtils; + +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonArrayBuilder; +import javax.json.JsonNumber; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; +import javax.json.JsonString; +import javax.json.JsonValue; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeDataSupport; +import java.io.ByteArrayInputStream; +import java.io.ObjectInputStream; +import java.io.StringReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public final class JsonUtil { + public static JsonArray toJSONArray(final Object[] array) throws Exception { + JsonArrayBuilder jsonArray = Json.createArrayBuilder(); + + for (Object parameter : array) { + if (parameter instanceof Map) { + Map map = (Map) parameter; + + JsonObjectBuilder jsonObject = Json.createObjectBuilder(); + + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + + Object val = entry.getValue(); + + if (val != null) { + if (val.getClass().isArray()) { + JsonArray objectArray = toJSONArray((Object[]) val); + jsonObject.add(key, objectArray); + } + else { + addToObject(key, val, jsonObject); + } + } + } + jsonArray.add(jsonObject); + } + else { + if (parameter != null) { + Class clz = parameter.getClass(); + + if (clz.isArray()) { + Object[] innerArray = (Object[]) parameter; + + if (innerArray instanceof CompositeData[]) { + JsonArrayBuilder innerJsonArray = Json.createArrayBuilder(); + for (Object data : innerArray) { + String s = Base64.encodeObject((CompositeDataSupport) data); + innerJsonArray.add(s); + } + JsonObjectBuilder jsonObject = Json.createObjectBuilder(); + jsonObject.add(CompositeData.class.getName(), innerJsonArray); + jsonArray.add(jsonObject); + } + else { + jsonArray.add(toJSONArray(innerArray)); + } + } + else { + addToArray(parameter, jsonArray); + } + } + else { + jsonArray.addNull(); + } + } + } + return jsonArray.build(); + } + + public static Object[] fromJsonArray(final JsonArray jsonArray) throws Exception { + Object[] array = new Object[jsonArray.size()]; + + for (int i = 0; i < jsonArray.size(); i++) { + Object val = jsonArray.get(i); + + if (val instanceof JsonArray) { + Object[] inner = fromJsonArray((JsonArray) val); + + array[i] = inner; + } + else if (val instanceof JsonObject) { + JsonObject jsonObject = (JsonObject) val; + + Map map = new HashMap<>(); + + Set keys = jsonObject.keySet(); + + for (String key : keys) { + Object innerVal = jsonObject.get(key); + + if (innerVal instanceof JsonArray) { + innerVal = fromJsonArray(((JsonArray) innerVal)); + } + else if (innerVal instanceof JsonObject) { + Map innerMap = new HashMap<>(); + JsonObject o = (JsonObject) innerVal; + Set innerKeys = o.keySet(); + for (String k : innerKeys) { + innerMap.put(k, o.get(k)); + } + innerVal = innerMap; + } + else if (innerVal instanceof JsonNumber) { + JsonNumber jsonNumber = (JsonNumber)innerVal; + innerVal = jsonNumber.longValue(); + } + if (CompositeData.class.getName().equals(key)) { + Object[] data = (Object[]) innerVal; + CompositeData[] cds = new CompositeData[data.length]; + for (int i1 = 0; i1 < data.length; i1++) { + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(Base64.decode((data[i1].toString())))); + cds[i1] = (CompositeDataSupport) ois.readObject(); + } + innerVal = cds; + } + + map.put(key, innerVal); + } + + array[i] = map; + } + else { + if (val == JsonObject.NULL) { + array[i] = null; + } + else { + array[i] = val; + } + } + } + + return array; + } + + public static JsonValue nullSafe(String input) { + return new NullableJsonString(input); + } + + public static void addToObject(final String key, final Object param, final JsonObjectBuilder jsonObjectBuilder) { + if (param instanceof Integer) { + jsonObjectBuilder.add(key, (Integer) param); + } + else if (param instanceof Long) { + jsonObjectBuilder.add(key, (Long) param); + } + else if (param instanceof Double) { + jsonObjectBuilder.add(key, (Double) param); + } + else if (param instanceof String) { + jsonObjectBuilder.add(key, (String) param); + } + else if (param instanceof Boolean) { + jsonObjectBuilder.add(key, (Boolean) param); + } + else if (param instanceof Map) { + JsonObject mapObject = toJsonObject((Map) param); + jsonObjectBuilder.add(key, mapObject); + } + else if (param instanceof Short) { + jsonObjectBuilder.add(key, (Short) param); + } + else if (param instanceof Byte) { + //?? + } + else if (param instanceof SimpleString) { + jsonObjectBuilder.add(key, param.toString()); + } + else { + throw ActiveMQClientMessageBundle.BUNDLE.invalidManagementParam(param.getClass().getName()); + } + } + + public static void addToArray(final Object param, final JsonArrayBuilder jsonArrayBuilder) { + if (param instanceof Integer) { + jsonArrayBuilder.add((Integer) param); + } + else if (param instanceof Long) { + jsonArrayBuilder.add((Long) param); + } + else if (param instanceof Double) { + jsonArrayBuilder.add((Double) param); + } + else if (param instanceof String) { + jsonArrayBuilder.add((String) param); + } + else if (param instanceof Boolean) { + jsonArrayBuilder.add((Boolean) param); + } + else if (param instanceof Map) { + JsonObject mapObject = toJsonObject((Map) param); + jsonArrayBuilder.add(mapObject); + } + else if (param instanceof Short) { + jsonArrayBuilder.add((Short) param); + } + else if (param instanceof Byte) { + //?? + } + else { + throw ActiveMQClientMessageBundle.BUNDLE.invalidManagementParam(param.getClass().getName()); + } + } + + public static JsonArray toJsonArray(List strings) { + JsonArrayBuilder array = Json.createArrayBuilder(); + if (strings != null) { + for (String connector : strings) { + array.add(connector); + } + } + return array.build(); + } + + public static JsonObject toJsonObject(Map map) { + JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); + if (map != null) { + for (Map.Entry entry : map.entrySet()) { + addToObject(entry.getKey(), entry.getValue(), jsonObjectBuilder); + } + } + return jsonObjectBuilder.build(); + } + + public static JsonArray readJsonArray(String jsonString) { + return Json.createReader(new StringReader(jsonString)).readArray(); + } + + public static JsonObject readJsonObject(String jsonString) { + return Json.createReader(new StringReader(jsonString)).readObject(); + } + + private JsonUtil() { + } + + private static class NullableJsonString implements JsonValue, JsonString { + private final String value; + private String escape; + + NullableJsonString(String value) { + if (value == null || value.length() == 0) { + this.value = null; + } + else { + this.value = value; + } + } + + @Override + public ValueType getValueType() { + return value == null ? ValueType.NULL : ValueType.STRING; + } + + @Override + public String getString() { + return this.value; + } + + @Override + public CharSequence getChars() { + return getString(); + } + + public String toString() { + if (this.value == null) { + return null; + } + String s = this.escape; + if (s == null) { + s = '\"' + StringEscapeUtils.escapeString(this.value) + '\"'; + this.escape = s; + } + return s; + } + } +} diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfiguration.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfiguration.java index a3e1d7cc383..3b9d9273a6f 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfiguration.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/TransportConfiguration.java @@ -25,6 +25,9 @@ import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.utils.UUIDGenerator; +import javax.json.Json; +import javax.json.JsonObject; + /** * A TransportConfiguration is used by a client to specify connections to a server and its backup if * one exists. @@ -61,6 +64,15 @@ public class TransportConfiguration implements Serializable { private static final byte TYPE_STRING = 3; + public JsonObject toJson() { + return Json.createObjectBuilder() + .add("name", name) + .add("factoryClassName", factoryClassName) + .add("params", JsonUtil.toJsonObject(params)) + .add("extraProps", JsonUtil.toJsonObject(extraProps)) + .build(); + } + /** * Utility method for splitting a comma separated list of hosts * diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfo.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfo.java index d4f5232ffbf..062ba46cfe7 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfo.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfo.java @@ -16,7 +16,9 @@ */ package org.apache.activemq.artemis.api.core.management; -import org.apache.activemq.artemis.utils.json.JSONObject; +import org.apache.activemq.artemis.api.core.JsonUtil; + +import javax.json.JsonObject; // XXX no javadocs public final class AddressSettingsInfo { @@ -63,9 +65,21 @@ public final class AddressSettingsInfo { // Static -------------------------------------------------------- - public static AddressSettingsInfo from(final String jsonString) throws Exception { - JSONObject object = new JSONObject(jsonString); - return new AddressSettingsInfo(object.getString("addressFullMessagePolicy"), object.getLong("maxSizeBytes"), object.getInt("pageSizeBytes"), object.getInt("pageCacheMaxSize"), object.getInt("maxDeliveryAttempts"), object.getLong("redeliveryDelay"), object.getDouble("redeliveryMultiplier"), object.getLong("maxRedeliveryDelay"), object.getString("DLA"), object.getString("expiryAddress"), object.getBoolean("lastValueQueue"), object.getLong("redistributionDelay"), object.getBoolean("sendToDLAOnNoRoute"), object.getLong("slowConsumerThreshold"), object.getLong("slowConsumerCheckPeriod"), object.getString("slowConsumerPolicy"), object.getBoolean("autoCreateJmsQueues"), object.getBoolean("autoDeleteJmsQueues"), object.getBoolean("autoCreateJmsTopics"), object.getBoolean("autoDeleteJmsTopics")); + public static AddressSettingsInfo from(final String jsonString) { + JsonObject object = JsonUtil.readJsonObject(jsonString); + return new AddressSettingsInfo(object.getString("addressFullMessagePolicy"), + object.getJsonNumber("maxSizeBytes").longValue(), object.getInt("pageSizeBytes"), object.getInt("pageCacheMaxSize"), + object.getInt("maxDeliveryAttempts"), + object.getJsonNumber("redeliveryDelay").longValue(), + object.getJsonNumber("redeliveryMultiplier").doubleValue(), + object.getJsonNumber("maxRedeliveryDelay").longValue(), + object.getString("DLA"), object.getString("expiryAddress"), object.getBoolean("lastValueQueue"), + object.getJsonNumber("redistributionDelay").longValue(), object.getBoolean("sendToDLAOnNoRoute"), + object.getJsonNumber("slowConsumerThreshold").longValue(), + object.getJsonNumber("slowConsumerCheckPeriod").longValue(), + object.getString("slowConsumerPolicy"), object.getBoolean("autoCreateJmsQueues"), + object.getBoolean("autoDeleteJmsQueues"), object.getBoolean("autoCreateJmsTopics"), + object.getBoolean("autoDeleteJmsTopics")); } // Constructors -------------------------------------------------- diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DayCounterInfo.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DayCounterInfo.java index 422772f0c1b..b6b4e8e14d7 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DayCounterInfo.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/DayCounterInfo.java @@ -16,11 +16,13 @@ */ package org.apache.activemq.artemis.api.core.management; -import java.util.Arrays; +import org.apache.activemq.artemis.api.core.JsonUtil; -import org.apache.activemq.artemis.utils.json.JSONArray; -import org.apache.activemq.artemis.utils.json.JSONException; -import org.apache.activemq.artemis.utils.json.JSONObject; +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; /** * Helper class to create Java Objects from the @@ -34,31 +36,35 @@ public final class DayCounterInfo { // Static -------------------------------------------------------- - public static String toJSON(final DayCounterInfo[] infos) throws JSONException { - JSONObject json = new JSONObject(); - JSONArray counters = new JSONArray(); + public static String toJSON(final DayCounterInfo[] infos) { + JsonObjectBuilder json = Json.createObjectBuilder(); + JsonArrayBuilder counters = Json.createArrayBuilder(); for (DayCounterInfo info : infos) { - JSONObject counter = new JSONObject(); - counter.put("date", info.getDate()); - counter.put("counters", Arrays.asList(info.getCounters())); - counters.put(counter); + JsonArrayBuilder counter = Json.createArrayBuilder(); + for (int c : info.getCounters()) { + counter.add(c); + } + JsonObjectBuilder dci = Json.createObjectBuilder() + .add("date", info.getDate()) + .add("counters", counter); + counters.add(dci); } - json.put("dayCounters", counters); - return json.toString(); + json.add("dayCounters", counters); + return json.build().toString(); } /** * Returns an array of RoleInfo corresponding to the JSON serialization returned * by {@link QueueControl#listMessageCounterHistory()}. */ - public static DayCounterInfo[] fromJSON(final String jsonString) throws JSONException { - JSONObject json = new JSONObject(jsonString); - JSONArray dayCounters = json.getJSONArray("dayCounters"); - DayCounterInfo[] infos = new DayCounterInfo[dayCounters.length()]; - for (int i = 0; i < dayCounters.length(); i++) { + public static DayCounterInfo[] fromJSON(final String jsonString) { + JsonObject json = JsonUtil.readJsonObject(jsonString); + JsonArray dayCounters = json.getJsonArray("dayCounters"); + DayCounterInfo[] infos = new DayCounterInfo[dayCounters.size()]; + for (int i = 0; i < dayCounters.size(); i++) { - JSONObject counter = (JSONObject) dayCounters.get(i); - JSONArray hour = (JSONArray) counter.getJSONArray("counters").get(0); + JsonObject counter = (JsonObject) dayCounters.get(i); + JsonArray hour = counter.getJsonArray("counters"); int[] hourCounters = new int[24]; for (int j = 0; j < 24; j++) { hourCounters[j] = hour.getInt(j); diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java index 98fafc4da3e..61a9306c0d0 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java @@ -16,22 +16,11 @@ */ package org.apache.activemq.artemis.api.core.management; -import java.io.ByteArrayInputStream; -import java.io.ObjectInputStream; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.apache.activemq.artemis.api.core.SimpleString; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.api.core.Message; -import org.apache.activemq.artemis.core.client.ActiveMQClientMessageBundle; -import org.apache.activemq.artemis.utils.Base64; -import org.apache.activemq.artemis.utils.json.JSONArray; -import org.apache.activemq.artemis.utils.json.JSONObject; +import org.apache.activemq.artemis.api.core.SimpleString; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; +import javax.json.JsonArray; /** * Helper class to use ActiveMQ Artemis Core messages to manage server resources. @@ -138,7 +127,7 @@ public static void putOperationInvocation(final Message message, String paramString; if (parameters != null) { - JSONArray jsonArray = ManagementHelper.toJSONArray(parameters); + JsonArray jsonArray = JsonUtil.toJSONArray(parameters); paramString = jsonArray.toString(); } @@ -149,151 +138,6 @@ public static void putOperationInvocation(final Message message, message.getBodyBuffer().writeNullableSimpleString(SimpleString.toSimpleString(paramString)); } - private static JSONArray toJSONArray(final Object[] array) throws Exception { - JSONArray jsonArray = new JSONArray(); - - for (Object parameter : array) { - if (parameter instanceof Map) { - Map map = (Map) parameter; - - JSONObject jsonObject = new JSONObject(); - - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - - Object val = entry.getValue(); - - if (val != null) { - if (val.getClass().isArray()) { - val = ManagementHelper.toJSONArray((Object[]) val); - } - else { - ManagementHelper.checkType(val); - } - } - - jsonObject.put(key, val); - } - - jsonArray.put(jsonObject); - } - else { - if (parameter != null) { - Class clz = parameter.getClass(); - - if (clz.isArray()) { - Object[] innerArray = (Object[]) parameter; - - if (innerArray instanceof CompositeData[]) { - JSONArray jsonArray1 = new JSONArray(); - for (Object data : innerArray) { - String s = Base64.encodeObject((CompositeDataSupport)data); - jsonArray1.put(s); - } - JSONObject jsonObject = new JSONObject(); - jsonObject.put(CompositeData.class.getName(), jsonArray1); - jsonArray.put(jsonObject); - System.out.println("ManagementHelper.toJSONArray"); - } - else { - jsonArray.put(ManagementHelper.toJSONArray(innerArray)); - } - } - else { - ManagementHelper.checkType(parameter); - - jsonArray.put(parameter); - } - } - else { - jsonArray.put((Object) null); - } - } - } - - return jsonArray; - } - - private static Object[] fromJSONArray(final JSONArray jsonArray) throws Exception { - Object[] array = new Object[jsonArray.length()]; - - for (int i = 0; i < jsonArray.length(); i++) { - Object val = jsonArray.get(i); - - if (val instanceof JSONArray) { - Object[] inner = ManagementHelper.fromJSONArray((JSONArray) val); - - array[i] = inner; - } - else if (val instanceof JSONObject) { - JSONObject jsonObject = (JSONObject) val; - - Map map = new HashMap<>(); - - Iterator iter = jsonObject.keys(); - - while (iter.hasNext()) { - String key = iter.next(); - - Object innerVal = jsonObject.get(key); - - if (innerVal instanceof JSONArray) { - innerVal = ManagementHelper.fromJSONArray(((JSONArray) innerVal)); - } - else if (innerVal instanceof JSONObject) { - Map innerMap = new HashMap<>(); - JSONObject o = (JSONObject) innerVal; - Iterator it = o.keys(); - while (it.hasNext()) { - String k = (String) it.next(); - innerMap.put(k, o.get(k)); - } - innerVal = innerMap; - } - else if (innerVal instanceof Integer) { - innerVal = ((Integer) innerVal).longValue(); - } - - if (CompositeData.class.getName().equals(key)) { - Object[] data = (Object[]) innerVal; - CompositeData[] cds = new CompositeData[data.length]; - for (int i1 = 0; i1 < data.length; i1++) { - ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(Base64.decode((data[i1].toString())))); - cds[i1] = (CompositeDataSupport) ois.readObject(); - } - innerVal = cds; - } - - map.put(key, innerVal); - } - - array[i] = map; - } - else { - if (val == JSONObject.NULL) { - array[i] = null; - } - else { - array[i] = val; - } - } - } - - return array; - } - - private static void checkType(final Object param) { - if (param instanceof Integer == false && param instanceof Long == false && - param instanceof Double == false && - param instanceof String == false && - param instanceof Boolean == false && - param instanceof Map == false && - param instanceof Byte == false && - param instanceof Short == false) { - throw ActiveMQClientMessageBundle.BUNDLE.invalidManagementParam(param.getClass().getName()); - } - } - /** * Used by ActiveMQ Artemis management service. */ @@ -302,9 +146,9 @@ public static Object[] retrieveOperationParameters(final Message message) throws String jsonString = (sstring == null) ? null : sstring.toString(); if (jsonString != null) { - JSONArray jsonArray = new JSONArray(jsonString); + JsonArray jsonArray = JsonUtil.readJsonArray(jsonString); - return ManagementHelper.fromJSONArray(jsonArray); + return JsonUtil.fromJsonArray(jsonArray); } else { return null; @@ -334,7 +178,7 @@ public static void storeResult(final Message message, final Object result) throw if (result != null) { // Result is stored in body, also encoded as JSON array of length 1 - JSONArray jsonArray = ManagementHelper.toJSONArray(new Object[]{result}); + JsonArray jsonArray = JsonUtil.toJSONArray(new Object[]{result}); resultString = jsonArray.toString(); } @@ -356,11 +200,8 @@ public static Object[] getResults(final Message message) throws Exception { String jsonString = (sstring == null) ? null : sstring.toString(); if (jsonString != null) { - JSONArray jsonArray = new JSONArray(jsonString); - - Object[] res = ManagementHelper.fromJSONArray(jsonArray); - - return res; + JsonArray jsonArray = JsonUtil.readJsonArray(jsonString); + return JsonUtil.fromJsonArray(jsonArray); } else { return null; @@ -397,38 +238,6 @@ public static boolean hasOperationSucceeded(final Message message) { return false; } - /** - * Used by ActiveMQ Artemis management service. - */ - public static Map fromCommaSeparatedKeyValues(final String str) throws Exception { - if (str == null || str.trim().length() == 0) { - return Collections.emptyMap(); - } - - // create a JSON array with 1 object: - JSONArray array = new JSONArray("[{" + str + "}]"); - Map params = (Map) ManagementHelper.fromJSONArray(array)[0]; - return params; - } - - /** - * Used by ActiveMQ Artemis management service. - */ - public static Object[] fromCommaSeparatedArrayOfCommaSeparatedKeyValues(final String str) throws Exception { - if (str == null || str.trim().length() == 0) { - return new Object[0]; - } - - String s = str; - - // if there is a single item, we wrap it in to make it a JSON object - if (!s.trim().startsWith("{")) { - s = "{" + s + "}"; - } - JSONArray array = new JSONArray("[" + s + "]"); - return ManagementHelper.fromJSONArray(array); - } - private ManagementHelper() { } } diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/RoleInfo.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/RoleInfo.java index d8c78ea18c9..01be093525b 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/RoleInfo.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/RoleInfo.java @@ -16,8 +16,10 @@ */ package org.apache.activemq.artemis.api.core.management; -import org.apache.activemq.artemis.utils.json.JSONArray; -import org.apache.activemq.artemis.utils.json.JSONObject; +import org.apache.activemq.artemis.api.core.JsonUtil; + +import javax.json.JsonArray; +import javax.json.JsonObject; /** * Helper class to create Java Objects from the @@ -48,11 +50,14 @@ public final class RoleInfo { * by {@link AddressControl#getRolesAsJSON()}. */ public static RoleInfo[] from(final String jsonString) throws Exception { - JSONArray array = new JSONArray(jsonString); - RoleInfo[] roles = new RoleInfo[array.length()]; - for (int i = 0; i < array.length(); i++) { - JSONObject r = array.getJSONObject(i); - RoleInfo role = new RoleInfo(r.getString("name"), r.getBoolean("send"), r.getBoolean("consume"), r.getBoolean("createDurableQueue"), r.getBoolean("deleteDurableQueue"), r.getBoolean("createNonDurableQueue"), r.getBoolean("deleteNonDurableQueue"), r.getBoolean("manage"), r.getBoolean("browse")); + JsonArray array = JsonUtil.readJsonArray(jsonString); + RoleInfo[] roles = new RoleInfo[array.size()]; + for (int i = 0; i < array.size(); i++) { + JsonObject r = array.getJsonObject(i); + RoleInfo role = new RoleInfo(r.getString("name"), r.getBoolean("send"), + r.getBoolean("consume"), r.getBoolean("createDurableQueue"), + r.getBoolean("deleteDurableQueue"), r.getBoolean("createNonDurableQueue"), + r.getBoolean("deleteNonDurableQueue"), r.getBoolean("manage"), r.getBoolean("browse")); roles[i] = role; } return roles; diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/Role.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/Role.java index 732da6d55bd..baa872a5ed8 100644 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/Role.java +++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/security/Role.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.core.security; +import javax.json.Json; +import javax.json.JsonObject; import java.io.Serializable; /** @@ -43,6 +45,20 @@ public class Role implements Serializable { private final boolean browse; + public JsonObject toJson() { + return Json.createObjectBuilder() + .add("name", name) + .add("send", send) + .add("consume", consume) + .add("createDurableQueue", createDurableQueue) + .add("deleteDurableQueue", deleteDurableQueue) + .add("createNonDurableQueue", createNonDurableQueue) + .add("deleteNonDurableQueue", deleteNonDurableQueue) + .add("manage", manage) + .add("browse", browse) + .build(); + } + /** * @deprecated Use {@link #Role(String, boolean, boolean, boolean, boolean, boolean, boolean, boolean, boolean)} * @param name diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONArray.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONArray.java deleted file mode 100644 index 0b8fd0c9b18..00000000000 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONArray.java +++ /dev/null @@ -1,931 +0,0 @@ -/* -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. -*/ -package org.apache.activemq.artemis.utils.json; - -import java.io.IOException; -import java.io.Writer; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; - -/** - * A JSONArray is an ordered sequence of values. Its external text form is a - * string wrapped in square brackets with commas separating the values. The - * internal form is an object having get and opt - * methods for accessing the values by index, and put methods for - * adding or replacing values. The values can be any of these types: - * Boolean, JSONArray, JSONObject, - * Number, {@code string}, or the - * JSONObject.NULL object. - *

- * The constructor can convert a JSON text into a Java object. The - * toString method converts to JSON text. - *

- * A get method returns a value if one can be found, and throws an - * exception if one cannot be found. An opt method returns a - * default value instead of throwing an exception, and so is useful for - * obtaining optional values. - *

- * The generic get() and opt() methods return an - * object which you can cast or query for type. There are also typed - * get and opt methods that do type checking and type - * coercion for you. - *

- * The texts produced by the toString methods strictly conform to - * JSON syntax rules. The constructors are more forgiving in the texts they will - * accept: - *

    - *
  • An extra , (comma) may appear just - * before the closing bracket.
  • - *
  • The {@code null} value will be inserted when there - * is , (comma) elision.
  • - *
  • Strings may be quoted with ' (single - * quote).
  • - *
  • 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: - * { } [ ] / \ : , = ; # and if they do not look like numbers - * and if they are not the reserved words true, - * false, or {@code null}.
  • - *
  • Values can be separated by ; (semicolon) as - * well as by , (comma).
  • - *
  • Numbers may have the 0- (octal) or - * 0x- (hex) prefix.
  • - *
- */ -public class JSONArray { - - /** - * The arrayList where the JSONArray's properties are kept. - */ - private final ArrayList myArrayList; - - /** - * Construct an empty JSONArray. - */ - public JSONArray() { - myArrayList = new ArrayList<>(); - } - - /** - * Construct a JSONArray from a JSONTokener. - * - * @param x A JSONTokener - * @throws JSONException If there is a syntax error. - */ - public JSONArray(final JSONTokener x) throws JSONException { - this(); - char c = x.nextClean(); - char q; - if (c == '[') { - q = ']'; - } - else if (c == '(') { - q = ')'; - } - else { - throw x.syntaxError("A JSONArray text must start with '['"); - } - if (x.nextClean() == ']') { - return; - } - x.back(); - for (;;) { - if (x.nextClean() == ',') { - x.back(); - myArrayList.add(null); - } - else { - x.back(); - myArrayList.add(x.nextValue()); - } - c = x.nextClean(); - switch (c) { - case ';': - case ',': - if (x.nextClean() == ']') { - return; - } - x.back(); - break; - case ']': - case ')': - if (q != c) { - throw x.syntaxError("Expected a '" + Character.valueOf(q) + "'"); - } - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); - } - } - } - - /** - * Construct a JSONArray from a source JSON text. - * - * @param source A string that begins with - * [ (left bracket) - * and ends with ] (right bracket). - * @throws JSONException If there is a syntax error. - */ - public JSONArray(final String source) throws JSONException { - this(new JSONTokener(source)); - } - - /** - * Construct a JSONArray from a Collection. - * - * @param collection A Collection. - */ - public JSONArray(final Collection collection) { - myArrayList = collection == null ? new ArrayList<>() : new ArrayList<>(collection); - } - - /** - * Construct a JSONArray from a collection of beans. - * The collection should have Java Beans. - */ - public JSONArray(final Collection collection, final boolean includeSuperClass) { - myArrayList = collection == null ? new ArrayList<>() : new ArrayList<>(collection.size()); - if (collection != null) { - Iterator iter = collection.iterator(); - while (iter.hasNext()) { - Object o = iter.next(); - if (o instanceof Map) { - myArrayList.add(new JSONObject((Map) o, includeSuperClass)); - } - else if (!JSONObject.isStandardProperty(o.getClass())) { - myArrayList.add(new JSONObject(o, includeSuperClass)); - } - else { - myArrayList.add(o); - } - } - } - } - - /** - * Construct a JSONArray from an array - * - * @throws JSONException If not an array. - */ - public JSONArray(final Object array) throws JSONException { - this(); - if (array.getClass().isArray()) { - int length = Array.getLength(array); - for (int i = 0; i < length; i += 1) { - this.put(Array.get(array, i)); - } - } - else { - throw new JSONException("JSONArray initial value should be a string or collection or array."); - } - } - - /** - * Construct a JSONArray from an array with a bean. - * The array should have Java Beans. - * - * @throws JSONException If not an array. - */ - public JSONArray(final Object array, final boolean includeSuperClass) throws JSONException { - this(); - if (array.getClass().isArray()) { - int length = Array.getLength(array); - for (int i = 0; i < length; i += 1) { - Object o = Array.get(array, i); - if (JSONObject.isStandardProperty(o.getClass())) { - myArrayList.add(o); - } - else { - myArrayList.add(new JSONObject(o, includeSuperClass)); - } - } - } - else { - throw new JSONException("JSONArray initial value should be a string or collection or array."); - } - } - - /** - * 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(final 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(final 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(final 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(final 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(final int index) throws JSONException { - Object o = get(index); - if (o instanceof JSONArray) { - return (JSONArray) o; - } - 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(final int index) throws JSONException { - Object o = get(index); - if (o instanceof JSONObject) { - return (JSONObject) o; - } - 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(final 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(final 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(final int index) { - return JSONObject.NULL.equals(opt(index)); - } - - /** - * Make a string from the contents of this JSONArray. The - * separator 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(final String separator) throws JSONException { - int len = length(); - StringBuffer sb = new StringBuffer(); - - for (int i = 0; i < len; i += 1) { - if (i > 0) { - sb.append(separator); - } - sb.append(JSONObject.valueToString(myArrayList.get(i))); - } - return sb.toString(); - } - - /** - * Get the number of elements in the JSONArray, included nulls. - * - * @return The length (or size). - */ - public int length() { - return 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(final int index) { - return index < 0 || index >= length() ? null : 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(final 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(final int index, final 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(final 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(final int index, final 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(final 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(final int index, final 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(final int index) { - Object o = opt(index); - return o instanceof JSONArray ? (JSONArray) o : 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(final int index) { - Object o = opt(index); - return o instanceof JSONObject ? (JSONObject) o : 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(final 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(final int index, final 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 converted to a string. - * - * @param index The index must be between 0 and length() - 1. - * @return A String value. - */ - public String optString(final 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(final int index, final 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(final 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(final 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. - * @return this. - * @throws JSONException if the value is not finite. - */ - public JSONArray put(final double value) throws JSONException { - Double d = Double.valueOf(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(final int value) { - put(Integer.valueOf(value)); - return this; - } - - /** - * Append a long value. This increases the array's length by one. - * - * @param value A long value. - * @return this. - */ - public JSONArray put(final long value) { - put(Long.valueOf(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(final Map 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(final Object value) { - 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(final int index, final 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(final int index, final 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(final int index, final double value) throws JSONException { - put(index, Double.valueOf(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(final int index, final int value) throws JSONException { - put(index, Integer.valueOf(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(final int index, final long value) throws JSONException { - put(index, Long.valueOf(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(final int index, final Map 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(final int index, final Object value) throws JSONException { - JSONObject.testValidity(value); - if (index < 0) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - if (index < length()) { - myArrayList.set(index, value); - } - else { - while (index != length()) { - put(JSONObject.NULL); - } - put(value); - } - return this; - } - - /** - * Remove an index and close the hole. - * - * @param index The index of the element to be removed. - * @return The value that was associated with the index, - * or null if there was no value. - */ - public Object remove(final int index) { - Object o = opt(index); - myArrayList.remove(index); - return o; - } - - /** - * 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(final 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), opt(i)); - } - return jo; - } - - /** - * Make a JSON text of this 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. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, transmittable - * representation of the array. - */ - @Override - public String toString() { - try { - return '[' + join(",") + ']'; - } - catch (Exception e) { - return ""; - } - } - - /** - * Make a pretty-printed 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 - * [ (left bracket) and ending with ] - *  (right bracket). - * @throws JSONException - */ - public String toString(final int indentFactor) throws JSONException { - return toString(indentFactor, 0); - } - - /** - * Make a pretty-printed 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(final int indentFactor, final int indent) throws JSONException { - int len = length(); - if (len == 0) { - return "[]"; - } - int i; - StringBuffer sb = new StringBuffer("["); - if (len == 1) { - sb.append(JSONObject.valueToString(myArrayList.get(0), indentFactor, indent)); - } - else { - int newindent = indent + indentFactor; - sb.append('\n'); - for (i = 0; i < len; i += 1) { - if (i > 0) { - sb.append(",\n"); - } - for (int j = 0; j < newindent; j += 1) { - sb.append(' '); - } - sb.append(JSONObject.valueToString(myArrayList.get(i), indentFactor, newindent)); - } - sb.append('\n'); - for (i = 0; i < indent; i += 1) { - sb.append(' '); - } - } - sb.append(']'); - return sb.toString(); - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. - * For compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(final Writer writer) throws JSONException { - try { - boolean b = false; - int len = length(); - - writer.write('['); - - for (int i = 0; i < len; i += 1) { - if (b) { - writer.write(','); - } - Object v = myArrayList.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); - } - } -} diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONException.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONException.java deleted file mode 100644 index abb79b0429d..00000000000 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONException.java +++ /dev/null @@ -1,56 +0,0 @@ -/* -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. -*/ -package org.apache.activemq.artemis.utils.json; - -/** - * The JSONException is thrown by the JSON.org classes then things are amiss. - */ -public class JSONException extends Exception { - - /** - * - */ - private static final long serialVersionUID = -3940674325153571604L; - - private Throwable cause; - - /** - * Constructs a JSONException with an explanatory message. - * - * @param message Detail about the reason for the exception. - */ - public JSONException(final String message) { - super(message); - } - - public JSONException(final Throwable t) { - super(t.getMessage()); - cause = t; - } - - @Override - public synchronized Throwable getCause() { - return cause; - } -} diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONObject.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONObject.java deleted file mode 100644 index ce1053ff640..00000000000 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONObject.java +++ /dev/null @@ -1,1540 +0,0 @@ -/* -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. -*/ -package org.apache.activemq.artemis.utils.json; - -import java.io.IOException; -import java.io.Writer; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.TreeSet; - -/** - * 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 get - * and opt methods for accessing the values by name, and put methods for - * adding or replacing values by name. - *

- * The values can be any of these types: Boolean, JSONArray, - * JSONObject, Number, {@code string}, or the - * JSONObject.NULL 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 get and - * opt methods, or to convert values into a JSON text using the put and - * toString methods. A get method returns a value if one can be found, and - * throws an exception if one cannot be found. An opt method returns a default value - * instead of throwing an exception, and so is useful for obtaining optional values. - *

- * The generic get() and opt() methods return an object, which you can - * cast or query for type. There are also typed get and opt methods that - * do type checking and type coercion for you. - *

- * The put methods adds values to an object. For example, - * - *

- * myString = new JSONObject().put("JSON", "Hello, World!").toString();
- * 
- * - * produces the string {"JSON": "Hello, World"}. - *

- * The texts produced by the toString methods strictly conform to the JSON syntax - * rules. The constructors are more forgiving in the texts they will accept: - *

    - *
  • An extra , (comma) may appear just before the closing brace. - *
  • - *
  • Strings may be quoted with ' (single quote).
  • - *
  • 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: { } [ ] / \ : , = ; # and if they do not look like numbers and if they - * are not the reserved words true, false, or {@code null}.
  • - *
  • Keys can be followed by = or => as well as by :.
  • - *
  • Values can be followed by ; (semicolon) as well as by - * , (comma).
  • - *
  • Numbers may have the 0- (octal) or 0x- - * (hex) prefix.
  • - *
- */ -public class JSONObject { - - /** - * 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. - */ - @Override - protected 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. - */ - @Override - public boolean equals(final Object object) { - return object == null || object == this; - } - - @Override - public int hashCode() { - // TODO - return 0; - } - - /** - * Get the "null" string value. - * - * @return The string "null". - */ - @Override - public String toString() { - return "null"; - } - } - - /** - * The map where the JSONObject's properties are kept. - */ - private final Map map; - - /** - * It is sometimes more convenient and less ambiguous to have a - * {@code null} object than to use Java's {@code null} value. - * JSONObject.NULL.equals(null) returns true. - * JSONObject.NULL.toString() returns "null". - */ - public static final Object NULL = new Null(); - - /** - * Construct an empty JSONObject. - */ - public JSONObject() { - map = new HashMap(); - } - - /** - * 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 names An array of strings. - * @throws JSONException If a value is a non-finite number or if a name is duplicated. - */ - public JSONObject(final JSONObject jo, final String[] names) throws JSONException { - this(); - for (String name : names) { - putOnce(name, jo.opt(name)); - } - } - - /** - * 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 - * or a duplicated key. - */ - public JSONObject(final JSONTokener x) throws JSONException { - this(); - 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"); - } - putOnce(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(final Map map) { - this.map = map == null ? new HashMap() : map; - } - - /** - * Construct a JSONObject from a Map. - * - * Note: Use this constructor when the map contains <key,bean>. - * - * @param map - A map with Key-Bean data. - * @param includeSuperClass - Tell whether to include the super class properties. - */ - public JSONObject(final Map map, final boolean includeSuperClass) { - this.map = new HashMap(); - if (map != null) { - Iterator i = map.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry e = i.next(); - if (JSONObject.isStandardProperty(e.getValue().getClass())) { - this.map.put(e.getKey(), e.getValue()); - } - else { - this.map.put(e.getKey(), new JSONObject(e.getValue(), includeSuperClass)); - } - } - } - } - - /** - * Construct a JSONObject from an Object using bean getters. - * It reflects on all of the public methods of the object. - * For each of the methods with no parameters and a name starting - * with "get" or "is" followed by an uppercase letter, - * the method is invoked, and a key and the value returned from the getter method - * are put into the new JSONObject. - * - * The key is formed by removing the "get" or "is" prefix. - * If the second remaining character is not upper case, then the first - * character is converted to lower case. - * - * For example, if an object has a method named "getName", and - * if the result of calling object.getName() is "Larry Fine", - * then the JSONObject will contain "name": "Larry Fine". - * - * @param bean An object that has getter methods that should be used - * to make a JSONObject. - */ - public JSONObject(final Object bean) { - this(); - populateInternalMap(bean, false); - } - - /** - * Construct a JSONObject from an Object using bean getters. - * It reflects on all of the public methods of the object. - * For each of the methods with no parameters and a name starting - * with "get" or "is" followed by an uppercase letter, - * the method is invoked, and a key and the value returned from the getter method - * are put into the new JSONObject. - * - * The key is formed by removing the "get" or "is" prefix. - * If the second remaining character is not upper case, then the first - * character is converted to lower case. - * - * @param bean An object that has getter methods that should be used - * to make a JSONObject. - * @param includeSuperClass If true, include the super class properties. - */ - public JSONObject(final Object bean, final boolean includeSuperClass) { - this(); - populateInternalMap(bean, includeSuperClass); - } - - private void populateInternalMap(final Object bean, boolean includeSuperClass) { - Class klass = bean.getClass(); - - /* If klass.getSuperClass is System class then force includeSuperClass to false. */ - - if (klass.getClassLoader() == null) { - includeSuperClass = false; - } - - Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); - for (Method method : methods) { - try { - if (Modifier.isPublic(method.getModifiers())) { - String name = method.getName(); - String key = ""; - if (name.startsWith("get")) { - key = name.substring(3); - } - else if (name.startsWith("is")) { - key = name.substring(2); - } - if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { - if (key.length() == 1) { - key = key.toLowerCase(); - } - else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() + key.substring(1); - } - - Object result = method.invoke(bean, (Object[]) null); - if (result == null) { - map.put(key, JSONObject.NULL); - } - else if (result.getClass().isArray()) { - map.put(key, new JSONArray(result, includeSuperClass)); - } - else if (result instanceof Collection) { // List or Set - map.put(key, new JSONArray((Collection) result, includeSuperClass)); - } - else if (result instanceof Map) { - map.put(key, new JSONObject((Map) result, includeSuperClass)); - } - else if (JSONObject.isStandardProperty(result.getClass())) { // Primitives, String and Wrapper - map.put(key, result); - } - else { - if (result.getClass().getPackage().getName().startsWith("java") || result.getClass().getClassLoader() == null) { - map.put(key, result.toString()); - } - else { // User defined Objects - map.put(key, new JSONObject(result, includeSuperClass)); - } - } - } - } - } - catch (IllegalAccessException | InvocationTargetException | JSONException e) { - throw new RuntimeException(e); - } - } - } - - static boolean isStandardProperty(final Class clazz) { - return clazz.isPrimitive() || clazz.isAssignableFrom(Byte.class) || - clazz.isAssignableFrom(Short.class) || - clazz.isAssignableFrom(Integer.class) || - clazz.isAssignableFrom(Long.class) || - clazz.isAssignableFrom(Float.class) || - clazz.isAssignableFrom(Double.class) || - clazz.isAssignableFrom(Character.class) || - clazz.isAssignableFrom(String.class) || - clazz.isAssignableFrom(Boolean.class); - } - - /** - * 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 obtained - * from the object. - */ - public JSONObject(final Object object, final String[] names) { - this(); - Class c = object.getClass(); - for (String name : names) { - try { - putOpt(name, c.getField(name).get(object)); - } - catch (Exception e) { - /* forget about it */ - } - } - } - - /** - * Construct a JSONObject from a source JSON text string. - * This is the most commonly used JSONObject constructor. - * - * @param source A string beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If there is a syntax error in the source - * string or a duplicated key. - */ - public JSONObject(final String source) throws JSONException { - this(new JSONTokener(source)); - } - - /** - * 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(final String key, final Object value) throws JSONException { - JSONObject.testValidity(value); - Object o = opt(key); - if (o == null) { - put(key, value instanceof JSONArray ? new JSONArray().put(value) : 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(final String key, final Object value) throws JSONException { - JSONObject.testValidity(value); - Object o = opt(key); - if (o == null) { - put(key, new JSONArray().put(value)); - } - else if (o instanceof JSONArray) { - put(key, ((JSONArray) o).put(value)); - } - else { - throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); - } - return this; - } - - /** - * 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 static String doubleToString(final 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; - } - - /** - * 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(final String key) throws JSONException { - Object o = opt(key); - if (o == null) { - throw new JSONException("JSONObject[" + 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(final 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[" + 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(final 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[" + 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(final 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(final String key) throws JSONException { - Object o = get(key); - if (o instanceof JSONArray) { - return (JSONArray) o; - } - throw new JSONException("JSONObject[" + 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(final String key) throws JSONException { - Object o = get(key); - if (o instanceof JSONObject) { - return (JSONObject) o; - } - throw new JSONException("JSONObject[" + 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(final String key) throws JSONException { - Object o = get(key); - return o instanceof Number ? ((Number) o).longValue() : (long) getDouble(key); - } - - /** - * Get an array of field names from a JSONObject. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(final JSONObject jo) { - int length = jo.length(); - if (length == 0) { - return null; - } - Iterator i = jo.keys(); - String[] names = new String[length]; - int j = 0; - while (i.hasNext()) { - names[j] = (String) i.next(); - j += 1; - } - return names; - } - - /** - * Get an array of field names from an Object. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(final Object object) { - if (object == null) { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if (length == 0) { - return null; - } - String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; - } - - /** - * 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(final 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(final String key) { - return map.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(final 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 keys() { - return map.keySet().iterator(); - } - - /** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - public int length() { - return map.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 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. - */ - public static String numberToString(final Number n) throws JSONException { - if (n == null) { - throw new JSONException("Null pointer"); - } - JSONObject.testValidity(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; - } - - /** - * 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(final String key) { - return key == null ? null : map.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(final 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(final String key, final 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(final String key, final 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(final 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(final String key, final 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(final 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(final String key, final 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(final 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(final 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(final 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(final String key, final 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 converted to a string. - * - * @param key A key string. - * @return A string which is the value. - */ - public String optString(final 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(final String key, final 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(final String key, final 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(final String key, final double value) throws JSONException { - put(key, Double.valueOf(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(final String key, final int value) throws JSONException { - put(key, Integer.valueOf(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(final String key, final long value) throws JSONException { - put(key, Long.valueOf(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(final String key, final Map 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(final String key, final Object value) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - if (value != null) { - JSONObject.testValidity(value); - map.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, and only if there is not already a member - * with that name. - * - * @param key - * @param value - * @return his. - * @throws JSONException if the key is a duplicate - */ - public JSONObject putOnce(final String key, final Object value) throws JSONException { - if (key != null && value != null) { - if (opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - put(key, value); - } - 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(final String key, final 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(final String string) { - if (string == null || string.length() == 0) { - return "\"\""; - } - - char b; - char c = 0; - int i; - int len = string.length(); - StringBuffer sb = new StringBuffer(len + 4); - 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" + t.substring(t.length() - 4)); - } - else { - sb.append(c); - } - } - } - sb.append('"'); - return sb.toString(); - } - - /** - * 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(final String key) { - return map.remove(key); - } - - /** - * Get an enumeration of the keys of the JSONObject. - * The keys will be sorted alphabetically. - * - * @return An iterator of the keys. - */ - public Iterator sortedKeys() { - return new TreeSet(map.keySet()).iterator(); - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * - * @param s A String. - * @return A simple JSON value. - */ - public static Object stringToValue(final String s) { - if (s.equals("")) { - return s; - } - 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. - */ - - char b = s.charAt(0); - 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 Integer.valueOf(Integer.parseInt(s.substring(2), 16)); - } - catch (Exception e) { - /* Ignore the error */ - } - } - else { - try { - return Integer.valueOf(Integer.parseInt(s, 8)); - } - catch (Exception e) { - /* Ignore the error */ - } - } - } - try { - if (s.indexOf('.') > -1 || s.indexOf('e') > -1 || s.indexOf('E') > -1) { - return Double.valueOf(s); - } - else { - Long myLong = Long.valueOf(s); - if (myLong.longValue() == myLong.intValue()) { - return Integer.valueOf(myLong.intValue()); - } - else { - return myLong; - } - } - } - catch (Exception f) { - /* Ignore the error */ - } - } - return s; - } - - /** - * Throw an exception if the object is a NaN or infinite number. - * - * @param o The object to test. - * @throws JSONException If o is a non-finite number. - */ - static void testValidity(final 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."); - } - } - } - } - - /** - * 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(final 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(opt(names.getString(i))); - } - return ja; - } - - /** - * Make a JSON text of this JSONObject. For compactness, no whitespace - * is added. If this would not result in a syntactically correct JSON text, - * then null will be returned instead. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, portable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - */ - @Override - public String toString() { - try { - Iterator keys = keys(); - StringBuilder sb = new StringBuilder("{"); - - while (keys.hasNext()) { - if (sb.length() > 1) { - sb.append(','); - } - Object o = keys.next(); - sb.append(JSONObject.quote(o.toString())); - sb.append(':'); - sb.append(JSONObject.valueToString(map.get(o))); - } - sb.append('}'); - return sb.toString(); - } - catch (JSONException e) { - return null; - } - } - - /** - * Make a prettyprinted JSON text of this JSONObject. - *

- * 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 { (left brace) and ending - * with } (right brace). - * @throws JSONException If the object contains an invalid number. - */ - public String toString(final int indentFactor) throws JSONException { - return toString(indentFactor, 0); - } - - /** - * Make a prettyprinted JSON text of this JSONObject. - *

- * 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 indentation of the top level. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the object contains an invalid number. - */ - String toString(final int indentFactor, final int indent) throws JSONException { - int j; - int n = length(); - if (n == 0) { - return "{}"; - } - Iterator keys = sortedKeys(); - StringBuffer sb = new StringBuffer("{"); - int newindent = indent + indentFactor; - Object o; - if (n == 1) { - o = keys.next(); - sb.append(JSONObject.quote(o.toString())); - sb.append(": "); - sb.append(JSONObject.valueToString(map.get(o), indentFactor, indent)); - } - else { - while (keys.hasNext()) { - o = keys.next(); - if (sb.length() > 1) { - sb.append(",\n"); - } - else { - sb.append('\n'); - } - for (j = 0; j < newindent; j += 1) { - sb.append(' '); - } - sb.append(JSONObject.quote(o.toString())); - sb.append(": "); - sb.append(JSONObject.valueToString(map.get(o), indentFactor, newindent)); - } - if (sb.length() > 1) { - sb.append('\n'); - for (j = 0; j < indent; j += 1) { - sb.append(' '); - } - } - } - sb.append('}'); - return sb.toString(); - } - - /** - * Make a JSON text of an Object value. If the object has an - * value.toJSONString() method, then that method will be used to produce - * the JSON text. The method is required to produce a strictly - * conforming text. If the object does not contain a toJSONString - * method (which is the most common case), then a text will be - * produced by other means. If the value is an array or Collection, - * then a JSONArray will be made from it and its toJSONString method - * will be called. If the value is a MAP, then a JSONObject will be made - * from it and its toJSONString method will be called. Otherwise, the - * value's toString method will be called, and the result will be quoted. - * - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param value The value to be serialized. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the value is or contains an invalid number. - */ - static String valueToString(final Object value) throws JSONException { - if (value == null || JSONObject.NULL == value) { - return "null"; - } - if (value instanceof JSONString) { - String o; - try { - o = ((JSONString) value).toJSONString(); - } - catch (RuntimeException e) { - throw new JSONException(e); - } - if (o == null) - throw new JSONException("Bad value from toJSONString: " + o); - return o; - } - if (value instanceof Number) { - return JSONObject.numberToString((Number) value); - } - if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - return new JSONObject((Map) value).toString(); - } - if (value instanceof Collection) { - return new JSONArray((Collection) value).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - return JSONObject.quote(value.toString()); - } - - /** - * Make a prettyprinted JSON text of an object value. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param value The value to be serialized. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @param indent The indentation of the top level. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with { (left brace) and ending - * with } (right brace). - * @throws JSONException If the object contains an invalid number. - */ - static String valueToString(final Object value, final int indentFactor, final int indent) throws JSONException { - if (value == null || JSONObject.NULL == value) { - return "null"; - } - try { - if (value instanceof JSONString) { - String o = ((JSONString) value).toJSONString(); - if (o != null) - return o; - } - } - catch (RuntimeException e) { - /* forget about it */ - } - if (value instanceof Number) { - return JSONObject.numberToString((Number) value); - } - if (value instanceof Boolean) { - return value.toString(); - } - if (value instanceof JSONObject) { - return ((JSONObject) value).toString(indentFactor, indent); - } - if (value instanceof JSONArray) { - return ((JSONArray) value).toString(indentFactor, indent); - } - if (value instanceof Map) { - return new JSONObject((Map) value).toString(indentFactor, indent); - } - if (value instanceof Collection) { - return new JSONArray((Collection) value).toString(indentFactor, indent); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(indentFactor, indent); - } - return JSONObject.quote(value.toString()); - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. - * For compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(final Writer writer) throws JSONException { - try { - boolean b = false; - Iterator keys = keys(); - writer.write('{'); - - while (keys.hasNext()) { - if (b) { - writer.write(','); - } - Object k = keys.next(); - writer.write(JSONObject.quote(k.toString())); - writer.write(':'); - Object v = map.get(k); - 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); - } - } -} diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONString.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONString.java deleted file mode 100644 index 07ec907e5fe..00000000000 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONString.java +++ /dev/null @@ -1,43 +0,0 @@ -/* -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. -*/ -package org.apache.activemq.artemis.utils.json; - -/** - * The JSONString interface allows a toJSONString() - * method so that a class can change the behavior of - * JSONObject.toString(), JSONArray.toString(), - * and JSONWriter.value(Object). The - * toJSONString method will be used instead of the default behavior - * of using the Object's toString() method and quoting the result. - */ -public interface JSONString { - - /** - * The toJSONString method allows a class to produce its own JSON - * serialization. - * - * @return A strictly syntactically correct JSON text. - */ - String toJSONString(); -} diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONTokener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONTokener.java deleted file mode 100644 index 5f5153b964f..00000000000 --- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/utils/json/JSONTokener.java +++ /dev/null @@ -1,414 +0,0 @@ -/* -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. -*/ -package org.apache.activemq.artemis.utils.json; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.io.StringReader; - -/** - * 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. - */ -public class JSONTokener { - - private int index; - - private final Reader reader; - - private char lastChar; - - private boolean useLastChar; - - /** - * Construct a JSONTokener from a string. - * - * @param reader A reader. - */ - public JSONTokener(final Reader reader) { - this.reader = reader.markSupported() ? reader : new BufferedReader(reader); - useLastChar = false; - index = 0; - } - - /** - * Construct a JSONTokener from a string. - * - * @param s A source string. - */ - public JSONTokener(final String s) { - this(new StringReader(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() throws JSONException { - if (useLastChar || index <= 0) { - throw new JSONException("Stepping back two steps is not supported"); - } - index -= 1; - useLastChar = true; - } - - /** - * 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(final 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() throws JSONException { - char nextChar = next(); - if (nextChar == 0) { - return false; - } - back(); - return true; - } - - /** - * 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() throws JSONException { - if (useLastChar) { - useLastChar = false; - if (lastChar != 0) { - index += 1; - } - return lastChar; - } - int c; - try { - c = reader.read(); - } - catch (IOException exc) { - throw new JSONException(exc); - } - - if (c <= 0) { // End of stream - lastChar = 0; - return 0; - } - index += 1; - lastChar = (char) c; - return lastChar; - } - - /** - * 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(final 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(final int n) throws JSONException { - if (n == 0) { - return ""; - } - - char[] buffer = new char[n]; - int pos = 0; - - if (useLastChar) { - useLastChar = false; - buffer[0] = lastChar; - pos = 1; - } - - try { - int len; - while (pos < n && (len = reader.read(buffer, pos, n - pos)) != -1) { - pos += len; - } - } - catch (IOException exc) { - throw new JSONException(exc); - } - index += pos; - - if (pos < n) { - throw syntaxError("Substring bounds error"); - } - - lastChar = buffer[n - 1]; - return new String(buffer); - } - - /** - * Get the next char in the string, skipping whitespace. - * - * @return A character, or 0 if there are no more characters. - * @throws JSONException - */ - public char nextClean() throws JSONException { - for (;;) { - char c = next(); - 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 - * " (double quote) or - * ' (single quote). - * @return A String. - * @throws JSONException Unterminated string. - */ - public String nextString(final 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(final char d) throws JSONException { - 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 delimiter - * characters or the end of line, whichever comes first. - * - * @param delimiters A set of delimiter characters. - * @return A string, trimmed. - */ - public String nextTo(final String delimiters) throws JSONException { - 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. - * - * @return An object. - * @throws JSONException If syntax error. - */ - public Object nextValue() throws JSONException { - char c = nextClean(); - String s; - - switch (c) { - case '"': - case '\'': - return nextString(c); - case '{': - back(); - return new JSONObject(this); - case '[': - 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(); - while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { - sb.append(c); - c = next(); - } - back(); - - s = sb.toString().trim(); - if (s.equals("")) { - throw syntaxError("Missing value"); - } - return JSONObject.stringToValue(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(final char to) throws JSONException { - char c; - try { - int startIndex = index; - reader.mark(Integer.MAX_VALUE); - do { - c = next(); - if (c == 0) { - reader.reset(); - index = startIndex; - return c; - } - } while (c != to); - } - catch (IOException exc) { - throw new JSONException(exc); - } - - back(); - return c; - } - - /** - * Make a JSONException to signal a syntax error. - * - * @param message The error message. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(final String message) { - return new JSONException(message + toString()); - } - - /** - * Make a printable string of this JSONTokener. - * - * @return " at character [this.index]" - */ - @Override - public String toString() { - return " at character " + index; - } -} \ No newline at end of file diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfoTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfoTest.java new file mode 100644 index 00000000000..f47787926c1 --- /dev/null +++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/api/core/management/AddressSettingsInfoTest.java @@ -0,0 +1,77 @@ +/* + * 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.activemq.artemis.api.core.management; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class AddressSettingsInfoTest { + + @Test + public void shouldLoadFromJSON() { + String json = "{\n" + + "\"addressFullMessagePolicy\":\"fullPolicy\",\n" + + "\"maxSizeBytes\":500,\n" + + "\"pageSizeBytes\":200,\n" + + "\"pageCacheMaxSize\":3,\n" + + "\"maxDeliveryAttempts\":3,\n" + + "\"redeliveryDelay\":70000,\n" + + "\"redeliveryMultiplier\":1.5,\n" + + "\"maxRedeliveryDelay\":100000,\n" + + "\"DLA\":\"deadLettersGoHere\",\n" + + "\"expiryAddress\":\"\",\n" + + "\"lastValueQueue\":true,\n" + + "\"redistributionDelay\":10004,\n" + + "\"sendToDLAOnNoRoute\":true,\n" + + "\"slowConsumerThreshold\":200,\n" + + "\"slowConsumerCheckPeriod\":300,\n" + + "\"slowConsumerPolicy\":\"retire\",\n" + + "\"autoCreateJmsQueues\":true,\n" + + "\"autoDeleteJmsQueues\":false,\n" + + "\"autoCreateJmsTopics\":true,\n" + + "\"autoDeleteJmsTopics\":false\n" + + "}"; + AddressSettingsInfo addressSettingsInfo = AddressSettingsInfo.from(json); + assertEquals("fullPolicy", addressSettingsInfo.getAddressFullMessagePolicy()); + assertEquals(500L, addressSettingsInfo.getMaxSizeBytes()); + assertEquals(200L, addressSettingsInfo.getPageSizeBytes()); + assertEquals(3, addressSettingsInfo.getPageCacheMaxSize()); + assertEquals(3, addressSettingsInfo.getMaxDeliveryAttempts()); + assertEquals(70000, addressSettingsInfo.getRedeliveryDelay()); + assertEquals(1.5, addressSettingsInfo.getRedeliveryMultiplier(), 0); + assertEquals(100000, addressSettingsInfo.getMaxRedeliveryDelay()); + assertEquals("deadLettersGoHere", addressSettingsInfo.getDeadLetterAddress()); + assertEquals("", addressSettingsInfo.getExpiryAddress()); + assertTrue(addressSettingsInfo.isLastValueQueue()); + assertEquals(10004L, addressSettingsInfo.getRedistributionDelay()); + assertTrue(addressSettingsInfo.isSendToDLAOnNoRoute()); + assertEquals(200L, addressSettingsInfo.getSlowConsumerThreshold()); + assertEquals(300L, addressSettingsInfo.getSlowConsumerCheckPeriod()); + assertEquals("retire", addressSettingsInfo.getSlowConsumerPolicy()); + assertTrue(addressSettingsInfo.isAutoCreateJmsQueues()); + assertTrue(addressSettingsInfo.isAutoCreateJmsTopics()); + assertFalse(addressSettingsInfo.isAutoDeleteJmsQueues()); + assertFalse(addressSettingsInfo.isAutoDeleteJmsTopics()); + } + +} \ No newline at end of file diff --git a/artemis-distribution/pom.xml b/artemis-distribution/pom.xml index 0faa449bc2b..33e59a3782c 100644 --- a/artemis-distribution/pom.xml +++ b/artemis-distribution/pom.xml @@ -188,6 +188,14 @@ io.netty netty-codec-mqtt + + org.apache.geronimo.specs + geronimo-json_1.0_spec + + + org.apache.johnzon + johnzon-core + diff --git a/artemis-distribution/src/main/assembly/dep.xml b/artemis-distribution/src/main/assembly/dep.xml index 0feb531f559..a62ef25d6a6 100644 --- a/artemis-distribution/src/main/assembly/dep.xml +++ b/artemis-distribution/src/main/assembly/dep.xml @@ -93,6 +93,8 @@ org.fusesource.hawtbuf:hawtbuf org.jgroups:jgroups io.netty:netty-codec-mqtt + org.apache.geronimo.specs:geronimo-json_1.0_spec + org.apache.johnzon:johnzon-core + + + org.apache.geronimo.specs + geronimo-json_1.0_spec + ${json-p.spec.version} + + + org.apache.johnzon + johnzon-core + ${johnzon.version} + diff --git a/tests/integration-tests/pom.xml b/tests/integration-tests/pom.xml index 5d7617cc787..3622eb13785 100644 --- a/tests/integration-tests/pom.xml +++ b/tests/integration-tests/pom.xml @@ -72,6 +72,16 @@ artemis-jms-client ${project.version} + + org.apache.geronimo.specs + geronimo-json_1.0_spec + test + + + org.apache.johnzon + johnzon-core + test + org.apache.activemq artemis-jms-server diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/aerogear/AeroGearBasicServerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/aerogear/AeroGearBasicServerTest.java index ded85ec52c4..7babcfcd60e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/aerogear/AeroGearBasicServerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/aerogear/AeroGearBasicServerTest.java @@ -24,6 +24,7 @@ import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.SendAcknowledgementHandler; import org.apache.activemq.artemis.api.core.client.ServerLocator; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.ConnectorServiceConfiguration; import org.apache.activemq.artemis.core.config.CoreQueueConfiguration; @@ -31,9 +32,6 @@ import org.apache.activemq.artemis.integration.aerogear.AeroGearConnectorServiceFactory; import org.apache.activemq.artemis.integration.aerogear.AeroGearConstants; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; -import org.apache.activemq.artemis.utils.json.JSONArray; -import org.apache.activemq.artemis.utils.json.JSONException; -import org.apache.activemq.artemis.utils.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -42,6 +40,8 @@ import org.mortbay.jetty.handler.AbstractHandler; import org.mortbay.jetty.nio.SelectChannelConnector; +import javax.json.JsonArray; +import javax.json.JsonObject; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -118,7 +118,7 @@ public void aerogearSimpleReceiveTest() throws Exception { assertTrue(latch.await(5, TimeUnit.SECONDS)); assertNotNull(aeroGearHandler.jsonObject); - JSONObject body = (JSONObject) aeroGearHandler.jsonObject.get("message"); + JsonObject body = aeroGearHandler.jsonObject.getJsonObject("message"); assertNotNull(body); String prop1 = body.getString("AEROGEAR_PROP1"); assertNotNull(prop1); @@ -132,25 +132,24 @@ public void aerogearSimpleReceiveTest() throws Exception { String sound = body.getString("sound"); assertNotNull(sound); assertEquals(sound, "sound1"); - String badge = body.getString("badge"); + int badge = body.getInt("badge"); assertNotNull(badge); - assertEquals(badge, "99"); - JSONArray jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("variants"); + assertEquals(badge, 99); + JsonArray jsonArray = aeroGearHandler.jsonObject.getJsonArray("variants"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "variant1"); assertEquals(jsonArray.getString(1), "variant2"); - jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("alias"); + jsonArray = aeroGearHandler.jsonObject.getJsonArray("alias"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "me"); assertEquals(jsonArray.getString(1), "him"); assertEquals(jsonArray.getString(2), "them"); - jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("deviceType"); + jsonArray = aeroGearHandler.jsonObject.getJsonArray("deviceType"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "android"); assertEquals(jsonArray.getString(1), "ipad"); - Integer ttl = (Integer) aeroGearHandler.jsonObject.get("ttl"); - assertNotNull(ttl); - assertEquals(ttl.intValue(), 3600); + int ttl = aeroGearHandler.jsonObject.getInt("ttl"); + assertEquals(ttl, 3600); latch = new CountDownLatch(1); aeroGearHandler.resetLatch(latch); @@ -167,7 +166,7 @@ public void aerogearSimpleReceiveTest() throws Exception { producer.send(m); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertNotNull(aeroGearHandler.jsonObject); - body = (JSONObject) aeroGearHandler.jsonObject.get("message"); + body = aeroGearHandler.jsonObject.getJsonObject("message"); assertNotNull(body); alert = body.getString("alert"); assertNotNull(alert); @@ -175,24 +174,22 @@ public void aerogearSimpleReceiveTest() throws Exception { sound = body.getString("sound"); assertNotNull(sound); assertEquals(sound, "s1"); - badge = body.getString("badge"); - assertNotNull(badge); - assertEquals(badge, "111"); - jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("variants"); + badge = body.getInt("badge"); + assertEquals(badge, 111); + jsonArray = aeroGearHandler.jsonObject.getJsonArray("variants"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "v1"); assertEquals(jsonArray.getString(1), "v2"); - jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("alias"); + jsonArray = aeroGearHandler.jsonObject.getJsonArray("alias"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "alias1"); assertEquals(jsonArray.getString(1), "alias2"); - jsonArray = (JSONArray) aeroGearHandler.jsonObject.get("deviceType"); + jsonArray = aeroGearHandler.jsonObject.getJsonArray("deviceType"); assertNotNull(jsonArray); assertEquals(jsonArray.getString(0), "dev1"); assertEquals(jsonArray.getString(1), "dev2"); - ttl = (Integer) aeroGearHandler.jsonObject.get("ttl"); - assertNotNull(ttl); - assertEquals(ttl.intValue(), 10000); + ttl = aeroGearHandler.jsonObject.getInt("ttl"); + assertEquals(ttl, 10000); session.start(); ClientMessage message = session.createConsumer("testQueue").receiveImmediate(); assertNull(message); @@ -200,7 +197,7 @@ public void aerogearSimpleReceiveTest() throws Exception { class AeroGearHandler extends AbstractHandler { - JSONObject jsonObject; + JsonObject jsonObject; private CountDownLatch latch; AeroGearHandler(CountDownLatch latch) { @@ -219,12 +216,7 @@ public void handle(String target, byte[] bytes = new byte[httpServletRequest.getContentLength()]; httpServletRequest.getInputStream().read(bytes); String json = new String(bytes); - try { - jsonObject = new JSONObject(json); - } - catch (JSONException e) { - jsonObject = null; - } + jsonObject = JsonUtil.readJsonObject(json); latch.countDown(); } diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlTest.java index 90aa8f98a9a..406dc8fc63c 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSQueueControlTest.java @@ -43,6 +43,7 @@ import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.api.jms.JMSFactoryType; @@ -68,10 +69,10 @@ import org.apache.activemq.artemis.tests.unit.util.InVMNamingContext; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.UUIDGenerator; -import org.apache.activemq.artemis.utils.json.JSONArray; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import javax.json.JsonArray; /** * A QueueControlTest @@ -111,9 +112,9 @@ public void testGetXXXCount() throws Exception { Assert.assertEquals(1, queueControl.getConsumerCount()); - JSONArray jsonArray = new JSONArray(queueControl.listConsumersAsJSON()); + JsonArray jsonArray = JsonUtil.readJsonArray(queueControl.listConsumersAsJSON()); - assertEquals(1, jsonArray.length()); + assertEquals(1, jsonArray.size()); JMSUtil.sendMessages(queue, 2); @@ -433,17 +434,17 @@ public void testListMessagesAsJSONWithNullFilter() throws Exception { String jsonString = queueControl.listMessagesAsJSON(null); Assert.assertNotNull(jsonString); - JSONArray array = new JSONArray(jsonString); - Assert.assertEquals(2, array.length()); - Assert.assertEquals(ids[0], array.getJSONObject(0).get("JMSMessageID")); - Assert.assertEquals(ids[1], array.getJSONObject(1).get("JMSMessageID")); + JsonArray array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(2, array.size()); + Assert.assertEquals(ids[0], array.getJsonObject(0).getString("JMSMessageID")); + Assert.assertEquals(ids[1], array.getJsonObject(1).getString("JMSMessageID")); JMSUtil.consumeMessages(2, queue); jsonString = queueControl.listMessagesAsJSON(null); Assert.assertNotNull(jsonString); - array = new JSONArray(jsonString); - Assert.assertEquals(0, array.length()); + array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(0, array.size()); } @Test diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlTest.java index 11546fce893..41bfc708031 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/JMSServerControlTest.java @@ -22,6 +22,7 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; import org.apache.activemq.artemis.api.core.management.AddressControl; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; import org.apache.activemq.artemis.api.core.management.ResourceNames; import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; @@ -48,7 +49,6 @@ import org.apache.activemq.artemis.tests.unit.util.InVMNamingContext; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.RandomUtil; -import org.apache.activemq.artemis.utils.json.JSONArray; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -66,6 +66,7 @@ import javax.jms.XAConnection; import javax.jms.XAConnectionFactory; import javax.jms.XASession; +import javax.json.JsonArray; import javax.naming.NamingException; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; @@ -627,15 +628,15 @@ public void testListAllConsumers() throws Exception { // create a consumer will create a Core queue bound to the topic address MessageConsumer cons = session.createConsumer(topic); - JSONArray jsonArray = new JSONArray(control.listAllConsumersAsJSON()); + JsonArray jsonArray = JsonUtil.readJsonArray(control.listAllConsumersAsJSON()); - Assert.assertEquals(1 + getNumberOfConsumers(), jsonArray.length()); + Assert.assertEquals(1 + getNumberOfConsumers(), jsonArray.size()); cons.close(); - jsonArray = new JSONArray(control.listAllConsumersAsJSON()); + jsonArray = JsonUtil.readJsonArray(control.listAllConsumersAsJSON()); - Assert.assertEquals(getNumberOfConsumers(), jsonArray.length()); + Assert.assertEquals(getNumberOfConsumers(), jsonArray.size()); String topicAddress = ActiveMQDestination.createTopicAddressFromName(topicName).toString(); AddressControl addressControl = (AddressControl) server.getManagementService().getResource(ResourceNames.CORE_ADDRESS + topicAddress); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlTest.java index 238aaa05b0c..25fd608b655 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/server/management/TopicControlTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.artemis.tests.integration.jms.server.management; import org.apache.activemq.artemis.api.core.client.ActiveMQClient; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; import org.apache.activemq.artemis.api.jms.ActiveMQJMSClient; import org.apache.activemq.artemis.api.jms.management.JMSServerControl; @@ -37,7 +38,6 @@ import org.apache.activemq.artemis.tests.integration.management.ManagementTestBase; import org.apache.activemq.artemis.tests.unit.util.InVMNamingContext; import org.apache.activemq.artemis.utils.RandomUtil; -import org.apache.activemq.artemis.utils.json.JSONArray; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -51,6 +51,7 @@ import javax.jms.Session; import javax.jms.TextMessage; import javax.jms.TopicSubscriber; +import javax.json.JsonArray; import javax.management.Notification; import java.util.ArrayList; import java.util.Arrays; @@ -159,9 +160,9 @@ public void testListXXXSubscriptionsCount() throws Exception { String json = topicControl.listAllSubscriptionsAsJSON(); System.out.println("Json: " + json); - JSONArray jsonArray = new JSONArray(json); + JsonArray jsonArray = JsonUtil.readJsonArray(json); - Assert.assertEquals(3, jsonArray.length()); + Assert.assertEquals(3, jsonArray.size()); connection_1.close(); connection_2.close(); @@ -221,17 +222,17 @@ public void testListXXXSubscriptionsAsJSONJMS2() throws Exception { SubscriptionInfo[] infos = SubscriptionInfo.from(jsonString); Assert.assertEquals(2, infos.length); - Assert.assertTrue(infos[0].getClientID().length() == 0); + Assert.assertNull(infos[0].getClientID()); Assert.assertTrue(infos[0].getName().equals(subscriptionName)); - Assert.assertTrue(infos[1].getClientID().length() == 0); + Assert.assertNull(infos[1].getClientID()); Assert.assertTrue(infos[1].getName().equals(subscriptionName + "2")); jsonString = topicControl.listNonDurableSubscriptionsAsJSON(); infos = SubscriptionInfo.from(jsonString); Assert.assertEquals(1, infos.length); - Assert.assertEquals(null, infos[0].getClientID()); - Assert.assertEquals(null, infos[0].getName()); + Assert.assertNull(infos[0].getClientID()); + Assert.assertNull(infos[0].getName()); jsonString = topicControl.listAllSubscriptionsAsJSON(); infos = SubscriptionInfo.from(jsonString); @@ -442,10 +443,10 @@ public void testListMessagesForSubscriptionAsJSON() throws Exception { TopicControl topicControl = createManagementControl(); String jsonString = topicControl.listMessagesForSubscriptionAsJSON(ActiveMQDestination.createQueueNameForDurableSubscription(true, clientID, subscriptionName)); Assert.assertNotNull(jsonString); - JSONArray array = new JSONArray(jsonString); - Assert.assertEquals(3, array.length()); + JsonArray array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(3, array.size()); for (int i = 0; i < 3; i++) { - Assert.assertEquals(ids[i], array.getJSONObject(i).get("JMSMessageID")); + Assert.assertEquals(ids[i], array.getJsonObject(i).getString("JMSMessageID")); } connection.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlTest.java index 2d4d98361d2..7de651d1616 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ActiveMQServerControlTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.integration.management; +import javax.json.JsonArray; +import javax.json.JsonObject; import javax.transaction.xa.XAResource; import javax.transaction.xa.Xid; import java.util.HashMap; @@ -33,6 +35,7 @@ import org.apache.activemq.artemis.api.core.management.AddressSettingsInfo; import org.apache.activemq.artemis.api.core.management.BridgeControl; import org.apache.activemq.artemis.api.core.management.DivertControl; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.api.core.management.ObjectNameBuilder; import org.apache.activemq.artemis.api.core.management.QueueControl; import org.apache.activemq.artemis.api.core.management.RoleInfo; @@ -47,8 +50,6 @@ import org.apache.activemq.artemis.jlibaio.LibaioContext; import org.apache.activemq.artemis.utils.RandomUtil; import org.apache.activemq.artemis.utils.UUIDGenerator; -import org.apache.activemq.artemis.utils.json.JSONArray; -import org.apache.activemq.artemis.utils.json.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -154,12 +155,12 @@ public void testGetConnectorsAsJSON() throws Exception { String jsonString = serverControl.getConnectorsAsJSON(); Assert.assertNotNull(jsonString); - JSONArray array = new JSONArray(jsonString); - Assert.assertEquals(1, array.length()); - JSONObject data = array.getJSONObject(0); - Assert.assertEquals(connectorConfig.getName(), data.optString("name")); - Assert.assertEquals(connectorConfig.getFactoryClassName(), data.optString("factoryClassName")); - Assert.assertEquals(connectorConfig.getParams().size(), data.getJSONObject("params").length()); + JsonArray array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(1, array.size()); + JsonObject data = array.getJsonObject(0); + Assert.assertEquals(connectorConfig.getName(), data.getString("name")); + Assert.assertEquals(connectorConfig.getFactoryClassName(), data.getString("factoryClassName")); + Assert.assertEquals(connectorConfig.getParams().size(), data.getJsonObject("params").size()); } @Test @@ -755,10 +756,10 @@ public void testListPreparedTransactionDetails() throws Exception { ActiveMQServerControl serverControl = createManagementControl(); - JSONArray jsonArray = new JSONArray(serverControl.listProducersInfoAsJSON()); + JsonArray jsonArray = JsonUtil.readJsonArray(serverControl.listProducersInfoAsJSON()); - assertEquals(1, jsonArray.length()); - assertEquals(4, ((JSONObject) jsonArray.get(0)).getInt("msgSent")); + assertEquals(1, jsonArray.size()); + assertEquals(4, ((JsonObject) jsonArray.get(0)).getInt("msgSent")); clientSession.close(); locator.close(); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlTest.java index 0298eb4ee89..ce8873f5728 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/BroadcastGroupControlTest.java @@ -20,15 +20,16 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration; import org.apache.activemq.artemis.api.core.UDPBroadcastEndpointFactory; import org.apache.activemq.artemis.api.core.management.BroadcastGroupControl; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.utils.RandomUtil; -import org.apache.activemq.artemis.utils.json.JSONArray; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import javax.json.JsonArray; import java.util.ArrayList; import java.util.List; @@ -54,8 +55,8 @@ public void testAttributes() throws Exception { Assert.assertEquals(broadcastGroupConfig.getConnectorInfos().get(0), connectorPairData); String jsonString = broadcastGroupControl.getConnectorPairsAsJSON(); Assert.assertNotNull(jsonString); - JSONArray array = new JSONArray(jsonString); - Assert.assertEquals(1, array.length()); + JsonArray array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(1, array.size()); Assert.assertEquals(broadcastGroupConfig.getConnectorInfos().get(0), array.getString(0)); Assert.assertTrue(broadcastGroupControl.isStarted()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlTest.java index 98b9bedcdf5..f2b85eca05e 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ClusterConnectionControlTest.java @@ -16,6 +16,7 @@ */ package org.apache.activemq.artemis.tests.integration.management; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.core.server.cluster.impl.MessageLoadBalancingType; import org.junit.Before; import org.junit.After; @@ -26,6 +27,7 @@ import java.util.List; import java.util.Map; +import javax.json.JsonArray; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; @@ -48,7 +50,6 @@ import org.apache.activemq.artemis.core.server.management.Notification; import org.apache.activemq.artemis.tests.integration.SimpleNotificationService; import org.apache.activemq.artemis.utils.RandomUtil; -import org.apache.activemq.artemis.utils.json.JSONArray; public class ClusterConnectionControlTest extends ManagementTestBase { @@ -91,8 +92,8 @@ public void testAttributes1() throws Exception { String jsonString = clusterConnectionControl.getStaticConnectorsAsJSON(); Assert.assertNotNull(jsonString); - JSONArray array = new JSONArray(jsonString); - Assert.assertEquals(1, array.length()); + JsonArray array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(1, array.size()); Assert.assertEquals(clusterConnectionConfig1.getStaticConnectors().get(0), array.getString(0)); Assert.assertNull(clusterConnectionControl.getDiscoveryGroupName()); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementHelperTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementHelperTest.java index bf72cc663c3..9fb95e7af6f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementHelperTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementHelperTest.java @@ -227,87 +227,6 @@ public void testMapWithArrayValues() throws Exception { } - @Test - public void testFromCommaSeparatedKeyValues() throws Exception { - String str = "key1=1, key2=false, key3=2.0, key4=whatever"; - - Map map = ManagementHelper.fromCommaSeparatedKeyValues(str); - Assert.assertEquals(4, map.size()); - Assert.assertTrue(map.containsKey("key1")); - Assert.assertEquals(1L, map.get("key1")); - - Assert.assertTrue(map.containsKey("key2")); - Assert.assertEquals(false, map.get("key2")); - - Assert.assertTrue(map.containsKey("key3")); - Assert.assertEquals(2.0, map.get("key3")); - - Assert.assertTrue(map.containsKey("key4")); - Assert.assertEquals("whatever", map.get("key4")); - } - - @Test - public void testFromCommaSeparatedArrayOfCommaSeparatedKeyValuesForSingleItem() throws Exception { - // if there is a single item, no need to enclose it in { } - String str = "k11=1, k12=false, k13=2.0, k14=whatever "; - - Object[] objects = ManagementHelper.fromCommaSeparatedArrayOfCommaSeparatedKeyValues(str); - Assert.assertEquals(1, objects.length); - - Assert.assertTrue(objects[0] instanceof Map); - Map map = (Map) objects[0]; - Assert.assertEquals(4, map.size()); - Assert.assertTrue(map.containsKey("k11")); - Assert.assertEquals(1L, map.get("k11")); - - Assert.assertTrue(map.containsKey("k12")); - Assert.assertEquals(false, map.get("k12")); - - Assert.assertTrue(map.containsKey("k13")); - Assert.assertEquals(2.0, map.get("k13")); - - Assert.assertTrue(map.containsKey("k14")); - Assert.assertEquals("whatever", map.get("k14")); - } - - @Test - public void testFromCommaSeparatedArrayOfCommaSeparatedKeyValues() throws Exception { - String str = "{ k11=1, k12=false, k13=2.0, k14=whatever },{ k21=2, k22=true, k23=23.0, k24=foo }"; - - Object[] objects = ManagementHelper.fromCommaSeparatedArrayOfCommaSeparatedKeyValues(str); - Assert.assertEquals(2, objects.length); - - Assert.assertTrue(objects[0] instanceof Map); - Map map = (Map) objects[0]; - Assert.assertEquals(4, map.size()); - Assert.assertTrue(map.containsKey("k11")); - Assert.assertEquals(1L, map.get("k11")); - - Assert.assertTrue(map.containsKey("k12")); - Assert.assertEquals(false, map.get("k12")); - - Assert.assertTrue(map.containsKey("k13")); - Assert.assertEquals(2.0, map.get("k13")); - - Assert.assertTrue(map.containsKey("k14")); - Assert.assertEquals("whatever", map.get("k14")); - - Assert.assertTrue(objects[1] instanceof Map); - map = (Map) objects[1]; - Assert.assertEquals(4, map.size()); - Assert.assertTrue(map.containsKey("k21")); - Assert.assertEquals(2L, map.get("k21")); - - Assert.assertTrue(map.containsKey("k22")); - Assert.assertEquals(true, map.get("k22")); - - Assert.assertTrue(map.containsKey("k23")); - Assert.assertEquals(23.0, map.get("k23")); - - Assert.assertTrue(map.containsKey("k24")); - Assert.assertEquals("foo", map.get("k24")); - } - // Package protected --------------------------------------------- // Protected ----------------------------------------------------- diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithPagingServerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithPagingServerTest.java index 236403ba458..793e82d449f 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithPagingServerTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/ManagementWithPagingServerTest.java @@ -17,6 +17,7 @@ package org.apache.activemq.artemis.tests.integration.management; import org.apache.activemq.artemis.api.core.ActiveMQBuffer; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ClientConsumer; import org.apache.activemq.artemis.api.core.client.ClientMessage; @@ -31,11 +32,11 @@ import org.apache.activemq.artemis.core.settings.impl.AddressFullMessagePolicy; import org.apache.activemq.artemis.core.settings.impl.AddressSettings; import org.apache.activemq.artemis.utils.RandomUtil; -import org.apache.activemq.artemis.utils.json.JSONArray; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import javax.json.JsonArray; import java.nio.ByteBuffer; /** @@ -77,9 +78,9 @@ public void testListMessagesAsJSON() throws Exception { String result = queueControl.listMessagesAsJSON(null); - JSONArray array = new JSONArray(result); + JsonArray array = JsonUtil.readJsonArray(result); - assertEquals(num, array.length()); + assertEquals(num, array.size()); //kick off receiver receiver.start(); @@ -88,9 +89,9 @@ public void testListMessagesAsJSON() throws Exception { result = queueControl.listMessagesAsJSON(null); - array = new JSONArray(result); + array = JsonUtil.readJsonArray(result); - assertEquals(0, array.length()); + assertEquals(0, array.size()); } @Test @@ -129,9 +130,9 @@ public void testListMessagesAsJSONWithFilter() throws Exception { String jsonString = queueControl.listMessagesAsJSON(filter); Assert.assertNotNull(jsonString); - JSONArray array = new JSONArray(jsonString); - Assert.assertEquals(num / 2, array.length()); - Assert.assertEquals(matchingValue, array.getJSONObject(0).get("key")); + JsonArray array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(num / 2, array.size()); + Assert.assertEquals(matchingValue, array.getJsonObject(0).getJsonNumber("key").longValue()); long n = queueControl.countMessages(filter); assertEquals(num / 2, n); diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlTest.java index e66e70d718b..0073c8d0fa1 100644 --- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlTest.java +++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/management/QueueControlTest.java @@ -16,6 +16,8 @@ */ package org.apache.activemq.artemis.tests.integration.management; +import javax.json.JsonArray; +import javax.json.JsonObject; import javax.management.Notification; import javax.management.openmbean.CompositeData; import java.util.HashMap; @@ -25,6 +27,7 @@ import java.util.concurrent.TimeUnit; import org.apache.activemq.artemis.api.core.ActiveMQException; +import org.apache.activemq.artemis.api.core.JsonUtil; import org.apache.activemq.artemis.api.core.Message; import org.apache.activemq.artemis.api.core.SimpleString; import org.apache.activemq.artemis.api.core.client.ClientConsumer; @@ -49,8 +52,6 @@ import org.apache.activemq.artemis.tests.integration.jms.server.management.JMSUtil; import org.apache.activemq.artemis.utils.Base64; import org.apache.activemq.artemis.utils.RandomUtil; -import org.apache.activemq.artemis.utils.json.JSONArray; -import org.apache.activemq.artemis.utils.json.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -219,16 +220,16 @@ public void testGetConsumerJSON() throws Exception { System.out.println("Consumers: " + queueControl.listConsumersAsJSON()); - JSONArray obj = new JSONArray(queueControl.listConsumersAsJSON()); + JsonArray obj = JsonUtil.readJsonArray(queueControl.listConsumersAsJSON()); - assertEquals(1, obj.length()); + assertEquals(1, obj.size()); consumer.close(); Assert.assertEquals(0, queueControl.getConsumerCount()); - obj = new JSONArray(queueControl.listConsumersAsJSON()); + obj = JsonUtil.readJsonArray(queueControl.listConsumersAsJSON()); - assertEquals(0, obj.length()); + assertEquals(0, obj.size()); session.deleteQueue(queue); } @@ -562,16 +563,16 @@ public void testListScheduledMessagesAsJSON() throws Exception { String jsonString = queueControl.listScheduledMessagesAsJSON(); Assert.assertNotNull(jsonString); - JSONArray array = new JSONArray(jsonString); - Assert.assertEquals(1, array.length()); - Assert.assertEquals(intValue, array.getJSONObject(0).get("key")); + JsonArray array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(1, array.size()); + Assert.assertEquals(intValue, array.getJsonObject(0).getJsonNumber("key").intValue()); Thread.sleep(delay + 500); jsonString = queueControl.listScheduledMessagesAsJSON(); Assert.assertNotNull(jsonString); - array = new JSONArray(jsonString); - Assert.assertEquals(0, array.length()); + array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(0, array.size()); consumeMessages(2, session, queue); @@ -620,16 +621,16 @@ public void testListMessagesAsJSONWithNullFilter() throws Exception { String jsonString = queueControl.listMessagesAsJSON(null); Assert.assertNotNull(jsonString); - JSONArray array = new JSONArray(jsonString); - Assert.assertEquals(1, array.length()); - Assert.assertEquals(intValue, array.getJSONObject(0).get("key")); + JsonArray array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(1, array.size()); + Assert.assertEquals(intValue, array.getJsonObject(0).getInt("key")); consumeMessages(1, session, queue); jsonString = queueControl.listMessagesAsJSON(null); Assert.assertNotNull(jsonString); - array = new JSONArray(jsonString); - Assert.assertEquals(0, array.length()); + array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(0, array.size()); session.deleteQueue(queue); } @@ -736,16 +737,16 @@ public void testListMessagesAsJSONWithFilter() throws Exception { String jsonString = queueControl.listMessagesAsJSON(filter); Assert.assertNotNull(jsonString); - JSONArray array = new JSONArray(jsonString); - Assert.assertEquals(1, array.length()); - Assert.assertEquals(matchingValue, array.getJSONObject(0).get("key")); + JsonArray array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(1, array.size()); + Assert.assertEquals(matchingValue, array.getJsonObject(0).getJsonNumber("key").longValue()); consumeMessages(2, session, queue); jsonString = queueControl.listMessagesAsJSON(filter); Assert.assertNotNull(jsonString); - array = new JSONArray(jsonString); - Assert.assertEquals(0, array.length()); + array = JsonUtil.readJsonArray(jsonString); + Assert.assertEquals(0, array.size()); session.deleteQueue(queue); } @@ -2099,8 +2100,8 @@ protected QueueControl createManagementControl(final SimpleString address, } protected long getFirstMessageId(final QueueControl queueControl) throws Exception { - JSONArray array = new JSONArray(queueControl.getFirstMessageAsJSON()); - JSONObject object = (JSONObject)array.get(0); - return object.getLong("messageID"); + JsonArray array = JsonUtil.readJsonArray(queueControl.getFirstMessageAsJSON()); + JsonObject object = (JsonObject) array.get(0); + return object.getJsonNumber("messageID").longValue(); } }