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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.client.communication;
  5. import java.util.Collection;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import java.util.Set;
  10. import com.google.gwt.json.client.JSONArray;
  11. import com.google.gwt.json.client.JSONBoolean;
  12. import com.google.gwt.json.client.JSONNull;
  13. import com.google.gwt.json.client.JSONObject;
  14. import com.google.gwt.json.client.JSONString;
  15. import com.google.gwt.json.client.JSONValue;
  16. import com.vaadin.terminal.gwt.client.ApplicationConnection;
  17. import com.vaadin.terminal.gwt.client.Connector;
  18. import com.vaadin.terminal.gwt.client.ConnectorMap;
  19. /**
  20. * Encoder for converting RPC parameters and other values to JSON for transfer
  21. * between the client and the server.
  22. *
  23. * Currently, basic data types as well as Map, String[] and Object[] are
  24. * supported, where maps and Object[] can contain other supported data types.
  25. *
  26. * TODO extensible type support
  27. *
  28. * @since 7.0
  29. */
  30. public class JsonEncoder {
  31. public static final String VTYPE_CONNECTOR = "c";
  32. public static final String VTYPE_BOOLEAN = "b";
  33. public static final String VTYPE_DOUBLE = "d";
  34. public static final String VTYPE_FLOAT = "f";
  35. public static final String VTYPE_LONG = "l";
  36. public static final String VTYPE_INTEGER = "i";
  37. public static final String VTYPE_STRING = "s";
  38. public static final String VTYPE_ARRAY = "a";
  39. public static final String VTYPE_STRINGARRAY = "S";
  40. public static final String VTYPE_MAP = "m";
  41. public static final String VTYPE_LIST = "L";
  42. public static final String VTYPE_SET = "q";
  43. public static final String VTYPE_NULL = "n";
  44. /**
  45. * Encode a value to a JSON representation for transport from the client to
  46. * the server.
  47. *
  48. * @param value
  49. * value to convert
  50. * @param connectorMap
  51. * mapper from connectors to connector IDs
  52. * @param connection
  53. * @return JSON representation of the value
  54. */
  55. public static JSONValue encode(Object value,
  56. boolean restrictToInternalTypes, ConnectorMap connectorMap,
  57. ApplicationConnection connection) {
  58. if (null == value) {
  59. return JSONNull.getInstance();
  60. } else if (value instanceof String[]) {
  61. String[] array = (String[]) value;
  62. JSONArray jsonArray = new JSONArray();
  63. for (int i = 0; i < array.length; ++i) {
  64. jsonArray.set(i, new JSONString(array[i]));
  65. }
  66. return jsonArray;
  67. } else if (value instanceof String) {
  68. return new JSONString((String) value);
  69. } else if (value instanceof Boolean) {
  70. return JSONBoolean.getInstance((Boolean) value);
  71. } else if (value instanceof Object[]) {
  72. return encodeObjectArray((Object[]) value, restrictToInternalTypes,
  73. connectorMap, connection);
  74. } else if (value instanceof Enum) {
  75. if (restrictToInternalTypes) {
  76. // Enums are encoded as strings in Vaadin 6 so we still do that
  77. // for backwards copmatibility.
  78. return encode(new UidlValue(value.toString()),
  79. restrictToInternalTypes, connectorMap, connection);
  80. } else {
  81. Enum e = (Enum) value;
  82. return encodeEnum(e, connectorMap, connection);
  83. }
  84. } else if (value instanceof Map) {
  85. return encodeMap((Map) value, restrictToInternalTypes,
  86. connectorMap, connection);
  87. } else if (value instanceof Connector) {
  88. Connector connector = (Connector) value;
  89. return new JSONString(connector.getConnectorId());
  90. } else if (value instanceof Collection) {
  91. return encodeCollection((Collection) value,
  92. restrictToInternalTypes, connectorMap, connection);
  93. } else if (value instanceof UidlValue) {
  94. return encodeVariableChange((UidlValue) value, connectorMap,
  95. connection);
  96. } else {
  97. String transportType = getTransportType(value);
  98. if (transportType != null) {
  99. return new JSONString(String.valueOf(value));
  100. } else {
  101. // Try to find a generated serializer object, class name is the
  102. // type
  103. transportType = value.getClass().getName();
  104. JSONSerializer serializer = connection.getSerializerMap()
  105. .getSerializer(transportType);
  106. // TODO handle case with no serializer found
  107. return serializer.serialize(value, connectorMap, connection);
  108. }
  109. }
  110. }
  111. private static JSONValue encodeVariableChange(UidlValue uidlValue,
  112. ConnectorMap connectorMap, ApplicationConnection connection) {
  113. Object value = uidlValue.getValue();
  114. JSONArray jsonArray = new JSONArray();
  115. jsonArray.set(0, new JSONString(getTransportType(value)));
  116. jsonArray.set(1, encode(value, true, connectorMap, connection));
  117. return jsonArray;
  118. }
  119. private static JSONValue encodeMap(Map<Object, Object> map,
  120. boolean restrictToInternalTypes, ConnectorMap connectorMap,
  121. ApplicationConnection connection) {
  122. /*
  123. * As we have no info about declared types, we instead select encoding
  124. * scheme based on actual type of first key. We can't do this if there's
  125. * no first key, so instead we send some special value that the
  126. * server-side decoding must check for. (see #8906)
  127. */
  128. if (map.isEmpty()) {
  129. return new JSONArray();
  130. }
  131. Object firstKey = map.keySet().iterator().next();
  132. if (firstKey instanceof String) {
  133. return encodeStringMap(map, restrictToInternalTypes, connectorMap,
  134. connection);
  135. } else if (restrictToInternalTypes) {
  136. throw new IllegalStateException(
  137. "Only string keys supported for legacy maps");
  138. } else if (firstKey instanceof Connector) {
  139. return encodeConenctorMap(map, connectorMap, connection);
  140. } else {
  141. return encodeObjectMap(map, connectorMap, connection);
  142. }
  143. }
  144. private static JSONValue encodeObjectMap(Map<Object, Object> map,
  145. ConnectorMap connectorMap, ApplicationConnection connection) {
  146. JSONArray keys = new JSONArray();
  147. JSONArray values = new JSONArray();
  148. for (Entry<?, ?> entry : map.entrySet()) {
  149. // restrictToInternalTypes always false if we end up here
  150. keys.set(keys.size(),
  151. encode(entry.getKey(), false, connectorMap, connection));
  152. values.set(values.size(),
  153. encode(entry.getValue(), false, connectorMap, connection));
  154. }
  155. JSONArray keysAndValues = new JSONArray();
  156. keysAndValues.set(0, keys);
  157. keysAndValues.set(1, values);
  158. return keysAndValues;
  159. }
  160. private static JSONValue encodeConenctorMap(Map<Object, Object> map,
  161. ConnectorMap connectorMap, ApplicationConnection connection) {
  162. JSONObject jsonMap = new JSONObject();
  163. for (Entry<?, ?> entry : map.entrySet()) {
  164. Connector connector = (Connector) entry.getKey();
  165. // restrictToInternalTypes always false if we end up here
  166. JSONValue encodedValue = encode(entry.getValue(), false,
  167. connectorMap, connection);
  168. jsonMap.put(connector.getConnectorId(), encodedValue);
  169. }
  170. return jsonMap;
  171. }
  172. private static JSONValue encodeStringMap(Map<Object, Object> map,
  173. boolean restrictToInternalTypes, ConnectorMap connectorMap,
  174. ApplicationConnection connection) {
  175. JSONObject jsonMap = new JSONObject();
  176. for (Entry<?, ?> entry : map.entrySet()) {
  177. String key = (String) entry.getKey();
  178. Object value = entry.getValue();
  179. if (restrictToInternalTypes) {
  180. value = new UidlValue(value);
  181. }
  182. JSONValue encodedValue = encode(value, restrictToInternalTypes,
  183. connectorMap, connection);
  184. jsonMap.put(key, encodedValue);
  185. }
  186. return jsonMap;
  187. }
  188. private static JSONValue encodeEnum(Enum e, ConnectorMap connectorMap,
  189. ApplicationConnection connection) {
  190. return new JSONString(e.toString());
  191. }
  192. private static JSONValue encodeObjectArray(Object[] array,
  193. boolean restrictToInternalTypes, ConnectorMap connectorMap,
  194. ApplicationConnection connection) {
  195. JSONArray jsonArray = new JSONArray();
  196. for (int i = 0; i < array.length; ++i) {
  197. // TODO handle object graph loops?
  198. Object value = array[i];
  199. if (restrictToInternalTypes) {
  200. value = new UidlValue(value);
  201. }
  202. jsonArray.set(
  203. i,
  204. encode(value, restrictToInternalTypes, connectorMap,
  205. connection));
  206. }
  207. return jsonArray;
  208. }
  209. private static JSONValue encodeCollection(Collection collection,
  210. boolean restrictToInternalTypes, ConnectorMap connectorMap,
  211. ApplicationConnection connection) {
  212. JSONArray jsonArray = new JSONArray();
  213. int idx = 0;
  214. for (Object o : collection) {
  215. JSONValue encodedObject = encode(o, restrictToInternalTypes,
  216. connectorMap, connection);
  217. jsonArray.set(idx++, encodedObject);
  218. }
  219. if (collection instanceof Set) {
  220. return jsonArray;
  221. } else if (collection instanceof List) {
  222. return jsonArray;
  223. } else {
  224. throw new RuntimeException("Unsupport collection type: "
  225. + collection.getClass().getName());
  226. }
  227. }
  228. /**
  229. * Returns the transport type for the given value. Only returns a transport
  230. * type for internally handled values.
  231. *
  232. * @param value
  233. * The value that should be transported
  234. * @return One of the JsonEncode.VTYPE_ constants or null if the value
  235. * cannot be transported using an internally handled type.
  236. */
  237. private static String getTransportType(Object value) {
  238. if (value == null) {
  239. return VTYPE_NULL;
  240. } else if (value instanceof String) {
  241. return VTYPE_STRING;
  242. } else if (value instanceof Connector) {
  243. return VTYPE_CONNECTOR;
  244. } else if (value instanceof Boolean) {
  245. return VTYPE_BOOLEAN;
  246. } else if (value instanceof Integer) {
  247. return VTYPE_INTEGER;
  248. } else if (value instanceof Float) {
  249. return VTYPE_FLOAT;
  250. } else if (value instanceof Double) {
  251. return VTYPE_DOUBLE;
  252. } else if (value instanceof Long) {
  253. return VTYPE_LONG;
  254. } else if (value instanceof List) {
  255. return VTYPE_LIST;
  256. } else if (value instanceof Set) {
  257. return VTYPE_SET;
  258. } else if (value instanceof String[]) {
  259. return VTYPE_STRINGARRAY;
  260. } else if (value instanceof Object[]) {
  261. return VTYPE_ARRAY;
  262. } else if (value instanceof Map) {
  263. return VTYPE_MAP;
  264. }
  265. return null;
  266. }
  267. }