diff options
author | Taras Hupalo <taras.hupalo@gmail.com> | 2014-08-12 15:28:41 +0300 |
---|---|---|
committer | Leif Åstrand <leif@vaadin.com> | 2014-08-26 09:51:15 +0000 |
commit | f2551a9fc03636deb5fcd3f30c761dca946c8341 (patch) | |
tree | b59bc2c5ea1f7471dec4ef59826614b4f6d0adbf | |
parent | c8d58261954de18ef67eaf9043bd93360202cf06 (diff) | |
download | vaadin-framework-f2551a9fc03636deb5fcd3f30c761dca946c8341.tar.gz vaadin-framework-f2551a9fc03636deb5fcd3f30c761dca946c8341.zip |
replaced all org.json.* usages with elemental.json.* (#8942)
Change-Id: I4809fbbdb48f3e36c8e1da8552ff3fa734714105
45 files changed, 510 insertions, 511 deletions
diff --git a/client-compiler/src/com/vaadin/tools/CvalChecker.java b/client-compiler/src/com/vaadin/tools/CvalChecker.java index e426c5c4e6..c48aa7d9db 100644 --- a/client-compiler/src/com/vaadin/tools/CvalChecker.java +++ b/client-compiler/src/com/vaadin/tools/CvalChecker.java @@ -31,9 +31,10 @@ import java.util.Locale; import java.util.ResourceBundle; import java.util.prefs.Preferences; +import elemental.json.JsonException; +import elemental.json.JsonObject; +import elemental.json.impl.JsonUtil; import org.apache.commons.io.IOUtils; -import org.json.JSONException; -import org.json.JSONObject; /** * This class is able to validate the vaadin CVAL license. @@ -58,9 +59,9 @@ public final class CvalChecker { public static class CvalInfo { public static class Product { - private JSONObject o; + private JsonObject o; - public Product(JSONObject o) { + public Product(JsonObject o) { this.o = o; } @@ -74,40 +75,32 @@ public final class CvalChecker { } @SuppressWarnings("unchecked") - private static <T> T get(JSONObject o, String k, Class<T> clz) { + private static <T> T get(JsonObject o, String k, Class<T> clz) { Object ret = null; try { if (clz == String.class) { ret = o.getString(k); - } else if (clz == JSONObject.class) { - ret = o.getJSONObject(k); + } else if (clz == JsonObject.class) { + ret = o.getObject(k); } else if (clz == Integer.class) { - ret = o.getInt(k); + ret = Integer.valueOf((int) o.getNumber(k)); } else if (clz == Date.class) { - ret = new Date(o.getLong(k)); + ret = new Date((long) o.getNumber(k)); } else if (clz == Boolean.class) { ret = o.getBoolean(k); } - } catch (JSONException e) { + } catch (JsonException e) { } return (T) ret; } - private static <T> T put(JSONObject o, String k, Object v) { - try { - o.put(k, v); - } catch (JSONException e) { - } - return null; - } - - private JSONObject o; + private JsonObject o; private Product product; - public CvalInfo(JSONObject o) { + public CvalInfo(JsonObject o) { this.o = o; - product = new Product(get(o, "product", JSONObject.class)); + product = new Product(get(o, "product", JsonObject.class)); } public Boolean getExpired() { @@ -139,11 +132,11 @@ public final class CvalChecker { } public void setExpiredEpoch(Date expiredEpoch) { - put(o, "expiredEpoch", expiredEpoch.getTime()); + o.put("expiredEpoch", expiredEpoch.getTime()); } public void setMessage(String msg) { - put(o, "message", msg); + o.put("message", msg); } @Override @@ -327,9 +320,9 @@ public final class CvalChecker { return null; } try { - JSONObject o = new JSONObject(json); + JsonObject o = JsonUtil.parse(json); return new CvalInfo(o); - } catch (JSONException e) { + } catch (JsonException e) { return null; } } diff --git a/gwt-files.xml b/gwt-files.xml index 4a8486ab55..c0ef583177 100644 --- a/gwt-files.xml +++ b/gwt-files.xml @@ -182,6 +182,13 @@ <include name="com/google/gwt/user/client/rpc/IsSerializable.*" /> </fileset> + <!-- GWT Elemental --> + <fileset dir="${gwt.elemental.jar.files}"> + <include name="elemental/util/Array*" /> + <include name="elemental/util/Can*" /> + <include name="elemental/util/Map*" /> + <include name="elemental/json/**" /> + </fileset> </union> <union id="server.gwt.includes"> @@ -189,5 +196,10 @@ <!-- Server files from gwt-user --> <include name="com/google/gwt/*/server/**" /> </fileset> + <!-- GWT Elemental --> + <fileset dir="${gwt.elemental.jar.files}"> + <exclude name="META-INF/**" /> + <exclude name="super/**" /> + </fileset> </union> </project> diff --git a/gwt/ivy.xml b/gwt/ivy.xml index 52d8acea92..d34b7ccfcc 100644 --- a/gwt/ivy.xml +++ b/gwt/ivy.xml @@ -25,6 +25,6 @@ <dependency org="com.vaadin.external.gwt" name="gwt-dev" rev="${gwt.version}" conf="gwt-dev,ide->default" /> <dependency org="com.vaadin.external.gwt" name="gwt-user" rev="${gwt.version}" conf="gwt-user,ide->default" /> <dependency org="com.vaadin.external.gwt" name="gwt-codeserver" rev="${gwt.version}" conf="gwt-codeserver,ide->default" /> - <dependency org="com.vaadin.external.gwt" name="gwt-elemental" rev="${gwt.version}" conf="gwt-elemental->default" /> + <dependency org="com.vaadin.external.gwt" name="gwt-elemental" rev="${gwt.version}" conf="gwt-elemental,ide->default" /> </dependencies> </ivy-module> diff --git a/server/src/com/vaadin/server/AbstractClientConnector.java b/server/src/com/vaadin/server/AbstractClientConnector.java index 03300b20e2..19796af48d 100644 --- a/server/src/com/vaadin/server/AbstractClientConnector.java +++ b/server/src/com/vaadin/server/AbstractClientConnector.java @@ -32,9 +32,6 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.logging.Logger; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.event.EventRouter; import com.vaadin.event.MethodEventSource; import com.vaadin.shared.communication.ClientRpc; @@ -46,6 +43,7 @@ import com.vaadin.ui.Component.Event; import com.vaadin.ui.HasComponents; import com.vaadin.ui.LegacyComponent; import com.vaadin.ui.UI; +import elemental.json.JsonObject; /** * An abstract base class for ClientConnector implementations. This class @@ -243,7 +241,7 @@ public abstract class AbstractClientConnector implements ClientConnector, } @Override - public JSONObject encodeState() throws JSONException { + public JsonObject encodeState() { return LegacyCommunicationManager.encodeState(this, getState(false)); } diff --git a/server/src/com/vaadin/server/BootstrapHandler.java b/server/src/com/vaadin/server/BootstrapHandler.java index fb54b5c879..0605d6a2b8 100644 --- a/server/src/com/vaadin/server/BootstrapHandler.java +++ b/server/src/com/vaadin/server/BootstrapHandler.java @@ -30,8 +30,6 @@ import java.util.Set; import javax.servlet.http.HttpServletResponse; -import org.json.JSONException; -import org.json.JSONObject; import org.jsoup.nodes.DataNode; import org.jsoup.nodes.Document; import org.jsoup.nodes.DocumentType; @@ -44,6 +42,11 @@ import com.vaadin.shared.Version; import com.vaadin.shared.communication.PushMode; import com.vaadin.ui.UI; +import elemental.json.Json; +import elemental.json.JsonException; +import elemental.json.JsonObject; +import elemental.json.impl.JsonUtil; + /** * * @author Vaadin Ltd @@ -191,7 +194,7 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { String html = getBootstrapHtml(context); writeBootstrapPage(response, html); - } catch (JSONException e) { + } catch (JsonException e) { writeError(response, e); } @@ -340,10 +343,8 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { * @param context * * @throws IOException - * @throws JSONException */ - private void setupMainDiv(BootstrapContext context) throws IOException, - JSONException { + private void setupMainDiv(BootstrapContext context) throws IOException { String style = getMainDivStyle(context); /*- Add classnames; @@ -399,8 +400,8 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { StringBuilder builder = new StringBuilder(); builder.append("//<![CDATA[\n"); builder.append("if (!window.vaadin) alert(" - + JSONObject.quote("Failed to load the bootstrap javascript: " - + bootstrapLocation) + ");\n"); + + JsonUtil.quote("Failed to load the bootstrap javascript: " + + bootstrapLocation) + ");\n"); appendMainScriptTagContents(context, builder); @@ -412,8 +413,8 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { } protected void appendMainScriptTagContents(BootstrapContext context, - StringBuilder builder) throws JSONException, IOException { - JSONObject appConfig = getApplicationParameters(context); + StringBuilder builder) throws IOException { + JsonObject appConfig = getApplicationParameters(context); boolean isDebug = !context.getSession().getConfiguration() .isProductionMode(); @@ -438,21 +439,21 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { } private static void appendJsonObject(StringBuilder builder, - JSONObject jsonObject, boolean isDebug) throws JSONException { + JsonObject jsonObject, boolean isDebug) { if (isDebug) { - builder.append(jsonObject.toString(4)); + builder.append(JsonUtil.stringify(jsonObject, 4)); } else { - builder.append(jsonObject.toString()); + builder.append(JsonUtil.stringify(jsonObject)); } } - protected JSONObject getApplicationParameters(BootstrapContext context) - throws JSONException, PaintException { + protected JsonObject getApplicationParameters(BootstrapContext context) + throws PaintException { VaadinRequest request = context.getRequest(); VaadinSession session = context.getSession(); VaadinService vaadinService = request.getService(); - JSONObject appConfig = new JSONObject(); + JsonObject appConfig = Json.createObject(); String themeName = context.getThemeName(); if (themeName != null) { @@ -465,7 +466,7 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { appConfig.put("extraParams", "&" + IGNORE_RESTART_PARAM + "=1"); } - JSONObject versionInfo = new JSONObject(); + JsonObject versionInfo = Json.createObject(); versionInfo.put("vaadinVersion", Version.getFullVersion()); appConfig.put("versionInfo", versionInfo); @@ -479,30 +480,42 @@ public abstract class BootstrapHandler extends SynchronizedRequestHandler { request); if (systemMessages != null) { // Write the CommunicationError -message to client - JSONObject comErrMsg = new JSONObject(); + JsonObject comErrMsg = Json.createObject(); comErrMsg.put("caption", systemMessages.getCommunicationErrorCaption()); comErrMsg.put("message", systemMessages.getCommunicationErrorMessage()); - comErrMsg.put("url", systemMessages.getCommunicationErrorURL()); + if (systemMessages.getCommunicationErrorURL() == null) { + comErrMsg.put("url", Json.createNull()); + } else { + comErrMsg.put("url", systemMessages.getCommunicationErrorURL()); + } appConfig.put("comErrMsg", comErrMsg); - JSONObject authErrMsg = new JSONObject(); + JsonObject authErrMsg = Json.createObject(); authErrMsg.put("caption", systemMessages.getAuthenticationErrorCaption()); authErrMsg.put("message", systemMessages.getAuthenticationErrorMessage()); - authErrMsg.put("url", systemMessages.getAuthenticationErrorURL()); + if (systemMessages.getAuthenticationErrorURL() == null) { + authErrMsg.put("url", Json.createNull()); + } else { + authErrMsg.put("url", systemMessages.getAuthenticationErrorURL()); + } appConfig.put("authErrMsg", authErrMsg); - JSONObject sessExpMsg = new JSONObject(); + JsonObject sessExpMsg = Json.createObject(); sessExpMsg .put("caption", systemMessages.getSessionExpiredCaption()); sessExpMsg .put("message", systemMessages.getSessionExpiredMessage()); - sessExpMsg.put("url", systemMessages.getSessionExpiredURL()); + if (systemMessages.getSessionExpiredURL() == null) { + sessExpMsg.put("url", Json.createNull()); + } else { + sessExpMsg.put("url", systemMessages.getSessionExpiredURL()); + } appConfig.put("sessExpMsg", sessExpMsg); } diff --git a/server/src/com/vaadin/server/ClientConnector.java b/server/src/com/vaadin/server/ClientConnector.java index e61ba50a3a..50ce2754cb 100644 --- a/server/src/com/vaadin/server/ClientConnector.java +++ b/server/src/com/vaadin/server/ClientConnector.java @@ -20,15 +20,13 @@ import java.lang.reflect.Method; import java.util.Collection; import java.util.List; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.event.ConnectorEvent; import com.vaadin.event.ConnectorEventListener; import com.vaadin.shared.Connector; import com.vaadin.shared.communication.SharedState; import com.vaadin.ui.UI; import com.vaadin.util.ReflectTools; +import elemental.json.JsonObject; /** * Interface implemented by all connectors that are capable of communicating @@ -279,10 +277,9 @@ public interface ClientConnector extends Connector { * . * * @return a JSON object with the encoded connector state - * @throws JSONException * if the state can not be encoded */ - public JSONObject encodeState() throws JSONException; + public JsonObject encodeState() ; /** * Handle a request directed to this connector. This can be used by diff --git a/server/src/com/vaadin/server/ClientMethodInvocation.java b/server/src/com/vaadin/server/ClientMethodInvocation.java index e51138d7bf..97caa7614a 100644 --- a/server/src/com/vaadin/server/ClientMethodInvocation.java +++ b/server/src/com/vaadin/server/ClientMethodInvocation.java @@ -23,8 +23,9 @@ import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Type; -import org.json.JSONArray; -import org.json.JSONException; +import elemental.json.JsonArray; +import elemental.json.JsonException; +import elemental.json.impl.JsonUtil; /** * Internal class for keeping track of pending server to client method @@ -107,8 +108,8 @@ public class ClientMethodInvocation implements Serializable, Type type = parameterTypes[i]; if (type instanceof Class<?>) { Class<?> clazz = (Class<?>) type; - if (JSONArray.class.isAssignableFrom(clazz)) { - parameters[i] = ((JSONArray) parameters[i]).toString(); + if (JsonArray.class.isAssignableFrom(clazz)) { + parameters[i] = JsonUtil.stringify((JsonArray) parameters[i]); } } } @@ -124,10 +125,10 @@ public class ClientMethodInvocation implements Serializable, Type type = parameterTypes[i]; if (type instanceof Class<?>) { Class<?> clazz = (Class<?>) type; - if (JSONArray.class.isAssignableFrom(clazz)) { + if (JsonArray.class.isAssignableFrom(clazz)) { try { - parameters[i] = new JSONArray(((String) parameters[i])); - } catch (JSONException e) { + parameters[i] = JsonUtil.<JsonArray>parse((String) parameters[i]); + } catch (JsonException e) { throw new IOException(e); } } diff --git a/server/src/com/vaadin/server/DragAndDropService.java b/server/src/com/vaadin/server/DragAndDropService.java index 087a670b5b..c21f27de97 100644 --- a/server/src/com/vaadin/server/DragAndDropService.java +++ b/server/src/com/vaadin/server/DragAndDropService.java @@ -24,9 +24,6 @@ import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.event.Transferable; import com.vaadin.event.TransferableImpl; import com.vaadin.event.dd.DragAndDropEvent; @@ -41,6 +38,7 @@ import com.vaadin.shared.communication.SharedState; import com.vaadin.shared.ui.dd.DragEventType; import com.vaadin.ui.Component; import com.vaadin.ui.UI; +import elemental.json.JsonObject; public class DragAndDropService implements VariableOwner, ClientConnector { @@ -352,7 +350,7 @@ public class DragAndDropService implements VariableOwner, ClientConnector { } @Override - public JSONObject encodeState() throws JSONException { + public JsonObject encodeState() { // TODO Auto-generated method stub return null; } diff --git a/server/src/com/vaadin/server/EncodeResult.java b/server/src/com/vaadin/server/EncodeResult.java index 55a97aa829..bf4fd48438 100644 --- a/server/src/com/vaadin/server/EncodeResult.java +++ b/server/src/com/vaadin/server/EncodeResult.java @@ -18,29 +18,31 @@ package com.vaadin.server; import java.io.Serializable; +import elemental.json.JsonValue; + public class EncodeResult implements Serializable { - private final Object encodedValue; - private final Object diff; + private final JsonValue encodedValue; + private final JsonValue diff; - public EncodeResult(Object encodedValue) { + public EncodeResult(JsonValue encodedValue) { this(encodedValue, null); } - public EncodeResult(Object encodedValue, Object diff) { + public EncodeResult(JsonValue encodedValue, JsonValue diff) { this.encodedValue = encodedValue; this.diff = diff; } - public Object getEncodedValue() { + public JsonValue getEncodedValue() { return encodedValue; } - public Object getDiff() { + public JsonValue getDiff() { return diff; } - public Object getDiffOrValue() { - Object diff = getDiff(); + public JsonValue getDiffOrValue() { + JsonValue diff = getDiff(); if (diff != null) { return diff; } else { diff --git a/server/src/com/vaadin/server/JavaScriptCallbackHelper.java b/server/src/com/vaadin/server/JavaScriptCallbackHelper.java index 53fb1f838b..2552db6d13 100644 --- a/server/src/com/vaadin/server/JavaScriptCallbackHelper.java +++ b/server/src/com/vaadin/server/JavaScriptCallbackHelper.java @@ -18,21 +18,20 @@ package com.vaadin.server; import java.io.Serializable; import java.lang.reflect.Method; -import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.json.JSONArray; -import org.json.JSONException; - import com.vaadin.shared.JavaScriptConnectorState; import com.vaadin.ui.AbstractJavaScriptComponent; import com.vaadin.ui.JavaScript.JavaScriptCallbackRpc; import com.vaadin.ui.JavaScriptFunction; import com.vaadin.util.ReflectTools; +import elemental.json.JsonArray; +import elemental.json.JsonException; + /** * Internal helper class used to implement functionality common to * {@link AbstractJavaScriptComponent} and {@link AbstractJavaScriptExtension}. @@ -47,7 +46,7 @@ import com.vaadin.util.ReflectTools; public class JavaScriptCallbackHelper implements Serializable { private static final Method CALL_METHOD = ReflectTools.findMethod( - JavaScriptCallbackRpc.class, "call", String.class, JSONArray.class); + JavaScriptCallbackRpc.class, "call", String.class, JsonArray.class); private AbstractClientConnector connector; private Map<String, JavaScriptFunction> callbacks = new HashMap<String, JavaScriptFunction>(); @@ -75,11 +74,11 @@ public class JavaScriptCallbackHelper implements Serializable { if (javascriptCallbackRpc == null) { javascriptCallbackRpc = new JavaScriptCallbackRpc() { @Override - public void call(String name, JSONArray arguments) { + public void call(String name, JsonArray arguments) { JavaScriptFunction callback = callbacks.get(name); try { callback.call(arguments); - } catch (JSONException e) { + } catch (JsonException e) { throw new IllegalArgumentException(e); } } @@ -95,7 +94,7 @@ public class JavaScriptCallbackHelper implements Serializable { + name + " on the client because a callback with the same name is registered on the server."); } - JSONArray args = new JSONArray(Arrays.asList(arguments)); + JsonArray args = (JsonArray) JsonCodec.encode(arguments, null, Object[].class, null).getEncodedValue(); connector.addMethodInvocationToQueue( JavaScriptCallbackRpc.class.getName(), CALL_METHOD, new Object[] { name, args }); diff --git a/server/src/com/vaadin/server/JsonCodec.java b/server/src/com/vaadin/server/JsonCodec.java index 34b05f73bf..1e933ab1f3 100644 --- a/server/src/com/vaadin/server/JsonCodec.java +++ b/server/src/com/vaadin/server/JsonCodec.java @@ -28,12 +28,10 @@ import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -41,18 +39,24 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.communication.DateSerializer; -import com.vaadin.server.communication.JSONSerializer; +import com.vaadin.server.communication.JsonSerializer; import com.vaadin.shared.Connector; import com.vaadin.shared.JsonConstants; import com.vaadin.shared.communication.UidlValue; import com.vaadin.ui.Component; import com.vaadin.ui.ConnectorTracker; +import elemental.json.Json; +import elemental.json.JsonArray; +import elemental.json.JsonException; +import elemental.json.JsonNull; +import elemental.json.JsonObject; +import elemental.json.JsonString; +import elemental.json.JsonType; +import elemental.json.JsonValue; +import elemental.json.impl.JreJsonArray; + /** * Decoder for converting RPC parameters and other values from JSON in transfer * between the client and the server and vice versa. @@ -62,21 +66,32 @@ import com.vaadin.ui.ConnectorTracker; public class JsonCodec implements Serializable { /* Immutable Encode Result representing null */ - private static final EncodeResult ENCODE_RESULT_NULL = new EncodeResult( - JSONObject.NULL); + private static final EncodeResult ENCODE_RESULT_NULL = new EncodeResult(Json.createNull()); /* Immutable empty JSONArray */ - private static final JSONArray EMPTY_JSON_ARRAY = new JSONArray() { + private static final JsonArray EMPTY_JSON_ARRAY = new JreJsonArray(Json.instance()) { @Override - public JSONArray put(Object value) { + public void set(int index, JsonValue value) { throw new UnsupportedOperationException( - "Immutable empty JSONArray."); + "Immutable empty JsonArray."); } @Override - public JSONArray put(int index, Object value) { + public void set(int index, String string) { throw new UnsupportedOperationException( - "Immutable empty JSONArray."); + "Immutable empty JsonArray."); + } + + @Override + public void set(int index, double number) { + throw new UnsupportedOperationException( + "Immutable empty JsonArray."); + } + + @Override + public void set(int index, boolean bool) { + throw new UnsupportedOperationException( + "Immutable empty JsonArray."); } }; @@ -197,7 +212,7 @@ public class JsonCodec implements Serializable { */ private static Map<String, Class<?>> transportTypeToType = new HashMap<String, Class<?>>(); - private static Map<Class<?>, JSONSerializer<?>> customSerializers = new HashMap<Class<?>, JSONSerializer<?>>(); + private static Map<Class<?>, JsonSerializer<?>> customSerializers = new HashMap<Class<?>, JsonSerializer<?>>(); static { customSerializers.put(Date.class, new DateSerializer()); } @@ -266,8 +281,7 @@ public class JsonCodec implements Serializable { } public static Object decodeInternalOrCustomType(Type targetType, - Object value, ConnectorTracker connectorTracker) - throws JSONException { + JsonValue value, ConnectorTracker connectorTracker) { if (isInternalType(targetType)) { return decodeInternalType(targetType, false, value, connectorTracker); @@ -276,50 +290,49 @@ public class JsonCodec implements Serializable { } } - public static Object decodeCustomType(Type targetType, Object value, - ConnectorTracker connectorTracker) throws JSONException { + public static Object decodeCustomType(Type targetType, JsonValue value, + ConnectorTracker connectorTracker) { if (isInternalType(targetType)) { - throw new JSONException("decodeCustomType cannot be used for " + throw new JsonException("decodeCustomType cannot be used for " + targetType + ", which is an internal type"); } // Try to decode object using fields - if (value == JSONObject.NULL) { + if (value.getType() == JsonType.NULL) { return null; } else if (targetType == byte.class || targetType == Byte.class) { - return Byte.valueOf(String.valueOf(value)); + return Byte.valueOf((byte) value.asNumber()); } else if (targetType == char.class || targetType == Character.class) { - return Character.valueOf(String.valueOf(value).charAt(0)); + return Character.valueOf(value.asString().charAt(0)); } else if (targetType instanceof Class<?> && ((Class<?>) targetType).isArray()) { // Legacy Object[] and String[] handled elsewhere, this takes care // of generic arrays Class<?> componentType = ((Class<?>) targetType).getComponentType(); - return decodeArray(componentType, (JSONArray) value, + return decodeArray(componentType, (JsonArray) value, connectorTracker); } else if (targetType instanceof GenericArrayType) { Type componentType = ((GenericArrayType) targetType) .getGenericComponentType(); - return decodeArray(componentType, (JSONArray) value, + return decodeArray(componentType, (JsonArray) value, connectorTracker); - } else if (targetType == JSONObject.class - || targetType == JSONArray.class) { + } else if (JsonValue.class.isAssignableFrom(getClassForType(targetType))) { return value; } else if (Enum.class.isAssignableFrom(getClassForType(targetType))) { Class<?> classForType = getClassForType(targetType); return decodeEnum(classForType.asSubclass(Enum.class), - (String) value); + (JsonString) value); } else if (customSerializers.containsKey(getClassForType(targetType))) { return customSerializers.get(getClassForType(targetType)) .deserialize(targetType, value, connectorTracker); } else { - return decodeObject(targetType, (JSONObject) value, + return decodeObject(targetType, (JsonObject) value, connectorTracker); } } - private static Object decodeArray(Type componentType, JSONArray value, - ConnectorTracker connectorTracker) throws JSONException { + private static Object decodeArray(Type componentType, JsonArray value, + ConnectorTracker connectorTracker) { Class<?> componentClass = getClassForType(componentType); Object array = Array.newInstance(componentClass, value.length()); for (int i = 0; i < value.length(); i++) { @@ -352,37 +365,36 @@ public class JsonCodec implements Serializable { * true if generics should be enforce, false to only allow * internal types in collections * @return - * @throws JSONException */ public static Object decodeInternalType(Type targetType, - boolean restrictToInternalTypes, Object encodedJsonValue, - ConnectorTracker connectorTracker) throws JSONException { + boolean restrictToInternalTypes, JsonValue encodedJsonValue, + ConnectorTracker connectorTracker) { if (!isInternalType(targetType)) { - throw new JSONException("Type " + targetType + throw new JsonException("Type " + targetType + " is not a supported internal type."); } String transportType = getInternalTransportType(targetType); - if (encodedJsonValue == JSONObject.NULL) { + if (encodedJsonValue.getType() == JsonType.NULL) { return null; } else if (targetType == Void.class) { - throw new JSONException( + throw new JsonException( "Something other than null was encoded for a null type"); } // UidlValue if (targetType == UidlValue.class) { - return decodeUidlValue((JSONArray) encodedJsonValue, + return decodeUidlValue((JsonArray) encodedJsonValue, connectorTracker); } // Collections if (JsonConstants.VTYPE_LIST.equals(transportType)) { return decodeList(targetType, restrictToInternalTypes, - (JSONArray) encodedJsonValue, connectorTracker); + (JsonArray) encodedJsonValue, connectorTracker); } else if (JsonConstants.VTYPE_SET.equals(transportType)) { return decodeSet(targetType, restrictToInternalTypes, - (JSONArray) encodedJsonValue, connectorTracker); + (JsonArray) encodedJsonValue, connectorTracker); } else if (JsonConstants.VTYPE_MAP.equals(transportType)) { return decodeMap(targetType, restrictToInternalTypes, encodedJsonValue, connectorTracker); @@ -391,42 +403,40 @@ public class JsonCodec implements Serializable { // Arrays if (JsonConstants.VTYPE_ARRAY.equals(transportType)) { - return decodeObjectArray(targetType, (JSONArray) encodedJsonValue, + return decodeObjectArray(targetType, (JsonArray) encodedJsonValue, connectorTracker); } else if (JsonConstants.VTYPE_STRINGARRAY.equals(transportType)) { - return decodeStringArray((JSONArray) encodedJsonValue); + return decodeStringArray((JsonArray) encodedJsonValue); } // Special Vaadin types - String stringValue = String.valueOf(encodedJsonValue); - if (JsonConstants.VTYPE_CONNECTOR.equals(transportType)) { - return connectorTracker.getConnector(stringValue); + return connectorTracker.getConnector(encodedJsonValue.asString()); } // Legacy types if (JsonConstants.VTYPE_STRING.equals(transportType)) { - return stringValue; + return encodedJsonValue.asString(); } else if (JsonConstants.VTYPE_INTEGER.equals(transportType)) { - return Integer.valueOf(stringValue); + return (int) encodedJsonValue.asNumber(); } else if (JsonConstants.VTYPE_LONG.equals(transportType)) { - return Long.valueOf(stringValue); + return (long) encodedJsonValue.asNumber(); } else if (JsonConstants.VTYPE_FLOAT.equals(transportType)) { - return Float.valueOf(stringValue); + return (float) encodedJsonValue.asNumber(); } else if (JsonConstants.VTYPE_DOUBLE.equals(transportType)) { - return Double.valueOf(stringValue); + return encodedJsonValue.asNumber(); } else if (JsonConstants.VTYPE_BOOLEAN.equals(transportType)) { - return Boolean.valueOf(stringValue); + return encodedJsonValue.asBoolean(); } - throw new JSONException("Unknown type " + transportType); + throw new JsonException("Unknown type " + transportType); } - private static UidlValue decodeUidlValue(JSONArray encodedJsonValue, - ConnectorTracker connectorTracker) throws JSONException { + private static UidlValue decodeUidlValue(JsonArray encodedJsonValue, + ConnectorTracker connectorTracker) { String type = encodedJsonValue.getString(0); Object decodedValue = decodeInternalType(getType(type), true, @@ -435,13 +445,13 @@ public class JsonCodec implements Serializable { } private static Map<Object, Object> decodeMap(Type targetType, - boolean restrictToInternalTypes, Object jsonMap, - ConnectorTracker connectorTracker) throws JSONException { - if (jsonMap instanceof JSONArray) { + boolean restrictToInternalTypes, JsonValue jsonMap, + ConnectorTracker connectorTracker) { + if (jsonMap.getType() == JsonType.ARRAY) { // Client-side has no declared type information to determine // encoding method for empty maps, so these are handled separately. // See #8906. - JSONArray jsonArray = (JSONArray) jsonMap; + JsonArray jsonArray = (JsonArray) jsonMap; if (jsonArray.length() == 0) { return new HashMap<Object, Object>(); } @@ -453,27 +463,27 @@ public class JsonCodec implements Serializable { Type valueType = ((ParameterizedType) targetType) .getActualTypeArguments()[1]; if (keyType == String.class) { - return decodeStringMap(valueType, (JSONObject) jsonMap, + return decodeStringMap(valueType, (JsonObject) jsonMap, connectorTracker); } else if (keyType == Connector.class) { - return decodeConnectorMap(valueType, (JSONObject) jsonMap, + return decodeConnectorMap(valueType, (JsonObject) jsonMap, connectorTracker); } else { - return decodeObjectMap(keyType, valueType, (JSONArray) jsonMap, + return decodeObjectMap(keyType, valueType, (JsonArray) jsonMap, connectorTracker); } } else { - return decodeStringMap(UidlValue.class, (JSONObject) jsonMap, + return decodeStringMap(UidlValue.class, (JsonObject) jsonMap, connectorTracker); } } private static Map<Object, Object> decodeObjectMap(Type keyType, - Type valueType, JSONArray jsonMap, ConnectorTracker connectorTracker) - throws JSONException { + Type valueType, JsonArray jsonMap, ConnectorTracker connectorTracker) + { - JSONArray keys = jsonMap.getJSONArray(0); - JSONArray values = jsonMap.getJSONArray(1); + JsonArray keys = jsonMap.getArray(0); + JsonArray values = jsonMap.getArray(1); assert (keys.length() == values.length()); @@ -491,12 +501,10 @@ public class JsonCodec implements Serializable { } private static Map<Object, Object> decodeConnectorMap(Type valueType, - JSONObject jsonMap, ConnectorTracker connectorTracker) - throws JSONException { + JsonObject jsonMap, ConnectorTracker connectorTracker) { Map<Object, Object> map = new HashMap<Object, Object>(); - for (Iterator<?> iter = jsonMap.keys(); iter.hasNext();) { - String key = (String) iter.next(); + for (String key : jsonMap.keys()) { Object value = decodeInternalOrCustomType(valueType, jsonMap.get(key), connectorTracker); if (valueType == UidlValue.class) { @@ -509,12 +517,10 @@ public class JsonCodec implements Serializable { } private static Map<Object, Object> decodeStringMap(Type valueType, - JSONObject jsonMap, ConnectorTracker connectorTracker) - throws JSONException { + JsonObject jsonMap, ConnectorTracker connectorTracker) { Map<Object, Object> map = new HashMap<Object, Object>(); - for (Iterator<?> iter = jsonMap.keys(); iter.hasNext();) { - String key = (String) iter.next(); + for (String key : jsonMap.keys()) { Object value = decodeInternalOrCustomType(valueType, jsonMap.get(key), connectorTracker); if (valueType == UidlValue.class) { @@ -535,11 +541,10 @@ public class JsonCodec implements Serializable { * @param encodedValueAndType * @param application * @return - * @throws JSONException */ private static Object decodeParametrizedType(Type targetType, - boolean restrictToInternalTypes, int typeIndex, Object value, - ConnectorTracker connectorTracker) throws JSONException { + boolean restrictToInternalTypes, int typeIndex, JsonValue value, + ConnectorTracker connectorTracker) { if (!restrictToInternalTypes && targetType instanceof ParameterizedType) { Type childType = ((ParameterizedType) targetType) .getActualTypeArguments()[typeIndex]; @@ -555,12 +560,11 @@ public class JsonCodec implements Serializable { } } - private static Object decodeEnum(Class<? extends Enum> cls, String value) { - return Enum.valueOf(cls, value); + private static Object decodeEnum(Class<? extends Enum> cls, JsonString value) { + return Enum.valueOf(cls, value.getString()); } - private static String[] decodeStringArray(JSONArray jsonArray) - throws JSONException { + private static String[] decodeStringArray(JsonArray jsonArray) { int length = jsonArray.length(); List<String> tokens = new ArrayList<String>(length); for (int i = 0; i < length; ++i) { @@ -570,21 +574,20 @@ public class JsonCodec implements Serializable { } private static Object[] decodeObjectArray(Type targetType, - JSONArray jsonArray, ConnectorTracker connectorTracker) - throws JSONException { + JsonArray jsonArray, ConnectorTracker connectorTracker) { List<Object> list = decodeList(List.class, true, jsonArray, connectorTracker); return list.toArray(new Object[list.size()]); } private static List<Object> decodeList(Type targetType, - boolean restrictToInternalTypes, JSONArray jsonArray, - ConnectorTracker connectorTracker) throws JSONException { + boolean restrictToInternalTypes, JsonArray jsonArray, + ConnectorTracker connectorTracker) { int arrayLength = jsonArray.length(); List<Object> list = new ArrayList<Object>(arrayLength); for (int i = 0; i < arrayLength; ++i) { // each entry always has two elements: type and value - Object encodedValue = jsonArray.get(i); + JsonValue encodedValue = jsonArray.get(i); Object decodedChild = decodeParametrizedType(targetType, restrictToInternalTypes, 0, encodedValue, connectorTracker); list.add(decodedChild); @@ -593,8 +596,8 @@ public class JsonCodec implements Serializable { } private static Set<Object> decodeSet(Type targetType, - boolean restrictToInternalTypes, JSONArray jsonArray, - ConnectorTracker connectorTracker) throws JSONException { + boolean restrictToInternalTypes, JsonArray jsonArray, + ConnectorTracker connectorTracker) { HashSet<Object> set = new HashSet<Object>(); set.addAll(decodeList(targetType, restrictToInternalTypes, jsonArray, connectorTracker)); @@ -602,8 +605,7 @@ public class JsonCodec implements Serializable { } private static Object decodeObject(Type targetType, - JSONObject serializedObject, ConnectorTracker connectorTracker) - throws JSONException { + JsonObject serializedObject, ConnectorTracker connectorTracker) { Class<?> targetClass = getClassForType(targetType); @@ -612,7 +614,7 @@ public class JsonCodec implements Serializable { for (BeanProperty property : getProperties(targetClass)) { String fieldName = property.getName(); - Object encodedFieldValue = serializedObject.get(fieldName); + JsonValue encodedFieldValue = serializedObject.get(fieldName); Type fieldType = property.getType(); Object decodedFieldValue = decodeInternalOrCustomType( fieldType, encodedFieldValue, connectorTracker); @@ -622,13 +624,12 @@ public class JsonCodec implements Serializable { return decodedObject; } catch (Exception e) { - throw new JSONException(e.getMessage()); + throw new RuntimeException(e); } } - public static EncodeResult encode(Object value, Object diffState, - Type valueType, ConnectorTracker connectorTracker) - throws JSONException { + public static EncodeResult encode(Object value, JsonValue diffState, + Type valueType, ConnectorTracker connectorTracker) { if (null == value) { return ENCODE_RESULT_NULL; @@ -636,13 +637,19 @@ public class JsonCodec implements Serializable { // Storing a single reference and only returning the EncodeResult at the // end the method is much shorter in bytecode which allows inlining - Object toReturn; + JsonValue toReturn; - if (value instanceof String || value instanceof Boolean - || value instanceof Number || value instanceof Character - || value instanceof JSONArray || value instanceof JSONObject) { + if (value instanceof JsonValue) { // all JSON compatible types are returned as is. - toReturn = value; + toReturn = (JsonValue) value; + } else if (value instanceof String) { + toReturn = Json.create((String) value); + } else if (value instanceof Boolean) { + toReturn = Json.create((Boolean) value); + } else if (value instanceof Number) { + toReturn = Json.create(((Number) value).doubleValue()); + } else if (value instanceof Character) { + toReturn = Json.create(Character.toString((Character) value)); } else if (value instanceof String[]) { toReturn = toJsonArray((String[]) value); } else if (value instanceof Collection) { @@ -658,9 +665,9 @@ public class JsonCodec implements Serializable { return ENCODE_RESULT_NULL; } // Connectors are simply serialized as ID. - toReturn = ((Connector) value).getConnectorId(); + toReturn = Json.create(((Connector) value).getConnectorId()); } else if (value instanceof Enum) { - toReturn = ((Enum<?>) value).name(); + toReturn = Json.create(((Enum<?>) value).name()); } else if (customSerializers.containsKey(value.getClass())) { toReturn = serializeJson(value, connectorTracker); } else if (valueType instanceof GenericArrayType) { @@ -677,10 +684,10 @@ public class JsonCodec implements Serializable { // needs to return it directly rather than assigning it to // toReturn. return encodeObject(value, (Class<?>) valueType, - (JSONObject) diffState, connectorTracker); + (JsonObject) diffState, connectorTracker); } } else { - throw new JSONException("Can not encode type " + valueType); + throw new JsonException("Can not encode type " + valueType); } return new EncodeResult(toReturn); } @@ -706,10 +713,9 @@ public class JsonCodec implements Serializable { * Loops through the fields of value and encodes them. */ private static EncodeResult encodeObject(Object value, Class<?> valueType, - JSONObject referenceValue, ConnectorTracker connectorTracker) - throws JSONException { - JSONObject encoded = new JSONObject(); - JSONObject diff = new JSONObject(); + JsonObject referenceValue, ConnectorTracker connectorTracker) { + JsonObject encoded = Json.createObject(); + JsonObject diff = Json.createObject(); try { for (BeanProperty property : getProperties(valueType)) { @@ -719,7 +725,7 @@ public class JsonCodec implements Serializable { Type fieldType = property.getType(); Object fieldValue = property.getValue(value); - if (encoded.has(fieldName)) { + if (encoded.hasKey(fieldName)) { throw new RuntimeException( "Can't encode " + valueType.getName() @@ -728,10 +734,10 @@ public class JsonCodec implements Serializable { + ". This can happen if there are getters and setters for a public field (the framework can't know which to ignore) or if there are properties with only casing distinguishing between the names (e.g. getFoo() and getFOO())"); } - Object fieldReference; + JsonValue fieldReference; if (referenceValue != null) { fieldReference = referenceValue.get(fieldName); - if (JSONObject.NULL.equals(fieldReference)) { + if (fieldReference instanceof JsonNull) { fieldReference = null; } } else { @@ -748,7 +754,7 @@ public class JsonCodec implements Serializable { } } catch (Exception e) { // TODO: Should exceptions be handled in a different way? - throw new JSONException(e.getMessage()); + throw new RuntimeException(e); } return new EncodeResult(encoded, diff); } @@ -760,8 +766,8 @@ public class JsonCodec implements Serializable { * @param referenceValue * @return */ - private static boolean jsonEquals(Object fieldValue, Object referenceValue) { - if (fieldValue == JSONObject.NULL) { + private static boolean jsonEquals(JsonValue fieldValue, JsonValue referenceValue) { + if (fieldValue instanceof JsonNull) { fieldValue = null; } @@ -769,41 +775,33 @@ public class JsonCodec implements Serializable { return true; } else if (fieldValue == null || referenceValue == null) { return false; - } else if (fieldValue instanceof Integer - && referenceValue instanceof Integer) { - return ((Integer) fieldValue).equals(referenceValue); - } else if (fieldValue instanceof Boolean - && referenceValue instanceof Boolean) { - return ((Boolean) fieldValue).equals(referenceValue); } else { - return fieldValue.toString().equals(referenceValue.toString()); + return fieldValue.jsEquals(referenceValue); } } - private static JSONArray encodeArrayContents(Type componentType, - Object array, ConnectorTracker connectorTracker) - throws JSONException { - JSONArray jsonArray = new JSONArray(); + private static JsonArray encodeArrayContents(Type componentType, + Object array, ConnectorTracker connectorTracker) { + JsonArray jsonArray = Json.createArray(); for (int i = 0; i < Array.getLength(array); i++) { EncodeResult encodeResult = encode(Array.get(array, i), null, componentType, connectorTracker); - jsonArray.put(encodeResult.getEncodedValue()); + jsonArray.set(i, encodeResult.getEncodedValue()); } return jsonArray; } - private static JSONArray encodeCollection(Type targetType, - Collection<?> collection, ConnectorTracker connectorTracker) - throws JSONException { - JSONArray jsonArray = new JSONArray(); + private static JsonArray encodeCollection(Type targetType, + Collection<?> collection, ConnectorTracker connectorTracker) { + JsonArray jsonArray = Json.createArray(); for (Object o : collection) { - jsonArray.put(encodeChild(targetType, 0, o, connectorTracker)); + jsonArray.set(jsonArray.length(), encodeChild(targetType, 0, o, connectorTracker)); } return jsonArray; } - private static Object encodeChild(Type targetType, int typeIndex, Object o, - ConnectorTracker connectorTracker) throws JSONException { + private static JsonValue encodeChild(Type targetType, int typeIndex, Object o, + ConnectorTracker connectorTracker) { if (targetType instanceof ParameterizedType) { Type childType = ((ParameterizedType) targetType) .getActualTypeArguments()[typeIndex]; @@ -812,19 +810,19 @@ public class JsonCodec implements Serializable { connectorTracker); return encodeResult.getEncodedValue(); } else { - throw new JSONException("Collection is missing generics"); + throw new JsonException("Collection is missing generics"); } } - private static Object encodeMap(Type mapType, Map<?, ?> map, - ConnectorTracker connectorTracker) throws JSONException { + private static JsonValue encodeMap(Type mapType, Map<?, ?> map, + ConnectorTracker connectorTracker) { Type keyType, valueType; if (mapType instanceof ParameterizedType) { keyType = ((ParameterizedType) mapType).getActualTypeArguments()[0]; valueType = ((ParameterizedType) mapType).getActualTypeArguments()[1]; } else { - throw new JSONException("Map is missing generics"); + throw new JsonException("Map is missing generics"); } if (map.isEmpty()) { @@ -842,11 +840,10 @@ public class JsonCodec implements Serializable { } } - private static JSONArray encodeObjectMap(Type keyType, Type valueType, - Map<?, ?> map, ConnectorTracker connectorTracker) - throws JSONException { - JSONArray keys = new JSONArray(); - JSONArray values = new JSONArray(); + private static JsonArray encodeObjectMap(Type keyType, Type valueType, + Map<?, ?> map, ConnectorTracker connectorTracker) { + JsonArray keys = Json.createArray(); + JsonArray values = Json.createArray(); for (Entry<?, ?> entry : map.entrySet()) { EncodeResult encodedKey = encode(entry.getKey(), null, keyType, @@ -854,19 +851,23 @@ public class JsonCodec implements Serializable { EncodeResult encodedValue = encode(entry.getValue(), null, valueType, connectorTracker); - keys.put(encodedKey.getEncodedValue()); - values.put(encodedValue.getEncodedValue()); + keys.set(keys.length(), encodedKey.getEncodedValue()); + values.set(values.length(), encodedValue.getEncodedValue()); } - return new JSONArray(Arrays.asList(keys, values)); + JsonArray jsonMap = Json.createArray(); + jsonMap.set(0, keys); + jsonMap.set(1, values); + + return jsonMap; } /* * Encodes a connector map. Invisible connectors are skipped. */ - private static JSONObject encodeConnectorMap(Type valueType, Map<?, ?> map, - ConnectorTracker connectorTracker) throws JSONException { - JSONObject jsonMap = new JSONObject(); + private static JsonObject encodeConnectorMap(Type valueType, Map<?, ?> map, + ConnectorTracker connectorTracker) { + JsonObject jsonMap = Json.createObject(); for (Entry<?, ?> entry : map.entrySet()) { ClientConnector key = (ClientConnector) entry.getKey(); @@ -881,9 +882,9 @@ public class JsonCodec implements Serializable { return jsonMap; } - private static JSONObject encodeStringMap(Type valueType, Map<?, ?> map, - ConnectorTracker connectorTracker) throws JSONException { - JSONObject jsonMap = new JSONObject(); + private static JsonObject encodeStringMap(Type valueType, Map<?, ?> map, + ConnectorTracker connectorTracker) { + JsonObject jsonMap = Json.createObject(); for (Entry<?, ?> entry : map.entrySet()) { String key = (String) entry.getKey(); @@ -904,16 +905,16 @@ public class JsonCodec implements Serializable { return typeToTransportType.get(getClassForType(valueType)); } - private static Object serializeJson(Object value, + private static JsonValue serializeJson(Object value, ConnectorTracker connectorTracker) { - JSONSerializer serializer = customSerializers.get(value.getClass()); + JsonSerializer serializer = customSerializers.get(value.getClass()); return serializer.serialize(value, connectorTracker); } - private static JSONArray toJsonArray(String[] array) { - JSONArray jsonArray = new JSONArray(); + private static JsonArray toJsonArray(String[] array) { + JsonArray jsonArray = Json.createArray(); for (int i = 0; i < array.length; ++i) { - jsonArray.put(array[i]); + jsonArray.set(i, array[i]); } return jsonArray; } diff --git a/server/src/com/vaadin/server/LegacyCommunicationManager.java b/server/src/com/vaadin/server/LegacyCommunicationManager.java index 0dda5661bd..e1beb1153c 100644 --- a/server/src/com/vaadin/server/LegacyCommunicationManager.java +++ b/server/src/com/vaadin/server/LegacyCommunicationManager.java @@ -27,9 +27,6 @@ import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.ClientConnector.ConnectorErrorEvent; import com.vaadin.shared.ApplicationConstants; import com.vaadin.shared.JavaScriptConnectorState; @@ -40,6 +37,9 @@ import com.vaadin.ui.HasComponents; import com.vaadin.ui.SelectiveRenderer; import com.vaadin.ui.UI; +import elemental.json.JsonObject; +import elemental.json.JsonValue; + /** * This is a common base class for the server-side implementations of the * communication system between the client code (compiled with GWT into @@ -85,12 +85,11 @@ public class LegacyCommunicationManager implements Serializable { * @deprecated As of 7.1. See #11411. */ @Deprecated - public static JSONObject encodeState(ClientConnector connector, - SharedState state) throws JSONException { + public static JsonObject encodeState(ClientConnector connector, SharedState state) { UI uI = connector.getUI(); ConnectorTracker connectorTracker = uI.getConnectorTracker(); Class<? extends SharedState> stateType = connector.getStateType(); - Object diffState = connectorTracker.getDiffState(connector); + JsonValue diffState = connectorTracker.getDiffState(connector); boolean supportsDiffState = !JavaScriptConnectorState.class .isAssignableFrom(stateType); if (diffState == null && supportsDiffState) { @@ -113,9 +112,9 @@ public class LegacyCommunicationManager implements Serializable { stateType, uI.getConnectorTracker()); if (supportsDiffState) { connectorTracker.setDiffState(connector, - (JSONObject) encodeResult.getEncodedValue()); + (JsonObject) encodeResult.getEncodedValue()); } - return (JSONObject) encodeResult.getDiff(); + return (JsonObject) encodeResult.getDiff(); } /** diff --git a/server/src/com/vaadin/server/VaadinService.java b/server/src/com/vaadin/server/VaadinService.java index 8d44ff74ed..cf50ba7210 100644 --- a/server/src/com/vaadin/server/VaadinService.java +++ b/server/src/com/vaadin/server/VaadinService.java @@ -48,9 +48,6 @@ import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletResponse; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.annotations.PreserveOnRefresh; import com.vaadin.event.EventRouter; import com.vaadin.server.VaadinSession.FutureAccess; @@ -67,6 +64,11 @@ import com.vaadin.ui.UI; import com.vaadin.util.CurrentInstance; import com.vaadin.util.ReflectTools; +import elemental.json.Json; +import elemental.json.JsonException; +import elemental.json.JsonObject; +import elemental.json.impl.JsonUtil; + /** * Provide deployment specific settings that are required outside terminal * specific code. @@ -1574,22 +1576,22 @@ public abstract class VaadinService implements Serializable { message += "<br/><br/>" + details; } - JSONObject appError = new JSONObject(); + JsonObject appError = Json.createObject(); appError.put("caption", caption); appError.put("message", message); appError.put("url", url); - JSONObject meta = new JSONObject(); + JsonObject meta = Json.createObject(); meta.put("appError", appError); - JSONObject json = new JSONObject(); - json.put("changes", new JSONObject()); - json.put("resources", new JSONObject()); - json.put("locales", new JSONObject()); + JsonObject json = Json.createObject(); + json.put("changes", Json.createObject()); + json.put("resources", Json.createObject()); + json.put("locales", Json.createObject()); json.put("meta", meta); json.put(ApplicationConstants.SERVER_SYNC_ID, -1); - returnString = json.toString(); - } catch (JSONException e) { + returnString = JsonUtil.stringify(json); + } catch (JsonException e) { getLogger().log(Level.WARNING, "Error creating critical notification JSON message", e); } diff --git a/server/src/com/vaadin/server/communication/ClientRpcWriter.java b/server/src/com/vaadin/server/communication/ClientRpcWriter.java index 1090fdbab9..6631f6176d 100644 --- a/server/src/com/vaadin/server/communication/ClientRpcWriter.java +++ b/server/src/com/vaadin/server/communication/ClientRpcWriter.java @@ -24,9 +24,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.json.JSONArray; -import org.json.JSONException; - import com.vaadin.server.ClientConnector; import com.vaadin.server.ClientMethodInvocation; import com.vaadin.server.EncodeResult; @@ -35,6 +32,12 @@ import com.vaadin.server.PaintException; import com.vaadin.shared.communication.ClientRpc; import com.vaadin.ui.UI; +import elemental.json.Json; +import elemental.json.JsonArray; +import elemental.json.JsonException; +import elemental.json.JsonValue; +import elemental.json.impl.JsonUtil; + /** * Serializes {@link ClientRpc client RPC} invocations to JSON. * @@ -59,18 +62,18 @@ public class ClientRpcWriter implements Serializable { Collection<ClientMethodInvocation> pendingInvocations = collectPendingRpcCalls(ui .getConnectorTracker().getDirtyVisibleConnectors()); - JSONArray rpcCalls = new JSONArray(); + JsonArray rpcCalls = Json.createArray(); for (ClientMethodInvocation invocation : pendingInvocations) { // add invocation to rpcCalls try { - JSONArray invocationJson = new JSONArray(); - invocationJson.put(invocation.getConnector().getConnectorId()); - invocationJson.put(invocation.getInterfaceName()); - invocationJson.put(invocation.getMethodName()); - JSONArray paramJson = new JSONArray(); + JsonArray invocationJson = Json.createArray(); + invocationJson.set(0, invocation.getConnector().getConnectorId()); + invocationJson.set(1, invocation.getInterfaceName()); + invocationJson.set(2, invocation.getMethodName()); + JsonArray paramJson = Json.createArray(); for (int i = 0; i < invocation.getParameterTypes().length; ++i) { Type parameterType = invocation.getParameterTypes()[i]; - Object referenceParameter = null; + JsonValue referenceParameter = null; // TODO Use default values for RPC parameter types // if (!JsonCodec.isInternalType(parameterType)) { // try { @@ -84,11 +87,11 @@ public class ClientRpcWriter implements Serializable { EncodeResult encodeResult = JsonCodec.encode( invocation.getParameters()[i], referenceParameter, parameterType, ui.getConnectorTracker()); - paramJson.put(encodeResult.getEncodedValue()); + paramJson.set(i, encodeResult.getEncodedValue()); } - invocationJson.put(paramJson); - rpcCalls.put(invocationJson); - } catch (JSONException e) { + invocationJson.set(3, paramJson); + rpcCalls.set(rpcCalls.length(), invocationJson); + } catch (JsonException e) { throw new PaintException( "Failed to serialize RPC method call parameters for connector " + invocation.getConnector().getConnectorId() @@ -97,7 +100,7 @@ public class ClientRpcWriter implements Serializable { + e.getMessage(), e); } } - writer.write(rpcCalls.toString()); + writer.write(JsonUtil.stringify(rpcCalls)); } /** diff --git a/server/src/com/vaadin/server/communication/ConnectorHierarchyWriter.java b/server/src/com/vaadin/server/communication/ConnectorHierarchyWriter.java index 653048b930..1c1a220b5d 100644 --- a/server/src/com/vaadin/server/communication/ConnectorHierarchyWriter.java +++ b/server/src/com/vaadin/server/communication/ConnectorHierarchyWriter.java @@ -21,16 +21,18 @@ import java.io.Serializable; import java.io.Writer; import java.util.Collection; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.AbstractClientConnector; import com.vaadin.server.ClientConnector; import com.vaadin.server.LegacyCommunicationManager; import com.vaadin.server.PaintException; import com.vaadin.ui.UI; +import elemental.json.Json; +import elemental.json.JsonArray; +import elemental.json.JsonException; +import elemental.json.JsonObject; +import elemental.json.impl.JsonUtil; + /** * Serializes a connector hierarchy to JSON. * @@ -55,27 +57,27 @@ public class ConnectorHierarchyWriter implements Serializable { Collection<ClientConnector> dirtyVisibleConnectors = ui .getConnectorTracker().getDirtyVisibleConnectors(); - JSONObject hierarchyInfo = new JSONObject(); + JsonObject hierarchyInfo = Json.createObject(); for (ClientConnector connector : dirtyVisibleConnectors) { String connectorId = connector.getConnectorId(); - JSONArray children = new JSONArray(); + JsonArray children = Json.createArray(); for (ClientConnector child : AbstractClientConnector .getAllChildrenIterable(connector)) { if (LegacyCommunicationManager .isConnectorVisibleToClient(child)) { - children.put(child.getConnectorId()); + children.set(children.length(), child.getConnectorId()); } } try { hierarchyInfo.put(connectorId, children); - } catch (JSONException e) { + } catch (JsonException e) { throw new PaintException( "Failed to send hierarchy information about " + connectorId + " to the client: " + e.getMessage(), e); } } - writer.write(hierarchyInfo.toString()); + writer.write(JsonUtil.stringify(hierarchyInfo)); } } diff --git a/server/src/com/vaadin/server/communication/ConnectorTypeWriter.java b/server/src/com/vaadin/server/communication/ConnectorTypeWriter.java index 0bafd20a81..d534987061 100644 --- a/server/src/com/vaadin/server/communication/ConnectorTypeWriter.java +++ b/server/src/com/vaadin/server/communication/ConnectorTypeWriter.java @@ -21,14 +21,16 @@ import java.io.Serializable; import java.io.Writer; import java.util.Collection; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.ClientConnector; import com.vaadin.server.PaintException; import com.vaadin.server.PaintTarget; import com.vaadin.ui.UI; +import elemental.json.Json; +import elemental.json.JsonException; +import elemental.json.JsonObject; +import elemental.json.impl.JsonUtil; + /** * Serializes connector type mappings to JSON. * @@ -56,18 +58,18 @@ public class ConnectorTypeWriter implements Serializable { Collection<ClientConnector> dirtyVisibleConnectors = ui .getConnectorTracker().getDirtyVisibleConnectors(); - JSONObject connectorTypes = new JSONObject(); + JsonObject connectorTypes = Json.createObject(); for (ClientConnector connector : dirtyVisibleConnectors) { String connectorType = target.getTag(connector); try { connectorTypes.put(connector.getConnectorId(), connectorType); - } catch (JSONException e) { + } catch (JsonException e) { throw new PaintException( "Failed to send connector type for connector " + connector.getConnectorId() + ": " + e.getMessage(), e); } } - writer.write(connectorTypes.toString()); + writer.write(JsonUtil.stringify(connectorTypes)); } } diff --git a/server/src/com/vaadin/server/communication/DateSerializer.java b/server/src/com/vaadin/server/communication/DateSerializer.java index 429941abfd..b66e46bc96 100644 --- a/server/src/com/vaadin/server/communication/DateSerializer.java +++ b/server/src/com/vaadin/server/communication/DateSerializer.java @@ -19,6 +19,8 @@ import java.lang.reflect.Type; import java.util.Date; import com.vaadin.ui.ConnectorTracker; +import elemental.json.Json; +import elemental.json.JsonValue; /** * Server side serializer/deserializer for java.util.Date @@ -26,17 +28,17 @@ import com.vaadin.ui.ConnectorTracker; * @since 7.2 * @author Vaadin Ltd */ -public class DateSerializer implements JSONSerializer<Date> { +public class DateSerializer implements JsonSerializer<Date> { @Override - public Date deserialize(Type type, Object jsonValue, + public Date deserialize(Type type, JsonValue jsonValue, ConnectorTracker connectorTracker) { - return new Date(Long.valueOf(String.valueOf(jsonValue))); + return new Date((long) jsonValue.asNumber()); } @Override - public Object serialize(Date value, ConnectorTracker connectorTracker) { - return value.getTime(); + public JsonValue serialize(Date value, ConnectorTracker connectorTracker) { + return Json.create(value.getTime()); } } diff --git a/server/src/com/vaadin/server/communication/JSONSerializer.java b/server/src/com/vaadin/server/communication/JsonSerializer.java index 91105d6ffd..39d145ec1b 100644 --- a/server/src/com/vaadin/server/communication/JSONSerializer.java +++ b/server/src/com/vaadin/server/communication/JsonSerializer.java @@ -18,17 +18,18 @@ package com.vaadin.server.communication; import java.lang.reflect.Type; import com.vaadin.ui.ConnectorTracker; +import elemental.json.JsonValue; /** * Implementors of this interface knows how to serialize an Object of a given * type to JSON and how to deserialize the JSON back into an object. * <p> * The {@link #serialize(Object, ConnectorTracker)} and - * {@link #deserialize(Type, Object, ConnectorTracker)} methods must be + * {@link #deserialize(Type, JsonValue, ConnectorTracker)} methods must be * symmetric so they can be chained and produce the original result (or an equal * result). * <p> - * Each {@link JSONSerializer} implementation can handle an object of a single + * Each {@link JsonSerializer} implementation can handle an object of a single * type. * <p> * This is the server side interface, see @@ -37,15 +38,12 @@ import com.vaadin.ui.ConnectorTracker; * @since 7.2 * @author Vaadin Ltd */ -public interface JSONSerializer<T> { +public interface JsonSerializer<T> { /** * Creates and deserializes an object received from the client. Must be * compatible with {@link #serialize(Object, ConnectorTracker)} and also * with the client side com.vaadin.client.communication.JSONSerializer. - * <p> - * The json parameter is of type Object as org.json JSON classes have no - * other common super class - * + * * @param type * The expected return type * @param jsonValue @@ -54,11 +52,11 @@ public interface JSONSerializer<T> { * the connector tracker instance for the UI * @return A deserialized object */ - T deserialize(Type type, Object jsonValue, ConnectorTracker connectorTracker); + T deserialize(Type type, JsonValue jsonValue, ConnectorTracker connectorTracker); /** * Serialize the given object into JSON. Must be compatible with - * {@link #deserialize(Object, connectorTracker)} and the client side + * {@link #deserialize(Type, JsonValue, ConnectorTracker)} and the client side * com.vaadin.client.communication.JSONSerializer * * @param value @@ -67,6 +65,6 @@ public interface JSONSerializer<T> { * The connector tracker instance for the UI * @return A JSON serialized version of the object */ - Object serialize(T value, ConnectorTracker connectorTracker); + JsonValue serialize(T value, ConnectorTracker connectorTracker); } diff --git a/server/src/com/vaadin/server/communication/PortletBootstrapHandler.java b/server/src/com/vaadin/server/communication/PortletBootstrapHandler.java index 66b08fdadd..1d1a300cd1 100644 --- a/server/src/com/vaadin/server/communication/PortletBootstrapHandler.java +++ b/server/src/com/vaadin/server/communication/PortletBootstrapHandler.java @@ -25,9 +25,6 @@ import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.ResourceURL; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.BootstrapHandler; import com.vaadin.server.PaintException; import com.vaadin.server.VaadinPortlet; @@ -39,6 +36,7 @@ import com.vaadin.server.VaadinResponse; import com.vaadin.server.VaadinService; import com.vaadin.server.VaadinSession; import com.vaadin.shared.ApplicationConstants; +import elemental.json.JsonObject; public class PortletBootstrapHandler extends BootstrapHandler { @Override @@ -71,7 +69,7 @@ public class PortletBootstrapHandler extends BootstrapHandler { @Override protected void appendMainScriptTagContents(BootstrapContext context, - StringBuilder builder) throws JSONException, IOException { + StringBuilder builder) throws IOException { // fixed base theme to use - all portal pages with Vaadin // applications will load this exactly once String portalTheme = ((VaadinPortletRequest) context.getRequest()) @@ -94,9 +92,9 @@ public class PortletBootstrapHandler extends BootstrapHandler { } @Override - protected JSONObject getApplicationParameters(BootstrapContext context) - throws JSONException, PaintException { - JSONObject parameters = super.getApplicationParameters(context); + protected JsonObject getApplicationParameters(BootstrapContext context) + throws PaintException { + JsonObject parameters = super.getApplicationParameters(context); VaadinPortletResponse response = (VaadinPortletResponse) context .getResponse(); VaadinPortletRequest request = (VaadinPortletRequest) context diff --git a/server/src/com/vaadin/server/communication/PushHandler.java b/server/src/com/vaadin/server/communication/PushHandler.java index 67e5f87153..6ee81270cd 100644 --- a/server/src/com/vaadin/server/communication/PushHandler.java +++ b/server/src/com/vaadin/server/communication/PushHandler.java @@ -29,7 +29,6 @@ import org.atmosphere.cpr.AtmosphereResource.TRANSPORT; import org.atmosphere.cpr.AtmosphereResourceEvent; import org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter; import org.atmosphere.handler.AbstractReflectorAtmosphereHandler; -import org.json.JSONException; import com.vaadin.server.ErrorEvent; import com.vaadin.server.ErrorHandler; @@ -46,6 +45,7 @@ import com.vaadin.server.VaadinSession; import com.vaadin.shared.ApplicationConstants; import com.vaadin.shared.communication.PushMode; import com.vaadin.ui.UI; +import elemental.json.JsonException; /** * Establishes bidirectional ("push") communication channels @@ -173,7 +173,7 @@ public class PushHandler extends AtmosphereResourceEventListenerAdapter { try { new ServerRpcHandler().handleRpc(ui, reader, vaadinRequest); connection.push(false); - } catch (JSONException e) { + } catch (JsonException e) { getLogger().log(Level.SEVERE, "Error writing JSON to response", e); // Refresh on client side diff --git a/server/src/com/vaadin/server/communication/ServerRpcHandler.java b/server/src/com/vaadin/server/communication/ServerRpcHandler.java index ae076e0856..d1b1be6b97 100644 --- a/server/src/com/vaadin/server/communication/ServerRpcHandler.java +++ b/server/src/com/vaadin/server/communication/ServerRpcHandler.java @@ -28,10 +28,6 @@ import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.ClientConnector; import com.vaadin.server.JsonCodec; import com.vaadin.server.LegacyCommunicationManager; @@ -52,6 +48,12 @@ import com.vaadin.ui.Component; import com.vaadin.ui.ConnectorTracker; import com.vaadin.ui.UI; +import elemental.json.JsonArray; +import elemental.json.JsonException; +import elemental.json.JsonObject; +import elemental.json.JsonValue; +import elemental.json.impl.JsonUtil; + /** * Handles a client-to-server message containing serialized {@link ServerRpc * server RPC} invocations. @@ -71,28 +73,31 @@ public class ServerRpcHandler implements Serializable { public static class RpcRequest implements Serializable { private final String csrfToken; - private final JSONArray invocations; + private final JsonArray invocations; private final int syncId; - private final JSONObject json; + private final JsonObject json; - public RpcRequest(String jsonString, VaadinRequest request) - throws JSONException { - json = new JSONObject(jsonString); + public RpcRequest(String jsonString, VaadinRequest request) { + json = JsonUtil.parse(jsonString); - String csrfToken = json.optString(ApplicationConstants.CSRF_TOKEN); - if (csrfToken.equals("")) { - csrfToken = ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE; + JsonValue token = json.get(ApplicationConstants.CSRF_TOKEN); + if (token == null) { + this.csrfToken = ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE; + } else { + String csrfToken = token.asString(); + if (csrfToken.equals("")) { + csrfToken = ApplicationConstants.CSRF_TOKEN_DEFAULT_VALUE; + } + this.csrfToken = csrfToken; } - this.csrfToken = csrfToken; if (request.getService().getDeploymentConfiguration() .isSyncIdCheckEnabled()) { - syncId = json.getInt(ApplicationConstants.SERVER_SYNC_ID); + syncId = (int) json.getNumber(ApplicationConstants.SERVER_SYNC_ID); } else { syncId = -1; } - invocations = json - .getJSONArray(ApplicationConstants.RPC_INVOCATIONS); + invocations = json.getArray(ApplicationConstants.RPC_INVOCATIONS); } /** @@ -110,7 +115,7 @@ public class ServerRpcHandler implements Serializable { * @return the data describing which RPC should be made, and all their * data */ - public JSONArray getRpcInvocationsData() { + public JsonArray getRpcInvocationsData() { return invocations; } @@ -134,7 +139,7 @@ public class ServerRpcHandler implements Serializable { * @return the raw JSON object that was received from the client * */ - public JSONObject getRawJson() { + public JsonObject getRawJson() { return json; } } @@ -155,11 +160,9 @@ public class ServerRpcHandler implements Serializable { * @throws InvalidUIDLSecurityKeyException * If the received security key does not match the one stored in * the session. - * @throws JSONException - * If deserializing the JSON fails. */ public void handleRpc(UI ui, Reader reader, VaadinRequest request) - throws IOException, InvalidUIDLSecurityKeyException, JSONException { + throws IOException, InvalidUIDLSecurityKeyException { ui.getSession().setLastRequestTimestamp(System.currentTimeMillis()); String changeMessage = getMessage(reader); @@ -205,7 +208,7 @@ public class ServerRpcHandler implements Serializable { * requested RPC calls. */ private void handleInvocations(UI uI, int lastSyncIdSeenByClient, - JSONArray invocationsData) { + JsonArray invocationsData) { // TODO PUSH Refactor so that this is not needed LegacyCommunicationManager manager = uI.getSession() .getCommunicationManager(); @@ -314,7 +317,7 @@ public class ServerRpcHandler implements Serializable { } } } - } catch (JSONException e) { + } catch (JsonException e) { getLogger().warning( "Unable to parse RPC call from the client: " + e.getMessage()); @@ -334,11 +337,10 @@ public class ServerRpcHandler implements Serializable { * the most recent sync id the client has seen at the time the * request was sent * @return list of MethodInvocation to perform - * @throws JSONException */ private List<MethodInvocation> parseInvocations( - ConnectorTracker connectorTracker, JSONArray invocationsJson, - int lastSyncIdSeenByClient) throws JSONException { + ConnectorTracker connectorTracker, JsonArray invocationsJson, + int lastSyncIdSeenByClient) { int invocationCount = invocationsJson.length(); ArrayList<MethodInvocation> invocations = new ArrayList<MethodInvocation>( invocationCount); @@ -347,7 +349,7 @@ public class ServerRpcHandler implements Serializable { // parse JSON to MethodInvocations for (int i = 0; i < invocationCount; ++i) { - JSONArray invocationJson = invocationsJson.getJSONArray(i); + JsonArray invocationJson = invocationsJson.getArray(i); MethodInvocation invocation = parseInvocation(invocationJson, previousInvocation, connectorTracker, @@ -363,17 +365,15 @@ public class ServerRpcHandler implements Serializable { return invocations; } - private MethodInvocation parseInvocation(JSONArray invocationJson, + private MethodInvocation parseInvocation(JsonArray invocationJson, MethodInvocation previousInvocation, - ConnectorTracker connectorTracker, long lastSyncIdSeenByClient) - throws JSONException { + ConnectorTracker connectorTracker, long lastSyncIdSeenByClient) { String connectorId = invocationJson.getString(0); String interfaceName = invocationJson.getString(1); String methodName = invocationJson.getString(2); if (connectorTracker.getConnector(connectorId) == null - && !connectorId - .equals(ApplicationConstants.DRAG_AND_DROP_CONNECTOR_ID)) { + && !connectorId.equals(ApplicationConstants.DRAG_AND_DROP_CONNECTOR_ID)) { if (!connectorTracker.connectorWasPresentAsRequestWasSent( connectorId, lastSyncIdSeenByClient)) { @@ -393,7 +393,7 @@ public class ServerRpcHandler implements Serializable { return null; } - JSONArray parametersJson = invocationJson.getJSONArray(3); + JsonArray parametersJson = invocationJson.getArray(3); if (LegacyChangeVariablesInvocation.isLegacyVariableChange( interfaceName, methodName)) { @@ -415,10 +415,9 @@ public class ServerRpcHandler implements Serializable { private LegacyChangeVariablesInvocation parseLegacyChangeVariablesInvocation( String connectorId, String interfaceName, String methodName, LegacyChangeVariablesInvocation previousInvocation, - JSONArray parametersJson, ConnectorTracker connectorTracker) - throws JSONException { + JsonArray parametersJson, ConnectorTracker connectorTracker) { if (parametersJson.length() != 2) { - throw new JSONException( + throw new JsonException( "Invalid parameters in legacy change variables call. Expected 2, was " + parametersJson.length()); } @@ -440,8 +439,8 @@ public class ServerRpcHandler implements Serializable { private ServerRpcMethodInvocation parseServerRpcInvocation( String connectorId, String interfaceName, String methodName, - JSONArray parametersJson, ConnectorTracker connectorTracker) - throws JSONException { + JsonArray parametersJson, ConnectorTracker connectorTracker) + throws JsonException { ClientConnector connector = connectorTracker.getConnector(connectorId); ServerRpcManager<?> rpcManager = connector.getRpcManager(interfaceName); @@ -471,7 +470,7 @@ public class ServerRpcHandler implements Serializable { .getGenericParameterTypes(); for (int j = 0; j < parametersJson.length(); ++j) { - Object parameterValue = parametersJson.get(j); + JsonValue parameterValue = parametersJson.get(j); Type parameterType = declaredRpcMethodParameterTypes[j]; parameters[j] = JsonCodec.decodeInternalOrCustomType(parameterType, parameterValue, connectorTracker); diff --git a/server/src/com/vaadin/server/communication/SharedStateWriter.java b/server/src/com/vaadin/server/communication/SharedStateWriter.java index 6a318f0758..6ef02955f7 100644 --- a/server/src/com/vaadin/server/communication/SharedStateWriter.java +++ b/server/src/com/vaadin/server/communication/SharedStateWriter.java @@ -21,14 +21,16 @@ import java.io.Serializable; import java.io.Writer; import java.util.Collection; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.ClientConnector; import com.vaadin.server.PaintException; import com.vaadin.shared.communication.SharedState; import com.vaadin.ui.UI; +import elemental.json.Json; +import elemental.json.JsonException; +import elemental.json.JsonObject; +import elemental.json.impl.JsonUtil; + /** * Serializes {@link SharedState shared state} changes to JSON. * @@ -53,16 +55,16 @@ public class SharedStateWriter implements Serializable { Collection<ClientConnector> dirtyVisibleConnectors = ui .getConnectorTracker().getDirtyVisibleConnectors(); - JSONObject sharedStates = new JSONObject(); + JsonObject sharedStates = Json.createObject(); for (ClientConnector connector : dirtyVisibleConnectors) { // encode and send shared state try { - JSONObject stateJson = connector.encodeState(); + JsonObject stateJson = connector.encodeState(); - if (stateJson != null && stateJson.length() != 0) { + if (stateJson != null && stateJson.keys().length != 0) { sharedStates.put(connector.getConnectorId(), stateJson); } - } catch (JSONException e) { + } catch (JsonException e) { throw new PaintException( "Failed to serialize shared state for connector " + connector.getClass().getName() + " (" @@ -70,6 +72,6 @@ public class SharedStateWriter implements Serializable { + e.getMessage(), e); } } - writer.write(sharedStates.toString()); + writer.write(JsonUtil.stringify(sharedStates)); } } diff --git a/server/src/com/vaadin/server/communication/UIInitHandler.java b/server/src/com/vaadin/server/communication/UIInitHandler.java index cf0de8e9ee..356ad25219 100644 --- a/server/src/com/vaadin/server/communication/UIInitHandler.java +++ b/server/src/com/vaadin/server/communication/UIInitHandler.java @@ -23,9 +23,6 @@ import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.annotations.PreserveOnRefresh; import com.vaadin.server.LegacyApplicationUIProvider; import com.vaadin.server.SynchronizedRequestHandler; @@ -43,6 +40,11 @@ import com.vaadin.shared.ui.ui.Transport; import com.vaadin.shared.ui.ui.UIConstants; import com.vaadin.ui.UI; +import elemental.json.Json; +import elemental.json.JsonException; +import elemental.json.JsonObject; +import elemental.json.impl.JsonUtil; + /** * Handles an initial request from the client to initialize a {@link UI}. * @@ -75,13 +77,13 @@ public abstract class UIInitHandler extends SynchronizedRequestHandler { session.getCommunicationManager().repaintAll(uI); - JSONObject params = new JSONObject(); + JsonObject params = Json.createObject(); params.put(UIConstants.UI_ID_PARAMETER, uI.getUIId()); String initialUIDL = getInitialUidl(request, uI); params.put("uidl", initialUIDL); - stringWriter.write(params.toString()); - } catch (JSONException e) { + stringWriter.write(JsonUtil.stringify(params)); + } catch (JsonException e) { throw new IOException("Error producing initial UIDL", e); } finally { stringWriter.close(); @@ -278,12 +280,10 @@ public abstract class UIInitHandler extends SynchronizedRequestHandler { * @param uI * the UI for which the UIDL should be generated * @return a string with the initial UIDL message - * @throws JSONException - * if an exception occurs while encoding output * @throws IOException */ protected String getInitialUidl(VaadinRequest request, UI uI) - throws JSONException, IOException { + throws IOException { StringWriter writer = new StringWriter(); try { writer.write("{"); diff --git a/server/src/com/vaadin/server/communication/UidlRequestHandler.java b/server/src/com/vaadin/server/communication/UidlRequestHandler.java index 0d8ddb7bc7..d28107e8f8 100644 --- a/server/src/com/vaadin/server/communication/UidlRequestHandler.java +++ b/server/src/com/vaadin/server/communication/UidlRequestHandler.java @@ -22,8 +22,6 @@ import java.io.Writer; import java.util.logging.Level; import java.util.logging.Logger; -import org.json.JSONException; - import com.vaadin.server.Constants; import com.vaadin.server.LegacyCommunicationManager.InvalidUIDLSecurityKeyException; import com.vaadin.server.ServletPortletHelper; @@ -38,6 +36,7 @@ import com.vaadin.shared.ApplicationConstants; import com.vaadin.shared.JsonConstants; import com.vaadin.shared.Version; import com.vaadin.ui.UI; +import elemental.json.JsonException; /** * Processes a UIDL request from the client. @@ -97,7 +96,7 @@ public class UidlRequestHandler extends SynchronizedRequestHandler implements } writeUidl(request, response, uI, stringWriter, repaintAll); - } catch (JSONException e) { + } catch (JsonException e) { getLogger().log(Level.SEVERE, "Error writing JSON to response", e); // Refresh on client side response.getWriter().write( @@ -144,8 +143,7 @@ public class UidlRequestHandler extends SynchronizedRequestHandler implements } private void writeUidl(VaadinRequest request, VaadinResponse response, - UI ui, Writer writer, boolean repaintAll) throws IOException, - JSONException { + UI ui, Writer writer, boolean repaintAll) throws IOException { openJsonMessage(writer, response); new UidlWriter().write(ui, writer, repaintAll, false); diff --git a/server/src/com/vaadin/server/communication/UidlWriter.java b/server/src/com/vaadin/server/communication/UidlWriter.java index 9d55f7e197..3b2caba55b 100644 --- a/server/src/com/vaadin/server/communication/UidlWriter.java +++ b/server/src/com/vaadin/server/communication/UidlWriter.java @@ -27,9 +27,6 @@ import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; -import org.json.JSONArray; -import org.json.JSONException; - import com.vaadin.annotations.JavaScript; import com.vaadin.annotations.StyleSheet; import com.vaadin.server.ClientConnector; @@ -43,6 +40,10 @@ import com.vaadin.shared.ApplicationConstants; import com.vaadin.ui.ConnectorTracker; import com.vaadin.ui.UI; +import elemental.json.Json; +import elemental.json.JsonArray; +import elemental.json.impl.JsonUtil; + /** * Serializes pending server-side changes to UI state to JSON. This includes * shared state, client RPC invocations, connector hierarchy changes, connector @@ -70,11 +71,9 @@ public class UidlWriter implements Serializable { * * @throws IOException * If the writing fails. - * @throws JSONException - * If the JSON serialization fails. */ public void write(UI ui, Writer writer, boolean repaintAll, boolean async) - throws IOException, JSONException { + throws IOException { VaadinSession session = ui.getSession(); VaadinService service = session.getService(); @@ -282,13 +281,13 @@ public class UidlWriter implements Serializable { // Include script dependencies in output if there are any if (!scriptDependencies.isEmpty()) { writer.write(", \"scriptDependencies\": " - + new JSONArray(scriptDependencies).toString()); + + JsonUtil.stringify(toJsonArray(scriptDependencies))); } // Include style dependencies in output if there are any if (!styleDependencies.isEmpty()) { writer.write(", \"styleDependencies\": " - + new JSONArray(styleDependencies).toString()); + + JsonUtil.stringify(toJsonArray(styleDependencies))); } session.getDragAndDropService().printJSONResponse(writer); @@ -306,6 +305,15 @@ public class UidlWriter implements Serializable { } } + private JsonArray toJsonArray(List<String> list) { + JsonArray result = Json.createArray(); + for (int i = 0; i < list.size(); i++) { + result.set(i, list.get(i)); + } + + return result; + } + /** * Adds the performance timing data (used by TestBench 3) to the UIDL * response. diff --git a/server/src/com/vaadin/ui/Button.java b/server/src/com/vaadin/ui/Button.java index 58b6f9de81..76b82aa034 100644 --- a/server/src/com/vaadin/ui/Button.java +++ b/server/src/com/vaadin/ui/Button.java @@ -19,8 +19,6 @@ package com.vaadin.ui; import java.io.Serializable; import java.lang.reflect.Method; -import org.json.JSONException; - import com.vaadin.event.Action; import com.vaadin.event.FieldEvents; import com.vaadin.event.FieldEvents.BlurEvent; @@ -63,12 +61,8 @@ public class Button extends AbstractComponent implements // Makes sure the enabled=false state is noticed at once - otherwise // a following setEnabled(true) call might have no effect. see // ticket #10030 - try { - getUI().getConnectorTracker().getDiffState(Button.this) - .put("enabled", false); - } catch (JSONException e) { - throw new RuntimeException(e); - } + getUI().getConnectorTracker().getDiffState(Button.this) + .put("enabled", false); } }; diff --git a/server/src/com/vaadin/ui/CheckBox.java b/server/src/com/vaadin/ui/CheckBox.java index 3c4ce1c528..7d9da30f29 100644 --- a/server/src/com/vaadin/ui/CheckBox.java +++ b/server/src/com/vaadin/ui/CheckBox.java @@ -16,8 +16,6 @@ package com.vaadin.ui; -import org.json.JSONException; - import com.vaadin.data.Property; import com.vaadin.event.FieldEvents.BlurEvent; import com.vaadin.event.FieldEvents.BlurListener; @@ -47,12 +45,8 @@ public class CheckBox extends AbstractField<Boolean> { * * See #11028, #10030. */ - try { - getUI().getConnectorTracker().getDiffState(CheckBox.this) - .put("checked", checked); - } catch (JSONException e) { - throw new RuntimeException(e); - } + getUI().getConnectorTracker().getDiffState(CheckBox.this) + .put("checked", checked); final Boolean oldValue = getValue(); final Boolean newValue = checked; diff --git a/server/src/com/vaadin/ui/ConnectorTracker.java b/server/src/com/vaadin/ui/ConnectorTracker.java index 9b8729f779..5386eb9d64 100644 --- a/server/src/com/vaadin/ui/ConnectorTracker.java +++ b/server/src/com/vaadin/ui/ConnectorTracker.java @@ -30,9 +30,6 @@ import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.AbstractClientConnector; import com.vaadin.server.ClientConnector; import com.vaadin.server.DragAndDropService; @@ -40,6 +37,10 @@ import com.vaadin.server.GlobalResourceHandler; import com.vaadin.server.LegacyCommunicationManager; import com.vaadin.server.StreamVariable; +import elemental.json.Json; +import elemental.json.JsonException; +import elemental.json.JsonObject; + /** * A class which takes care of book keeping of {@link ClientConnector}s for a * UI. @@ -76,7 +77,7 @@ public class ConnectorTracker implements Serializable { private boolean writingResponse = false; private UI uI; - private transient Map<ClientConnector, JSONObject> diffStates = new HashMap<ClientConnector, JSONObject>(); + private transient Map<ClientConnector, JsonObject> diffStates = new HashMap<ClientConnector, JsonObject>(); /** Maps connectorIds to a map of named StreamVariables */ private Map<String, Map<String, StreamVariable>> pidToNameToStreamVariable; @@ -556,12 +557,12 @@ public class ConnectorTracker implements Serializable { return dirtyVisibleConnectors; } - public JSONObject getDiffState(ClientConnector connector) { + public JsonObject getDiffState(ClientConnector connector) { assert getConnector(connector.getConnectorId()) == connector; return diffStates.get(connector); } - public void setDiffState(ClientConnector connector, JSONObject diffState) { + public void setDiffState(ClientConnector connector, JsonObject diffState) { assert getConnector(connector.getConnectorId()) == connector; diffStates.put(connector, diffState); } @@ -621,11 +622,11 @@ public class ConnectorTracker implements Serializable { this.writingResponse = writingResponse; } - /* Special serialization to JSONObjects which are not serializable */ + /* Special serialization to JsonObjects which are not serializable */ private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.defaultWriteObject(); - // Convert JSONObjects in diff state to String representation as - // JSONObject is not serializable + // Convert JsonObjects in diff state to String representation as + // JsonObject is not serializable HashMap<ClientConnector, String> stringDiffStates = new HashMap<ClientConnector, String>( diffStates.size() * 2); for (ClientConnector key : diffStates.keySet()) { @@ -634,23 +635,23 @@ public class ConnectorTracker implements Serializable { out.writeObject(stringDiffStates); } - /* Special serialization to JSONObjects which are not serializable */ + /* Special serialization to JsonObjects which are not serializable */ private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - // Read String versions of JSONObjects and parse into JSONObjects as - // JSONObject is not serializable - diffStates = new HashMap<ClientConnector, JSONObject>(); + // Read String versions of JsonObjects and parse into JsonObjects as + // JsonObject is not serializable + diffStates = new HashMap<ClientConnector, JsonObject>(); @SuppressWarnings("unchecked") HashMap<ClientConnector, String> stringDiffStates = (HashMap<ClientConnector, String>) in .readObject(); - diffStates = new HashMap<ClientConnector, JSONObject>( + diffStates = new HashMap<ClientConnector, JsonObject>( stringDiffStates.size() * 2); for (ClientConnector key : stringDiffStates.keySet()) { try { - diffStates.put(key, new JSONObject(stringDiffStates.get(key))); - } catch (JSONException e) { + diffStates.put(key, Json.parse(stringDiffStates.get(key))); + } catch (JsonException e) { throw new IOException(e); } } diff --git a/server/src/com/vaadin/ui/JavaScript.java b/server/src/com/vaadin/ui/JavaScript.java index 68c8c9a6e4..668ae67056 100644 --- a/server/src/com/vaadin/ui/JavaScript.java +++ b/server/src/com/vaadin/ui/JavaScript.java @@ -19,15 +19,15 @@ package com.vaadin.ui; import java.util.HashMap; import java.util.Map; -import org.json.JSONArray; -import org.json.JSONException; - import com.vaadin.server.AbstractExtension; import com.vaadin.server.Page; import com.vaadin.shared.communication.ServerRpc; import com.vaadin.shared.extension.javascriptmanager.ExecuteJavaScriptRpc; import com.vaadin.shared.extension.javascriptmanager.JavaScriptManagerState; +import elemental.json.JsonArray; +import elemental.json.JsonException; + /** * Provides access to JavaScript functionality in the web browser. To get an * instance of JavaScript, either use Page.getJavaScript() or @@ -43,7 +43,7 @@ public class JavaScript extends AbstractExtension { // Can not be defined in client package as this JSONArray is not available // in GWT public interface JavaScriptCallbackRpc extends ServerRpc { - public void call(String name, JSONArray arguments); + public void call(String name, JsonArray arguments); } /** @@ -54,12 +54,12 @@ public class JavaScript extends AbstractExtension { public JavaScript() { registerRpc(new JavaScriptCallbackRpc() { @Override - public void call(String name, JSONArray arguments) { + public void call(String name, JsonArray arguments) { JavaScriptFunction function = functions.get(name); // TODO handle situation if name is not registered try { function.call(arguments); - } catch (JSONException e) { + } catch (JsonException e) { throw new IllegalArgumentException(e); } } diff --git a/server/src/com/vaadin/ui/JavaScriptFunction.java b/server/src/com/vaadin/ui/JavaScriptFunction.java index 2c026abd1a..c006a36d58 100644 --- a/server/src/com/vaadin/ui/JavaScriptFunction.java +++ b/server/src/com/vaadin/ui/JavaScriptFunction.java @@ -18,14 +18,12 @@ package com.vaadin.ui; import java.io.Serializable; -import org.json.JSONArray; -import org.json.JSONException; - import com.vaadin.server.AbstractJavaScriptExtension; +import elemental.json.JsonArray; /** * Defines a method that is called by a client-side JavaScript function. When - * the corresponding JavaScript function is called, the {@link #call(JSONArray)} + * the corresponding JavaScript function is called, the {@link #call(JsonArray)} * method is invoked. * * @see JavaScript#addFunction(String, JavaScriptCallback) @@ -46,8 +44,6 @@ public interface JavaScriptFunction extends Serializable { * @param arguments * an array with JSON representations of the arguments with which * the JavaScript function was called. - * @throws JSONException - * if the arguments can not be interpreted */ - public void call(JSONArray arguments) throws JSONException; + public void call(JsonArray arguments); } diff --git a/server/src/com/vaadin/ui/Slider.java b/server/src/com/vaadin/ui/Slider.java index ff6c955e47..66ed1a48f4 100644 --- a/server/src/com/vaadin/ui/Slider.java +++ b/server/src/com/vaadin/ui/Slider.java @@ -16,8 +16,6 @@ package com.vaadin.ui; -import org.json.JSONException; - import com.vaadin.shared.ui.slider.SliderOrientation; import com.vaadin.shared.ui.slider.SliderServerRpc; import com.vaadin.shared.ui.slider.SliderState; @@ -42,12 +40,8 @@ public class Slider extends AbstractField<Double> { * * See #12133. */ - try { - getUI().getConnectorTracker().getDiffState(Slider.this) - .put("value", value); - } catch (JSONException e) { - throw new RuntimeException(e); - } + getUI().getConnectorTracker().getDiffState(Slider.this) + .put("value", value); try { setValue(value, true); diff --git a/server/tests/src/com/vaadin/server/JSONSerializerTest.java b/server/tests/src/com/vaadin/server/JsonSerializerTest.java index 8c1967acb3..b735d811d5 100644 --- a/server/tests/src/com/vaadin/server/JSONSerializerTest.java +++ b/server/tests/src/com/vaadin/server/JsonSerializerTest.java @@ -15,8 +15,8 @@ package com.vaadin.server; * License for the specific language governing permissions and limitations under * the License. */ + import java.lang.reflect.Type; -import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -24,14 +24,15 @@ import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.TestCase; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.JsonCodec.BeanProperty; import com.vaadin.shared.communication.UidlValue; import com.vaadin.shared.ui.splitpanel.AbstractSplitPanelState; +import elemental.json.Json; +import elemental.json.JsonArray; +import elemental.json.JsonException; +import elemental.json.JsonValue; + /** * Tests for {@link JsonCodec} * @@ -39,7 +40,7 @@ import com.vaadin.shared.ui.splitpanel.AbstractSplitPanelState; * @since 7.0 * */ -public class JSONSerializerTest extends TestCase { +public class JsonSerializerTest extends TestCase { HashMap<String, AbstractSplitPanelState> stringToStateMap; HashMap<AbstractSplitPanelState, String> stateToStringMap; @@ -56,7 +57,7 @@ public class JSONSerializerTest extends TestCase { stringToStateMap.put("string - state 1", s); stringToStateMap.put("String - state 2", s2); - Object encodedMap = JsonCodec.encode(stringToStateMap, null, mapType, + JsonValue encodedMap = JsonCodec.encode(stringToStateMap, null, mapType, null).getEncodedValue(); ensureDecodedCorrectly(stringToStateMap, encodedMap, mapType); @@ -73,15 +74,16 @@ public class JSONSerializerTest extends TestCase { stateToStringMap.put(s, "string - state 1"); stateToStringMap.put(s2, "String - state 2"); - Object encodedMap = JsonCodec.encode(stateToStringMap, null, mapType, + JsonValue encodedMap = JsonCodec.encode(stateToStringMap, null, mapType, null).getEncodedValue(); ensureDecodedCorrectly(stateToStringMap, encodedMap, mapType); } - public void testNullLegacyValue() throws JSONException { - JSONArray inputArray = new JSONArray( - Arrays.asList("n", JSONObject.NULL)); + public void testNullLegacyValue() throws JsonException { + JsonArray inputArray = Json.createArray(); + inputArray.set(0, "n"); + inputArray.set(1, Json.createNull()); UidlValue decodedObject = (UidlValue) JsonCodec.decodeInternalType( UidlValue.class, true, inputArray, null); assertNull(decodedObject.getValue()); @@ -89,17 +91,19 @@ public class JSONSerializerTest extends TestCase { public void testNullTypeOtherValue() { try { - JSONArray inputArray = new JSONArray(Arrays.asList("n", "a")); + JsonArray inputArray = Json.createArray(); + inputArray.set(0, "n"); + inputArray.set(1, "a"); UidlValue decodedObject = (UidlValue) JsonCodec.decodeInternalType( UidlValue.class, true, inputArray, null); - throw new AssertionFailedError("No JSONException thrown"); - } catch (JSONException e) { + throw new AssertionFailedError("No JsonException thrown"); + } catch (JsonException e) { // Should throw exception } } - private void ensureDecodedCorrectly(Object original, Object encoded, + private void ensureDecodedCorrectly(Object original, JsonValue encoded, Type type) throws Exception { Object serverSideDecoded = JsonCodec.decodeInternalOrCustomType(type, encoded, null); diff --git a/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTestServer.java b/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTestServer.java index 30f1c85fef..214341371a 100644 --- a/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTestServer.java +++ b/server/tests/src/com/vaadin/tests/server/CsrfTokenMissingTestServer.java @@ -22,7 +22,6 @@ import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.easymock.EasyMock; -import org.json.JSONException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -37,6 +36,7 @@ import com.vaadin.server.communication.ServerRpcHandler.RpcRequest; import com.vaadin.shared.ApplicationConstants; import com.vaadin.tests.util.AlwaysLockedVaadinSession; import com.vaadin.tests.util.MockDeploymentConfiguration; +import elemental.json.JsonException; /** * Test the actual csrf token validation by the server. @@ -141,7 +141,7 @@ public class CsrfTokenMissingTestServer { private RpcRequest createRequest() { try { return new RpcRequest(getPayload(), vaadinRequest); - } catch (JSONException e) { + } catch (JsonException e) { LOGGER.log(Level.SEVERE, "", e); Assert.assertTrue(false); diff --git a/server/tests/src/com/vaadin/tests/server/TestClassesSerializable.java b/server/tests/src/com/vaadin/tests/server/TestClassesSerializable.java index 63f79504ff..9bcabc9329 100644 --- a/server/tests/src/com/vaadin/tests/server/TestClassesSerializable.java +++ b/server/tests/src/com/vaadin/tests/server/TestClassesSerializable.java @@ -51,7 +51,7 @@ public class TestClassesSerializable extends TestCase { "com\\.vaadin\\.server\\.communication\\.PushRequestHandler.*", "com\\.vaadin\\.server\\.communication\\.PushHandler.*", // PushHandler "com\\.vaadin\\.server\\.communication\\.DateSerializer", // - "com\\.vaadin\\.server\\.communication\\.JSONSerializer", // + "com\\.vaadin\\.server\\.communication\\.JsonSerializer", // // and its inner classes do not need to be serializable "com\\.vaadin\\.util\\.SerializerHelper", // fully static // class level filtering, also affecting nested classes and diff --git a/server/tests/src/com/vaadin/tests/server/TestClientMethodSerialization.java b/server/tests/src/com/vaadin/tests/server/TestClientMethodSerialization.java index 41b71a37fa..ad70024af4 100644 --- a/server/tests/src/com/vaadin/tests/server/TestClientMethodSerialization.java +++ b/server/tests/src/com/vaadin/tests/server/TestClientMethodSerialization.java @@ -21,22 +21,23 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Method; -import java.util.Arrays; import junit.framework.TestCase; -import org.json.JSONArray; - import com.vaadin.server.ClientMethodInvocation; import com.vaadin.server.JavaScriptCallbackHelper; import com.vaadin.ui.JavaScript.JavaScriptCallbackRpc; import com.vaadin.util.ReflectTools; +import elemental.json.Json; +import elemental.json.JsonArray; +import elemental.json.impl.JsonUtil; + public class TestClientMethodSerialization extends TestCase { private static final Method JAVASCRIPT_CALLBACK_METHOD = ReflectTools .findMethod(JavaScriptCallbackRpc.class, "call", String.class, - JSONArray.class); + JsonArray.class); private static final Method BASIC_PARAMS_CALL_METHOD = ReflectTools .findMethod(TestClientMethodSerialization.class, @@ -60,15 +61,17 @@ public class TestClientMethodSerialization extends TestCase { */ public void testClientMethodSerialization_WithJSONArray_ContentStaysSame() throws Exception { - JSONArray originalArray = new JSONArray(Arrays.asList( - "callbackParameter1", "callBackParameter2", "12345")); + JsonArray originalArray = Json.createArray(); + originalArray.set(0, "callbackParameter1"); + originalArray.set(1, "callBackParameter2"); + originalArray.set(2, "12345"); ClientMethodInvocation original = new ClientMethodInvocation(null, "interfaceName", JAVASCRIPT_CALLBACK_METHOD, new Object[] { "callBackMethodName", originalArray }); ClientMethodInvocation copy = (ClientMethodInvocation) serializeAndDeserialize(original); - JSONArray copyArray = (JSONArray) copy.getParameters()[1]; - assertEquals(originalArray.toString(), copyArray.toString()); + JsonArray copyArray = (JsonArray) copy.getParameters()[1]; + assertEquals(JsonUtil.stringify(originalArray), JsonUtil.stringify(copyArray)); } public void testClientMethodSerialization_WithBasicParams_NoChanges() diff --git a/shared/ivy.xml b/shared/ivy.xml index 2dac7adbc2..dcb7390c04 100644 --- a/shared/ivy.xml +++ b/shared/ivy.xml @@ -27,8 +27,6 @@ conf="build,ide,test->default" /> <dependency org="com.vaadin.external.google" name="guava" rev="16.0.1.vaadin1" conf="build,ide,test->default" /> - <dependency org="com.vaadin.external.json" name="json" - rev="0.0.20080701" conf="build,ide,test->default" /> <dependency org="junit" name="junit" rev="4.11" conf="test,ide -> default" /> diff --git a/uitest/src/com/vaadin/tests/components/javascriptcomponent/BasicJavaScriptComponent.java b/uitest/src/com/vaadin/tests/components/javascriptcomponent/BasicJavaScriptComponent.java index 5a64cb6a00..bd7522aab7 100644 --- a/uitest/src/com/vaadin/tests/components/javascriptcomponent/BasicJavaScriptComponent.java +++ b/uitest/src/com/vaadin/tests/components/javascriptcomponent/BasicJavaScriptComponent.java @@ -19,9 +19,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.json.JSONArray; -import org.json.JSONException; - import com.vaadin.annotations.JavaScript; import com.vaadin.server.ConnectorResource; import com.vaadin.server.DownloadStream; @@ -39,6 +36,7 @@ import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.HasComponents; import com.vaadin.ui.JavaScriptFunction; +import elemental.json.JsonArray; public class BasicJavaScriptComponent extends AbstractTestUI { @@ -78,15 +76,15 @@ public class BasicJavaScriptComponent extends AbstractTestUI { }); addFunction("messageToServer", new JavaScriptFunction() { @Override - public void call(JSONArray arguments) throws JSONException { + public void call(JsonArray arguments) { log.log("Got callback message: " + arguments.getString(0)); } }); addFunction("reportParentIds", new JavaScriptFunction() { @Override - public void call(JSONArray arguments) throws JSONException { - JSONArray parentIds = arguments.getJSONArray(0); + public void call(JsonArray arguments) { + JsonArray parentIds = arguments.getArray(0); if (!parentIds.getString(0).equals(getConnectorId())) { log.log("Connector ids doesn't match"); } diff --git a/uitest/src/com/vaadin/tests/components/table/TableRemovedQuicklySendsInvalidRpcCalls.java b/uitest/src/com/vaadin/tests/components/table/TableRemovedQuicklySendsInvalidRpcCalls.java index c21a38a0ac..710a4f8fe3 100644 --- a/uitest/src/com/vaadin/tests/components/table/TableRemovedQuicklySendsInvalidRpcCalls.java +++ b/uitest/src/com/vaadin/tests/components/table/TableRemovedQuicklySendsInvalidRpcCalls.java @@ -19,8 +19,6 @@ package com.vaadin.tests.components.table; import java.util.ArrayList; import java.util.Collection; -import org.json.JSONObject; - import com.vaadin.annotations.Push; import com.vaadin.server.ClientConnector; import com.vaadin.server.StreamVariable; @@ -30,6 +28,7 @@ import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.ConnectorTracker; import com.vaadin.ui.Table; +import elemental.json.JsonObject; @Push public class TableRemovedQuicklySendsInvalidRpcCalls extends AbstractTestUI { @@ -125,12 +124,12 @@ public class TableRemovedQuicklySendsInvalidRpcCalls extends AbstractTestUI { } @Override - public JSONObject getDiffState(ClientConnector connector) { + public JsonObject getDiffState(ClientConnector connector) { return tracker.getDiffState(connector); } @Override - public void setDiffState(ClientConnector connector, JSONObject diffState) { + public void setDiffState(ClientConnector connector, JsonObject diffState) { tracker.setDiffState(connector, diffState); } diff --git a/uitest/src/com/vaadin/tests/extensions/JavascriptManagerTest.java b/uitest/src/com/vaadin/tests/extensions/JavascriptManagerTest.java index b89e16d755..4807bb9029 100644 --- a/uitest/src/com/vaadin/tests/extensions/JavascriptManagerTest.java +++ b/uitest/src/com/vaadin/tests/extensions/JavascriptManagerTest.java @@ -16,16 +16,15 @@ package com.vaadin.tests.extensions; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - import com.vaadin.server.VaadinRequest; import com.vaadin.tests.components.AbstractTestUI; import com.vaadin.tests.util.Log; import com.vaadin.ui.JavaScript; import com.vaadin.ui.JavaScriptFunction; +import elemental.json.JsonArray; +import elemental.json.JsonNull; + public class JavascriptManagerTest extends AbstractTestUI { private Log log = new Log(5); @@ -36,14 +35,14 @@ public class JavascriptManagerTest extends AbstractTestUI { final JavaScript js = JavaScript.getCurrent(); js.addFunction("testing.doTest", new JavaScriptFunction() { @Override - public void call(JSONArray arguments) throws JSONException { + public void call(JsonArray arguments) { log.log("Got " + arguments.length() + " arguments"); - log.log("Argument 1 as a number: " + arguments.getInt(0)); + log.log("Argument 1 as a number: " + (int) arguments.getNumber(0)); log.log("Argument 2 as a string: " + arguments.getString(1)); log.log("Argument 3.p as a boolean: " - + arguments.getJSONObject(2).getBoolean("p")); + + arguments.getObject(2).getBoolean("p")); log.log("Argument 4 is JSONObject.NULL: " - + (arguments.get(3) == JSONObject.NULL)); + + (arguments.get(3) instanceof JsonNull)); js.removeFunction("testing.doTest"); } }); diff --git a/uitest/src/com/vaadin/tests/extensions/SimpleJavaScriptExtensionTest.java b/uitest/src/com/vaadin/tests/extensions/SimpleJavaScriptExtensionTest.java index d3e0edf04c..6f14fb301c 100644 --- a/uitest/src/com/vaadin/tests/extensions/SimpleJavaScriptExtensionTest.java +++ b/uitest/src/com/vaadin/tests/extensions/SimpleJavaScriptExtensionTest.java @@ -16,9 +16,6 @@ package com.vaadin.tests.extensions; -import org.json.JSONArray; -import org.json.JSONException; - import com.vaadin.annotations.JavaScript; import com.vaadin.annotations.StyleSheet; import com.vaadin.server.AbstractJavaScriptExtension; @@ -31,6 +28,7 @@ import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.JavaScriptFunction; import com.vaadin.ui.Notification; +import elemental.json.JsonArray; public class SimpleJavaScriptExtensionTest extends AbstractTestUI { @@ -71,7 +69,7 @@ public class SimpleJavaScriptExtensionTest extends AbstractTestUI { }); addFunction("greetToServer", new JavaScriptFunction() { @Override - public void call(JSONArray arguments) throws JSONException { + public void call(JsonArray arguments) { Notification.show(getState().getPrefix() + arguments.getString(0)); } diff --git a/uitest/src/com/vaadin/tests/minitutorials/v7a3/Flot.java b/uitest/src/com/vaadin/tests/minitutorials/v7a3/Flot.java index f4aca81ffa..86666b12e8 100644 --- a/uitest/src/com/vaadin/tests/minitutorials/v7a3/Flot.java +++ b/uitest/src/com/vaadin/tests/minitutorials/v7a3/Flot.java @@ -20,13 +20,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.json.JSONArray; -import org.json.JSONException; - import com.vaadin.annotations.JavaScript; import com.vaadin.ui.AbstractJavaScriptComponent; import com.vaadin.ui.JavaScriptFunction; import com.vaadin.ui.Notification; +import elemental.json.JsonArray; @JavaScript({ "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js", @@ -42,9 +40,9 @@ public class Flot extends AbstractJavaScriptComponent { }); addFunction("onPlotClick", new JavaScriptFunction() { @Override - public void call(JSONArray arguments) throws JSONException { - int seriesIndex = arguments.getInt(0); - int dataIndex = arguments.getInt(1); + public void call(JsonArray arguments) { + int seriesIndex = (int) arguments.getNumber(0); + int dataIndex = (int) arguments.getNumber(1); Notification.show("Clicked on [" + seriesIndex + ", " + dataIndex + "]"); } diff --git a/uitest/src/com/vaadin/tests/minitutorials/v7a3/JSAPIUI.java b/uitest/src/com/vaadin/tests/minitutorials/v7a3/JSAPIUI.java index 8f1eda6816..e98fe6d066 100644 --- a/uitest/src/com/vaadin/tests/minitutorials/v7a3/JSAPIUI.java +++ b/uitest/src/com/vaadin/tests/minitutorials/v7a3/JSAPIUI.java @@ -1,8 +1,5 @@ package com.vaadin.tests.minitutorials.v7a3; -import org.json.JSONArray; -import org.json.JSONException; - import com.vaadin.server.ExternalResource; import com.vaadin.server.VaadinRequest; import com.vaadin.ui.JavaScript; @@ -12,6 +9,9 @@ import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; import com.vaadin.ui.UI; +import elemental.json.JsonArray; +import elemental.json.JsonException; + public class JSAPIUI extends UI { @Override public void init(VaadinRequest request) { @@ -19,7 +19,7 @@ public class JSAPIUI extends UI { JavaScript.getCurrent().addFunction("com.example.api.notify", new JavaScriptFunction() { @Override - public void call(JSONArray arguments) throws JSONException { + public void call(JsonArray arguments) { try { String caption = arguments.getString(0); if (arguments.length() == 1) { @@ -28,10 +28,10 @@ public class JSAPIUI extends UI { } else { // type should be in [1] Notification.show(caption, - Type.values()[arguments.getInt(1)]); + Type.values()[((int) arguments.getNumber(1))]); } - } catch (JSONException e) { + } catch (JsonException e) { // We'll log in the console, you might not want to JavaScript.getCurrent().execute( "console.error('" + e.getMessage() + "')"); diff --git a/uitest/src/com/vaadin/tests/push/TrackMessageSizeUI.java b/uitest/src/com/vaadin/tests/push/TrackMessageSizeUI.java index 6e2784f21d..e7a74775bf 100644 --- a/uitest/src/com/vaadin/tests/push/TrackMessageSizeUI.java +++ b/uitest/src/com/vaadin/tests/push/TrackMessageSizeUI.java @@ -23,8 +23,6 @@ import java.net.URL; import javax.servlet.ServletContext; import org.apache.commons.io.IOUtils; -import org.json.JSONArray; -import org.json.JSONException; import com.vaadin.annotations.JavaScript; import com.vaadin.server.VaadinRequest; @@ -32,6 +30,7 @@ import com.vaadin.server.VaadinService; import com.vaadin.server.VaadinServletService; import com.vaadin.tests.components.AbstractTestUIWithLog; import com.vaadin.ui.JavaScriptFunction; +import elemental.json.JsonArray; // Load vaadinPush.js so that jQueryVaadin is defined @JavaScript("vaadin://vaadinPush.debug.js") @@ -58,7 +57,7 @@ public class TrackMessageSizeUI extends AbstractTestUIWithLog { getPage().getJavaScript().addFunction("logToServer", new JavaScriptFunction() { @Override - public void call(JSONArray arguments) throws JSONException { + public void call(JsonArray arguments) { String message = arguments.getString(0); log(message); } diff --git a/uitest/src/com/vaadin/tests/serialization/SerializerTestTest.java b/uitest/src/com/vaadin/tests/serialization/SerializerTestTest.java index 47bb212347..dcba561599 100644 --- a/uitest/src/com/vaadin/tests/serialization/SerializerTestTest.java +++ b/uitest/src/com/vaadin/tests/serialization/SerializerTestTest.java @@ -86,9 +86,8 @@ public class SerializerTestTest extends MultiBrowserTest { getLogRow(logRow++)); Assert.assertEquals("state.floatArray: [57, 0, -12]", getLogRow(logRow++)); - Assert.assertEquals("state.floatObjectValue: 1.0000001", - getLogRow(logRow++)); - Assert.assertEquals("state.floatValue: 3.14159", getLogRow(logRow++)); + Assert.assertTrue(getLogRow(logRow++).startsWith("state.floatObjectValue: 1.0000001")); + Assert.assertTrue(getLogRow(logRow++).startsWith("state.floatValue: 3.14159")); Assert.assertEquals("state.longArray: [-57841235865, 57]", getLogRow(logRow++)); Assert.assertEquals("state.longObjectValue: 577431841360", diff --git a/uitest/src/com/vaadin/tests/tb3/AbstractTB3Test.java b/uitest/src/com/vaadin/tests/tb3/AbstractTB3Test.java index d2313a0709..1e1cbedbd6 100644 --- a/uitest/src/com/vaadin/tests/tb3/AbstractTB3Test.java +++ b/uitest/src/com/vaadin/tests/tb3/AbstractTB3Test.java @@ -30,13 +30,13 @@ import java.net.URL; import java.util.Collections; import java.util.List; +import elemental.json.JsonObject; +import elemental.json.impl.JsonUtil; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHttpEntityEnclosingRequest; -import org.json.JSONException; -import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; @@ -1247,7 +1247,7 @@ public abstract class AbstractTB3Test extends TestBenchTestCase { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest( "POST", sessionURL.toExternalForm()); HttpResponse response = client.execute(host, r); - JSONObject object = extractObject(response); + JsonObject object = extractObject(response); URL myURL = new URL(object.getString("proxyId")); if ((myURL.getHost() != null) && (myURL.getPort() != -1)) { return myURL.getHost(); @@ -1258,13 +1258,11 @@ public abstract class AbstractTB3Test extends TestBenchTestCase { return null; } - private static JSONObject extractObject(HttpResponse resp) - throws IOException, JSONException { + private static JsonObject extractObject(HttpResponse resp) throws IOException { InputStream contents = resp.getEntity().getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(contents, writer, "UTF8"); - JSONObject objToReturn = new JSONObject(writer.toString()); - return objToReturn; + return JsonUtil.parse(writer.toString()); } } |