You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

JsonEncoder.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright 2000-2021 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.communication;
  17. import java.util.Collection;
  18. import java.util.List;
  19. import java.util.Map;
  20. import java.util.Map.Entry;
  21. import java.util.Set;
  22. import com.vaadin.client.ApplicationConnection;
  23. import com.vaadin.client.JsArrayObject;
  24. import com.vaadin.client.metadata.NoDataException;
  25. import com.vaadin.client.metadata.Property;
  26. import com.vaadin.client.metadata.Type;
  27. import com.vaadin.shared.Connector;
  28. import com.vaadin.shared.JsonConstants;
  29. import com.vaadin.shared.communication.UidlValue;
  30. import elemental.json.Json;
  31. import elemental.json.JsonArray;
  32. import elemental.json.JsonObject;
  33. import elemental.json.JsonValue;
  34. /**
  35. * Encoder for converting RPC parameters and other values to JSON for transfer
  36. * between the client and the server.
  37. *
  38. * Currently, basic data types as well as Map, String[] and Object[] are
  39. * supported, where maps and Object[] can contain other supported data types.
  40. *
  41. * TODO extensible type support
  42. *
  43. * @since 7.0
  44. */
  45. public class JsonEncoder {
  46. /**
  47. * Encode a value to a JSON representation for transport from the client to
  48. * the server.
  49. *
  50. * @param value
  51. * value to convert
  52. * @param connection
  53. * @return JSON representation of the value
  54. */
  55. public static JsonValue encode(Object value, Type type,
  56. ApplicationConnection connection) {
  57. if (null == value) {
  58. return Json.createNull();
  59. } else if (value instanceof JsonValue) {
  60. return (JsonValue) value;
  61. } else if (value instanceof String[]) {
  62. String[] array = (String[]) value;
  63. JsonArray jsonArray = Json.createArray();
  64. for (int i = 0; i < array.length; ++i) {
  65. jsonArray.set(i, array[i]);
  66. }
  67. return jsonArray;
  68. } else if (value instanceof String) {
  69. return Json.create((String) value);
  70. } else if (value instanceof Boolean) {
  71. return Json.create((Boolean) value);
  72. } else if (value instanceof Number) {
  73. return Json.create(((Number) value).doubleValue());
  74. } else if (value instanceof Character) {
  75. return Json.create(String.valueOf(value));
  76. } else if (value instanceof Object[] && type == null) {
  77. // Non-legacy arrays handed by generated serializer
  78. return encodeLegacyObjectArray((Object[]) value, connection);
  79. } else if (value instanceof Enum) {
  80. return encodeEnum((Enum<?>) value, connection);
  81. } else if (value instanceof Map) {
  82. return encodeMap((Map) value, type, connection);
  83. } else if (value instanceof Connector) {
  84. Connector connector = (Connector) value;
  85. return Json.create(connector.getConnectorId());
  86. } else if (value instanceof Collection) {
  87. return encodeCollection((Collection) value, type, connection);
  88. } else if (value instanceof UidlValue) {
  89. return encodeVariableChange((UidlValue) value, connection);
  90. } else {
  91. // First see if there's a custom serializer
  92. JSONSerializer<Object> serializer = null;
  93. if (type != null) {
  94. serializer = (JSONSerializer<Object>) type.findSerializer();
  95. if (serializer != null) {
  96. return serializer.serialize(value, connection);
  97. }
  98. }
  99. String transportType = getTransportType(value);
  100. if (transportType != null) {
  101. // Send the string value for remaining legacy types
  102. return Json.create(String.valueOf(value));
  103. } else if (type != null) {
  104. // And finally try using bean serialization logic
  105. try {
  106. JsArrayObject<Property> properties = type
  107. .getPropertiesAsArray();
  108. JsonObject jsonObject = Json.createObject();
  109. int size = properties.size();
  110. for (int i = 0; i < size; i++) {
  111. Property property = properties.get(i);
  112. Object propertyValue = property.getValue(value);
  113. Type propertyType = property.getType();
  114. JsonValue encodedPropertyValue = encode(propertyValue,
  115. propertyType, connection);
  116. jsonObject.put(property.getName(),
  117. encodedPropertyValue);
  118. }
  119. return jsonObject;
  120. } catch (NoDataException e) {
  121. throw new RuntimeException(
  122. "Can not encode " + type.getSignature(), e);
  123. }
  124. } else {
  125. throw new RuntimeException("Can't encode " + value.getClass()
  126. + " without type information");
  127. }
  128. }
  129. }
  130. private static JsonValue encodeVariableChange(UidlValue uidlValue,
  131. ApplicationConnection connection) {
  132. Object value = uidlValue.getValue();
  133. JsonArray jsonArray = Json.createArray();
  134. String transportType = getTransportType(value);
  135. if (transportType == null) {
  136. /*
  137. * This should not happen unless you try to send an unsupported type
  138. * in a legacy variable change from the client to the server.
  139. */
  140. String valueType = null;
  141. if (value != null) {
  142. valueType = value.getClass().getName();
  143. }
  144. throw new IllegalArgumentException(
  145. "Cannot encode object of type " + valueType);
  146. }
  147. jsonArray.set(0, Json.create(transportType));
  148. jsonArray.set(1, encode(value, null, connection));
  149. return jsonArray;
  150. }
  151. private static JsonValue encodeMap(Map<Object, Object> map, Type type,
  152. ApplicationConnection connection) {
  153. /*
  154. * As we have no info about declared types, we instead select encoding
  155. * scheme based on actual type of first key. We can't do this if there's
  156. * no first key, so instead we send some special value that the
  157. * server-side decoding must check for. (see #8906)
  158. */
  159. if (map.isEmpty()) {
  160. return Json.createArray();
  161. }
  162. Object firstKey = map.keySet().iterator().next();
  163. if (firstKey instanceof String) {
  164. return encodeStringMap(map, type, connection);
  165. } else if (type == null) {
  166. throw new IllegalStateException(
  167. "Only string keys supported for legacy maps");
  168. } else if (firstKey instanceof Connector) {
  169. return encodeConnectorMap(map, type, connection);
  170. } else {
  171. return encodeObjectMap(map, type, connection);
  172. }
  173. }
  174. private static JsonValue encodeChildValue(Object value, Type collectionType,
  175. int typeIndex, ApplicationConnection connection) {
  176. if (collectionType == null) {
  177. return encode(new UidlValue(value), null, connection);
  178. } else {
  179. assert collectionType.getParameterTypes() != null
  180. && collectionType.getParameterTypes().length > typeIndex
  181. && collectionType
  182. .getParameterTypes()[typeIndex] != null : "Proper generics required for encoding child value, assertion failed for "
  183. + collectionType;
  184. Type childType = collectionType.getParameterTypes()[typeIndex];
  185. return encode(value, childType, connection);
  186. }
  187. }
  188. private static JsonArray encodeObjectMap(Map<Object, Object> map, Type type,
  189. ApplicationConnection connection) {
  190. JsonArray keys = Json.createArray();
  191. JsonArray values = Json.createArray();
  192. assert type != null : "Should only be used for non-legacy types";
  193. for (Entry<?, ?> entry : map.entrySet()) {
  194. keys.set(keys.length(),
  195. encodeChildValue(entry.getKey(), type, 0, connection));
  196. values.set(values.length(),
  197. encodeChildValue(entry.getValue(), type, 1, connection));
  198. }
  199. JsonArray keysAndValues = Json.createArray();
  200. keysAndValues.set(0, keys);
  201. keysAndValues.set(1, values);
  202. return keysAndValues;
  203. }
  204. private static JsonValue encodeConnectorMap(Map<Object, Object> map,
  205. Type type, ApplicationConnection connection) {
  206. JsonObject jsonMap = Json.createObject();
  207. for (Entry<?, ?> entry : map.entrySet()) {
  208. Connector connector = (Connector) entry.getKey();
  209. JsonValue encodedValue = encodeChildValue(entry.getValue(), type, 1,
  210. connection);
  211. jsonMap.put(connector.getConnectorId(), encodedValue);
  212. }
  213. return jsonMap;
  214. }
  215. private static JsonValue encodeStringMap(Map<Object, Object> map, Type type,
  216. ApplicationConnection connection) {
  217. JsonObject jsonMap = Json.createObject();
  218. for (Entry<?, ?> entry : map.entrySet()) {
  219. String key = (String) entry.getKey();
  220. Object value = entry.getValue();
  221. jsonMap.put(key, encodeChildValue(value, type, 1, connection));
  222. }
  223. return jsonMap;
  224. }
  225. private static JsonValue encodeEnum(Enum<?> e,
  226. ApplicationConnection connection) {
  227. return Json.create(e.toString());
  228. }
  229. private static JsonValue encodeLegacyObjectArray(Object[] array,
  230. ApplicationConnection connection) {
  231. JsonArray jsonArray = Json.createArray();
  232. for (int i = 0; i < array.length; ++i) {
  233. // TODO handle object graph loops?
  234. Object value = array[i];
  235. jsonArray.set(i, encode(value, null, connection));
  236. }
  237. return jsonArray;
  238. }
  239. private static JsonArray encodeCollection(Collection collection, Type type,
  240. ApplicationConnection connection) {
  241. JsonArray jsonArray = Json.createArray();
  242. int idx = 0;
  243. for (Object o : collection) {
  244. JsonValue encodedObject = encodeChildValue(o, type, 0, connection);
  245. jsonArray.set(idx++, encodedObject);
  246. }
  247. if (collection instanceof Set) {
  248. return jsonArray;
  249. } else if (collection instanceof List) {
  250. return jsonArray;
  251. } else {
  252. throw new RuntimeException("Unsupport collection type: "
  253. + collection.getClass().getName());
  254. }
  255. }
  256. /**
  257. * Returns the transport type for the given value. Only returns a transport
  258. * type for internally handled values.
  259. *
  260. * @param value
  261. * The value that should be transported
  262. * @return One of the JsonEncode.VTYPE_ constants or null if the value
  263. * cannot be transported using an internally handled type.
  264. */
  265. private static String getTransportType(Object value) {
  266. if (value == null) {
  267. return JsonConstants.VTYPE_NULL;
  268. } else if (value instanceof String) {
  269. return JsonConstants.VTYPE_STRING;
  270. } else if (value instanceof Connector) {
  271. return JsonConstants.VTYPE_CONNECTOR;
  272. } else if (value instanceof Boolean) {
  273. return JsonConstants.VTYPE_BOOLEAN;
  274. } else if (value instanceof Integer) {
  275. return JsonConstants.VTYPE_INTEGER;
  276. } else if (value instanceof Float) {
  277. return JsonConstants.VTYPE_FLOAT;
  278. } else if (value instanceof Double) {
  279. return JsonConstants.VTYPE_DOUBLE;
  280. } else if (value instanceof Long) {
  281. return JsonConstants.VTYPE_LONG;
  282. } else if (value instanceof List) {
  283. return JsonConstants.VTYPE_LIST;
  284. } else if (value instanceof Set) {
  285. return JsonConstants.VTYPE_SET;
  286. } else if (value instanceof String[]) {
  287. return JsonConstants.VTYPE_STRINGARRAY;
  288. } else if (value instanceof Object[]) {
  289. return JsonConstants.VTYPE_ARRAY;
  290. } else if (value instanceof Map) {
  291. return JsonConstants.VTYPE_MAP;
  292. } else if (value instanceof Enum<?>) {
  293. // Enum value is processed as a string
  294. return JsonConstants.VTYPE_STRING;
  295. }
  296. return null;
  297. }
  298. }