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

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