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.

JsonDecoder.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. /*
  2. * Copyright 2000-2014 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.ArrayList;
  18. import java.util.Collection;
  19. import java.util.HashMap;
  20. import java.util.HashSet;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import com.vaadin.client.ApplicationConnection;
  25. import com.vaadin.client.ConnectorMap;
  26. import com.vaadin.client.FastStringSet;
  27. import com.vaadin.client.JsArrayObject;
  28. import com.vaadin.client.Profiler;
  29. import com.vaadin.client.metadata.NoDataException;
  30. import com.vaadin.client.metadata.Property;
  31. import com.vaadin.client.metadata.Type;
  32. import com.vaadin.shared.Connector;
  33. import elemental.json.JsonArray;
  34. import elemental.json.JsonObject;
  35. import elemental.json.JsonType;
  36. import elemental.json.JsonValue;
  37. /**
  38. * Client side decoder for decodeing shared state and other values from JSON
  39. * received from the server.
  40. *
  41. * Currently, basic data types as well as Map, String[] and Object[] are
  42. * supported, where maps and Object[] can contain other supported data types.
  43. *
  44. * TODO extensible type support
  45. *
  46. * @since 7.0
  47. */
  48. public class JsonDecoder {
  49. private static final FastStringSet decodedWithoutReference = FastStringSet
  50. .create();
  51. static {
  52. decodedWithoutReference.add(String.class.getName());
  53. decodedWithoutReference.add(Boolean.class.getName());
  54. decodedWithoutReference.add(Byte.class.getName());
  55. decodedWithoutReference.add(Character.class.getName());
  56. decodedWithoutReference.add(Short.class.getName());
  57. decodedWithoutReference.add(Integer.class.getName());
  58. decodedWithoutReference.add(Long.class.getName());
  59. decodedWithoutReference.add(Float.class.getName());
  60. decodedWithoutReference.add(Double.class.getName());
  61. decodedWithoutReference.add(Connector.class.getName());
  62. decodedWithoutReference.add(Map.class.getName());
  63. decodedWithoutReference.add(List.class.getName());
  64. decodedWithoutReference.add(Set.class.getName());
  65. }
  66. /**
  67. * Decode a JSON array with two elements (type and value) into a client-side
  68. * type, recursively if necessary.
  69. *
  70. * @param jsonValue
  71. * JSON value with encoded data
  72. * @param connection
  73. * reference to the current ApplicationConnection
  74. * @return decoded value (does not contain JSON types)
  75. */
  76. public static Object decodeValue(Type type, JsonValue jsonValue,
  77. Object target, ApplicationConnection connection) {
  78. String baseTypeName = type.getBaseTypeName();
  79. if (baseTypeName.startsWith("elemental.json.Json")) {
  80. return jsonValue;
  81. }
  82. // Null is null, regardless of type (except JSON)
  83. if (jsonValue.getType() == JsonType.NULL) {
  84. return null;
  85. }
  86. if (Map.class.getName().equals(baseTypeName)
  87. || HashMap.class.getName().equals(baseTypeName)) {
  88. return decodeMap(type, jsonValue, connection);
  89. } else if (List.class.getName().equals(baseTypeName)
  90. || ArrayList.class.getName().equals(baseTypeName)) {
  91. assert jsonValue.getType() == JsonType.ARRAY;
  92. return decodeList(type, (JsonArray) jsonValue, connection);
  93. } else if (Set.class.getName().equals(baseTypeName)) {
  94. assert jsonValue.getType() == JsonType.ARRAY;
  95. return decodeSet(type, (JsonArray) jsonValue, connection);
  96. } else if (String.class.getName().equals(baseTypeName)) {
  97. return jsonValue.asString();
  98. } else if (Integer.class.getName().equals(baseTypeName)) {
  99. return Integer.valueOf((int) jsonValue.asNumber());
  100. } else if (Long.class.getName().equals(baseTypeName)) {
  101. return Long.valueOf((long) jsonValue.asNumber());
  102. } else if (Float.class.getName().equals(baseTypeName)) {
  103. return Float.valueOf((float) jsonValue.asNumber());
  104. } else if (Double.class.getName().equals(baseTypeName)) {
  105. return Double.valueOf(jsonValue.asNumber());
  106. } else if (Boolean.class.getName().equals(baseTypeName)) {
  107. return Boolean.valueOf(jsonValue.asString());
  108. } else if (Byte.class.getName().equals(baseTypeName)) {
  109. return Byte.valueOf((byte) jsonValue.asNumber());
  110. } else if (Character.class.getName().equals(baseTypeName)) {
  111. return Character.valueOf(jsonValue.asString().charAt(0));
  112. } else if (Connector.class.getName().equals(baseTypeName)) {
  113. return ConnectorMap.get(connection).getConnector(
  114. jsonValue.asString());
  115. } else {
  116. return decodeObject(type, jsonValue, target, connection);
  117. }
  118. }
  119. private static Object decodeObject(Type type, JsonValue jsonValue,
  120. Object target, ApplicationConnection connection) {
  121. Profiler.enter("JsonDecoder.decodeObject");
  122. JSONSerializer<Object> serializer = (JSONSerializer<Object>) type
  123. .findSerializer();
  124. if (serializer != null) {
  125. if (target != null && serializer instanceof DiffJSONSerializer<?>) {
  126. DiffJSONSerializer<Object> diffSerializer = (DiffJSONSerializer<Object>) serializer;
  127. diffSerializer.update(target, type, jsonValue, connection);
  128. Profiler.leave("JsonDecoder.decodeObject");
  129. return target;
  130. } else {
  131. Object object = serializer.deserialize(type, jsonValue,
  132. connection);
  133. Profiler.leave("JsonDecoder.decodeObject");
  134. return object;
  135. }
  136. } else {
  137. try {
  138. Profiler.enter("JsonDecoder.decodeObject meta data processing");
  139. JsArrayObject<Property> properties = type
  140. .getPropertiesAsArray();
  141. if (target == null) {
  142. target = type.createInstance();
  143. }
  144. JsonObject jsonObject = (JsonObject) jsonValue;
  145. int size = properties.size();
  146. for (int i = 0; i < size; i++) {
  147. Property property = properties.get(i);
  148. if (!jsonObject.hasKey(property.getName())) {
  149. continue;
  150. }
  151. Type propertyType = property.getType();
  152. Object propertyReference;
  153. if (needsReferenceValue(propertyType)) {
  154. propertyReference = property.getValue(target);
  155. } else {
  156. propertyReference = null;
  157. }
  158. Profiler.leave("JsonDecoder.decodeObject meta data processing");
  159. JsonValue encodedPropertyValue = jsonObject.get(property
  160. .getName());
  161. Object decodedValue = decodeValue(propertyType,
  162. encodedPropertyValue, propertyReference, connection);
  163. Profiler.enter("JsonDecoder.decodeObject meta data processing");
  164. property.setValue(target, decodedValue);
  165. }
  166. Profiler.leave("JsonDecoder.decodeObject meta data processing");
  167. Profiler.leave("JsonDecoder.decodeObject");
  168. return target;
  169. } catch (NoDataException e) {
  170. Profiler.leave("JsonDecoder.decodeObject meta data processing");
  171. Profiler.leave("JsonDecoder.decodeObject");
  172. throw new RuntimeException("Can not deserialize "
  173. + type.getSignature(), e);
  174. }
  175. }
  176. }
  177. private static boolean needsReferenceValue(Type type) {
  178. return !decodedWithoutReference.contains(type.getBaseTypeName());
  179. }
  180. private static Map<Object, Object> decodeMap(Type type, JsonValue jsonMap,
  181. ApplicationConnection connection) {
  182. // Client -> server encodes empty map as an empty array because of
  183. // #8906. Do the same for server -> client to maintain symmetry.
  184. if (jsonMap.getType() == JsonType.ARRAY) {
  185. JsonArray array = (JsonArray) jsonMap;
  186. if (array.length() == 0) {
  187. return new HashMap<Object, Object>();
  188. }
  189. }
  190. Type keyType = type.getParameterTypes()[0];
  191. Type valueType = type.getParameterTypes()[1];
  192. if (keyType.getBaseTypeName().equals(String.class.getName())) {
  193. assert jsonMap.getType() == JsonType.OBJECT;
  194. return decodeStringMap(valueType, (JsonObject) jsonMap, connection);
  195. } else if (keyType.getBaseTypeName().equals(Connector.class.getName())) {
  196. assert jsonMap.getType() == JsonType.OBJECT;
  197. return decodeConnectorMap(valueType, (JsonObject) jsonMap,
  198. connection);
  199. } else {
  200. assert jsonMap.getType() == JsonType.ARRAY;
  201. return decodeObjectMap(keyType, valueType, (JsonArray) jsonMap,
  202. connection);
  203. }
  204. }
  205. private static Map<Object, Object> decodeObjectMap(Type keyType,
  206. Type valueType, JsonArray jsonValue,
  207. ApplicationConnection connection) {
  208. Map<Object, Object> map = new HashMap<Object, Object>();
  209. JsonArray keys = jsonValue.get(0);
  210. JsonArray values = jsonValue.get(1);
  211. assert (keys.length() == values.length());
  212. for (int i = 0; i < keys.length(); i++) {
  213. Object decodedKey = decodeValue(keyType, keys.get(i), null,
  214. connection);
  215. Object decodedValue = decodeValue(valueType, values.get(i), null,
  216. connection);
  217. map.put(decodedKey, decodedValue);
  218. }
  219. return map;
  220. }
  221. private static Map<Object, Object> decodeConnectorMap(Type valueType,
  222. JsonObject jsonMap, ApplicationConnection connection) {
  223. Map<Object, Object> map = new HashMap<Object, Object>();
  224. ConnectorMap connectorMap = ConnectorMap.get(connection);
  225. for (String connectorId : jsonMap.keys()) {
  226. Object value = decodeValue(valueType, jsonMap.get(connectorId),
  227. null, connection);
  228. map.put(connectorMap.getConnector(connectorId), value);
  229. }
  230. return map;
  231. }
  232. private static Map<Object, Object> decodeStringMap(Type valueType,
  233. JsonObject jsonMap, ApplicationConnection connection) {
  234. Map<Object, Object> map = new HashMap<Object, Object>();
  235. for (String key : jsonMap.keys()) {
  236. Object value = decodeValue(valueType, jsonMap.get(key), null,
  237. connection);
  238. map.put(key, value);
  239. }
  240. return map;
  241. }
  242. private static List<Object> decodeList(Type type, JsonArray jsonArray,
  243. ApplicationConnection connection) {
  244. List<Object> tokens = new ArrayList<Object>();
  245. decodeIntoCollection(type.getParameterTypes()[0], jsonArray,
  246. connection, tokens);
  247. return tokens;
  248. }
  249. private static Set<Object> decodeSet(Type type, JsonArray jsonArray,
  250. ApplicationConnection connection) {
  251. Set<Object> tokens = new HashSet<Object>();
  252. decodeIntoCollection(type.getParameterTypes()[0], jsonArray,
  253. connection, tokens);
  254. return tokens;
  255. }
  256. private static void decodeIntoCollection(Type childType,
  257. JsonArray jsonArray, ApplicationConnection connection,
  258. Collection<Object> tokens) {
  259. for (int i = 0; i < jsonArray.length(); ++i) {
  260. // each entry always has two elements: type and value
  261. JsonValue entryValue = jsonArray.get(i);
  262. tokens.add(decodeValue(childType, entryValue, null, connection));
  263. }
  264. }
  265. /**
  266. * Called by generated deserialization code to treat a generic object as a
  267. * JsonValue. This is needed because GWT refuses to directly cast String
  268. * typed as Object into a JSO.
  269. */
  270. public static native <T extends JsonValue> T obj2jso(Object object)
  271. /*-{
  272. return object;
  273. }-*/;
  274. }