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

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