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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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,
  58. boolean restrictToInternalTypes, 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[]) {
  79. return encodeObjectArray((Object[]) value, restrictToInternalTypes,
  80. connection);
  81. } else if (value instanceof Enum) {
  82. return encodeEnum((Enum<?>) value, connection);
  83. } else if (value instanceof Map) {
  84. return encodeMap((Map) value, restrictToInternalTypes, 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,
  90. restrictToInternalTypes, connection);
  91. } else if (value instanceof UidlValue) {
  92. return encodeVariableChange((UidlValue) value, connection);
  93. } else {
  94. String transportType = getTransportType(value);
  95. if (transportType != null) {
  96. return new JSONString(String.valueOf(value));
  97. } else {
  98. // Try to find a generated serializer object, class name is the
  99. // type
  100. Type type = new Type(value.getClass());
  101. JSONSerializer<Object> serializer = (JSONSerializer<Object>) type
  102. .findSerializer();
  103. if (serializer != null) {
  104. return serializer.serialize(value, connection);
  105. } else {
  106. try {
  107. Collection<Property> properties = type.getProperties();
  108. JSONObject jsonObject = new JSONObject();
  109. for (Property property : properties) {
  110. Object propertyValue = property.getValue(value);
  111. JSONValue encodedPropertyValue = encode(
  112. propertyValue, restrictToInternalTypes,
  113. connection);
  114. jsonObject.put(property.getName(),
  115. encodedPropertyValue);
  116. }
  117. return jsonObject;
  118. } catch (NoDataException e) {
  119. throw new RuntimeException("Can not encode "
  120. + type.getSignature(), e);
  121. }
  122. }
  123. }
  124. }
  125. }
  126. private static JSONValue encodeVariableChange(UidlValue uidlValue,
  127. ApplicationConnection connection) {
  128. Object value = uidlValue.getValue();
  129. JSONArray jsonArray = new JSONArray();
  130. jsonArray.set(0, new JSONString(getTransportType(value)));
  131. jsonArray.set(1, encode(value, true, connection));
  132. return jsonArray;
  133. }
  134. private static JSONValue encodeMap(Map<Object, Object> map,
  135. boolean restrictToInternalTypes, ApplicationConnection connection) {
  136. /*
  137. * As we have no info about declared types, we instead select encoding
  138. * scheme based on actual type of first key. We can't do this if there's
  139. * no first key, so instead we send some special value that the
  140. * server-side decoding must check for. (see #8906)
  141. */
  142. if (map.isEmpty()) {
  143. return new JSONArray();
  144. }
  145. Object firstKey = map.keySet().iterator().next();
  146. if (firstKey instanceof String) {
  147. return encodeStringMap(map, restrictToInternalTypes, connection);
  148. } else if (restrictToInternalTypes) {
  149. throw new IllegalStateException(
  150. "Only string keys supported for legacy maps");
  151. } else if (firstKey instanceof Connector) {
  152. return encodeConenctorMap(map, connection);
  153. } else {
  154. return encodeObjectMap(map, connection);
  155. }
  156. }
  157. private static JSONValue encodeObjectMap(Map<Object, Object> map,
  158. ApplicationConnection connection) {
  159. JSONArray keys = new JSONArray();
  160. JSONArray values = new JSONArray();
  161. for (Entry<?, ?> entry : map.entrySet()) {
  162. // restrictToInternalTypes always false if we end up here
  163. keys.set(keys.size(), encode(entry.getKey(), false, connection));
  164. values.set(values.size(),
  165. encode(entry.getValue(), false, connection));
  166. }
  167. JSONArray keysAndValues = new JSONArray();
  168. keysAndValues.set(0, keys);
  169. keysAndValues.set(1, values);
  170. return keysAndValues;
  171. }
  172. private static JSONValue encodeConenctorMap(Map<Object, Object> map,
  173. ApplicationConnection connection) {
  174. JSONObject jsonMap = new JSONObject();
  175. for (Entry<?, ?> entry : map.entrySet()) {
  176. Connector connector = (Connector) entry.getKey();
  177. // restrictToInternalTypes always false if we end up here
  178. JSONValue encodedValue = encode(entry.getValue(), false, connection);
  179. jsonMap.put(connector.getConnectorId(), encodedValue);
  180. }
  181. return jsonMap;
  182. }
  183. private static JSONValue encodeStringMap(Map<Object, Object> map,
  184. boolean restrictToInternalTypes, ApplicationConnection connection) {
  185. JSONObject jsonMap = new JSONObject();
  186. for (Entry<?, ?> entry : map.entrySet()) {
  187. String key = (String) entry.getKey();
  188. Object value = entry.getValue();
  189. if (restrictToInternalTypes) {
  190. value = new UidlValue(value);
  191. }
  192. JSONValue encodedValue = encode(value, restrictToInternalTypes,
  193. connection);
  194. jsonMap.put(key, encodedValue);
  195. }
  196. return jsonMap;
  197. }
  198. private static JSONValue encodeEnum(Enum<?> e,
  199. ApplicationConnection connection) {
  200. return new JSONString(e.toString());
  201. }
  202. private static JSONValue encodeObjectArray(Object[] array,
  203. boolean restrictToInternalTypes, ApplicationConnection connection) {
  204. JSONArray jsonArray = new JSONArray();
  205. for (int i = 0; i < array.length; ++i) {
  206. // TODO handle object graph loops?
  207. Object value = array[i];
  208. if (restrictToInternalTypes) {
  209. value = new UidlValue(value);
  210. }
  211. jsonArray
  212. .set(i, encode(value, restrictToInternalTypes, connection));
  213. }
  214. return jsonArray;
  215. }
  216. private static JSONValue encodeCollection(Collection collection,
  217. boolean restrictToInternalTypes, ApplicationConnection connection) {
  218. JSONArray jsonArray = new JSONArray();
  219. int idx = 0;
  220. for (Object o : collection) {
  221. JSONValue encodedObject = encode(o, restrictToInternalTypes,
  222. connection);
  223. jsonArray.set(idx++, encodedObject);
  224. }
  225. if (collection instanceof Set) {
  226. return jsonArray;
  227. } else if (collection instanceof List) {
  228. return jsonArray;
  229. } else {
  230. throw new RuntimeException("Unsupport collection type: "
  231. + collection.getClass().getName());
  232. }
  233. }
  234. /**
  235. * Returns the transport type for the given value. Only returns a transport
  236. * type for internally handled values.
  237. *
  238. * @param value
  239. * The value that should be transported
  240. * @return One of the JsonEncode.VTYPE_ constants or null if the value
  241. * cannot be transported using an internally handled type.
  242. */
  243. private static String getTransportType(Object value) {
  244. if (value == null) {
  245. return JsonConstants.VTYPE_NULL;
  246. } else if (value instanceof String) {
  247. return JsonConstants.VTYPE_STRING;
  248. } else if (value instanceof Connector) {
  249. return JsonConstants.VTYPE_CONNECTOR;
  250. } else if (value instanceof Boolean) {
  251. return JsonConstants.VTYPE_BOOLEAN;
  252. } else if (value instanceof Integer) {
  253. return JsonConstants.VTYPE_INTEGER;
  254. } else if (value instanceof Float) {
  255. return JsonConstants.VTYPE_FLOAT;
  256. } else if (value instanceof Double) {
  257. return JsonConstants.VTYPE_DOUBLE;
  258. } else if (value instanceof Long) {
  259. return JsonConstants.VTYPE_LONG;
  260. } else if (value instanceof List) {
  261. return JsonConstants.VTYPE_LIST;
  262. } else if (value instanceof Set) {
  263. return JsonConstants.VTYPE_SET;
  264. } else if (value instanceof String[]) {
  265. return JsonConstants.VTYPE_STRINGARRAY;
  266. } else if (value instanceof Object[]) {
  267. return JsonConstants.VTYPE_ARRAY;
  268. } else if (value instanceof Map) {
  269. return JsonConstants.VTYPE_MAP;
  270. } else if (value instanceof Enum<?>) {
  271. // Enum value is processed as a string
  272. return JsonConstants.VTYPE_STRING;
  273. }
  274. return null;
  275. }
  276. }