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

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