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.

JsonCodec.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.server;
  5. import java.beans.IntrospectionException;
  6. import java.beans.Introspector;
  7. import java.beans.PropertyDescriptor;
  8. import java.io.Serializable;
  9. import java.lang.reflect.InvocationTargetException;
  10. import java.lang.reflect.Method;
  11. import java.util.ArrayList;
  12. import java.util.HashMap;
  13. import java.util.Iterator;
  14. import java.util.List;
  15. import java.util.Map;
  16. import com.vaadin.external.json.JSONArray;
  17. import com.vaadin.external.json.JSONException;
  18. import com.vaadin.external.json.JSONObject;
  19. import com.vaadin.terminal.Paintable;
  20. import com.vaadin.terminal.gwt.client.communication.JsonEncoder;
  21. /**
  22. * Decoder for converting RPC parameters and other values from JSON in transfer
  23. * between the client and the server and vice versa.
  24. *
  25. * @since 7.0
  26. */
  27. public class JsonCodec implements Serializable {
  28. private static Map<Class<?>, String> typeToTransportType = new HashMap<Class<?>, String>();
  29. static {
  30. registerType(String.class, JsonEncoder.VTYPE_STRING);
  31. registerType(Paintable.class, JsonEncoder.VTYPE_PAINTABLE);
  32. registerType(Boolean.class, JsonEncoder.VTYPE_BOOLEAN);
  33. registerType(Integer.class, JsonEncoder.VTYPE_INTEGER);
  34. registerType(Float.class, JsonEncoder.VTYPE_FLOAT);
  35. registerType(Double.class, JsonEncoder.VTYPE_DOUBLE);
  36. registerType(Long.class, JsonEncoder.VTYPE_LONG);
  37. // transported as string representation
  38. registerType(Enum.class, JsonEncoder.VTYPE_STRING);
  39. registerType(String[].class, JsonEncoder.VTYPE_STRINGARRAY);
  40. registerType(Object[].class, JsonEncoder.VTYPE_ARRAY);
  41. registerType(Map.class, JsonEncoder.VTYPE_MAP);
  42. }
  43. private static void registerType(Class<?> type, String transportType) {
  44. typeToTransportType.put(type, transportType);
  45. }
  46. /**
  47. * Convert a JSON array with two elements (type and value) into a
  48. * server-side type, recursively if necessary.
  49. *
  50. * @param value
  51. * JSON array with two elements
  52. * @param idMapper
  53. * mapper between paintable ID and {@link Paintable} objects
  54. * @return converted value (does not contain JSON types)
  55. * @throws JSONException
  56. * if the conversion fails
  57. */
  58. public static Object decode(JSONArray value, PaintableIdMapper idMapper)
  59. throws JSONException {
  60. return convertVariableValue(value.getString(0), value.get(1), idMapper);
  61. }
  62. private static Object convertVariableValue(String variableType,
  63. Object value, PaintableIdMapper idMapper) throws JSONException {
  64. Object val = null;
  65. // TODO type checks etc.
  66. if (JsonEncoder.VTYPE_ARRAY.equals(variableType)) {
  67. val = convertArray((JSONArray) value, idMapper);
  68. } else if (JsonEncoder.VTYPE_MAP.equals(variableType)) {
  69. val = convertMap((JSONObject) value, idMapper);
  70. } else if (JsonEncoder.VTYPE_STRINGARRAY.equals(variableType)) {
  71. val = convertStringArray((JSONArray) value);
  72. } else if (JsonEncoder.VTYPE_STRING.equals(variableType)) {
  73. val = value;
  74. } else if (JsonEncoder.VTYPE_INTEGER.equals(variableType)) {
  75. // TODO handle properly
  76. val = Integer.valueOf(String.valueOf(value));
  77. } else if (JsonEncoder.VTYPE_LONG.equals(variableType)) {
  78. // TODO handle properly
  79. val = Long.valueOf(String.valueOf(value));
  80. } else if (JsonEncoder.VTYPE_FLOAT.equals(variableType)) {
  81. // TODO handle properly
  82. val = Float.valueOf(String.valueOf(value));
  83. } else if (JsonEncoder.VTYPE_DOUBLE.equals(variableType)) {
  84. // TODO handle properly
  85. val = Double.valueOf(String.valueOf(value));
  86. } else if (JsonEncoder.VTYPE_BOOLEAN.equals(variableType)) {
  87. // TODO handle properly
  88. val = Boolean.valueOf(String.valueOf(value));
  89. } else if (JsonEncoder.VTYPE_PAINTABLE.equals(variableType)) {
  90. // TODO handle properly
  91. val = idMapper.getPaintable(String.valueOf(value));
  92. } else {
  93. // Try to decode object using fields
  94. return decodeObject(variableType, (JSONObject) value, idMapper);
  95. }
  96. return val;
  97. }
  98. private static Object convertMap(JSONObject jsonMap,
  99. PaintableIdMapper idMapper) throws JSONException {
  100. HashMap<String, Object> map = new HashMap<String, Object>();
  101. Iterator<String> it = jsonMap.keys();
  102. while (it.hasNext()) {
  103. String key = it.next();
  104. map.put(key, decode(jsonMap.getJSONArray(key), idMapper));
  105. }
  106. return map;
  107. }
  108. private static String[] convertStringArray(JSONArray jsonArray)
  109. throws JSONException {
  110. int length = jsonArray.length();
  111. List<String> tokens = new ArrayList<String>(length);
  112. for (int i = 0; i < length; ++i) {
  113. tokens.add(jsonArray.getString(i));
  114. }
  115. return tokens.toArray(new String[tokens.size()]);
  116. }
  117. private static Object convertArray(JSONArray jsonArray,
  118. PaintableIdMapper idMapper) throws JSONException {
  119. List<Object> tokens = new ArrayList<Object>();
  120. for (int i = 0; i < jsonArray.length(); ++i) {
  121. // each entry always has two elements: type and value
  122. JSONArray entryArray = jsonArray.getJSONArray(i);
  123. tokens.add(decode(entryArray, idMapper));
  124. }
  125. return tokens.toArray(new Object[tokens.size()]);
  126. }
  127. /**
  128. * Encode a value to a JSON representation for transport from the server to
  129. * the client.
  130. *
  131. * @param value
  132. * value to convert
  133. * @param idMapper
  134. * mapper between paintable ID and {@link Paintable} objects
  135. * @return JSON representation of the value
  136. * @throws JSONException
  137. * if encoding a value fails (e.g. NaN or infinite number)
  138. */
  139. public static JSONArray encode(Object value, PaintableIdMapper idMapper)
  140. throws JSONException {
  141. return encode(value, null, idMapper);
  142. }
  143. public static JSONArray encode(Object value, Class<?> valueType,
  144. PaintableIdMapper idMapper) throws JSONException {
  145. if (null == value) {
  146. // TODO as undefined type?
  147. return combineTypeAndValue(JsonEncoder.VTYPE_UNDEFINED,
  148. JSONObject.NULL);
  149. } else if (value instanceof String[]) {
  150. String[] array = (String[]) value;
  151. JSONArray jsonArray = new JSONArray();
  152. for (int i = 0; i < array.length; ++i) {
  153. jsonArray.put(array[i]);
  154. }
  155. return combineTypeAndValue(JsonEncoder.VTYPE_STRINGARRAY, jsonArray);
  156. } else if (value instanceof String) {
  157. return combineTypeAndValue(JsonEncoder.VTYPE_STRING, value);
  158. } else if (value instanceof Boolean) {
  159. return combineTypeAndValue(JsonEncoder.VTYPE_BOOLEAN, value);
  160. } else if (value instanceof Number) {
  161. return combineTypeAndValue(getTransportType(value), value);
  162. } else if (value instanceof Object[]) {
  163. Object[] array = (Object[]) value;
  164. JSONArray jsonArray = encodeArrayContents(array, idMapper);
  165. return combineTypeAndValue(JsonEncoder.VTYPE_ARRAY, jsonArray);
  166. } else if (value instanceof Map) {
  167. Map<String, Object> map = (Map<String, Object>) value;
  168. JSONObject jsonMap = encodeMapContents(map, idMapper);
  169. return combineTypeAndValue(JsonEncoder.VTYPE_MAP, jsonMap);
  170. } else if (value instanceof Paintable) {
  171. Paintable paintable = (Paintable) value;
  172. return combineTypeAndValue(JsonEncoder.VTYPE_PAINTABLE,
  173. idMapper.getPaintableId(paintable));
  174. } else if (getTransportType(value) != JsonEncoder.VTYPE_UNDEFINED) {
  175. return combineTypeAndValue(getTransportType(value),
  176. String.valueOf(value));
  177. } else {
  178. // Any object that we do not know how to encode we encode by looping
  179. // through fields
  180. if (valueType == null) {
  181. valueType = value.getClass();
  182. }
  183. return combineTypeAndValue(valueType.getCanonicalName(),
  184. encodeObject(value, idMapper));
  185. }
  186. }
  187. private static Object encodeObject(Object value, PaintableIdMapper idMapper)
  188. throws JSONException {
  189. JSONObject jsonMap = new JSONObject();
  190. try {
  191. for (PropertyDescriptor pd : Introspector.getBeanInfo(
  192. value.getClass()).getPropertyDescriptors()) {
  193. String fieldName = pd.getName();
  194. Class<?> fieldType = pd.getPropertyType();
  195. if (pd.getReadMethod() == null || pd.getWriteMethod() == null) {
  196. continue;
  197. }
  198. Method getterMethod = pd.getReadMethod();
  199. Object fieldValue = getterMethod.invoke(value, null);
  200. jsonMap.put(fieldName, encode(fieldValue, fieldType, idMapper));
  201. }
  202. } catch (Exception e) {
  203. // TODO: Should exceptions be handled in a different way?
  204. throw new JSONException(e);
  205. }
  206. return jsonMap;
  207. }
  208. private static Object decodeObject(String type,
  209. JSONObject serializedObject, PaintableIdMapper idMapper)
  210. throws JSONException {
  211. Class<?> cls;
  212. try {
  213. cls = Class.forName(type);
  214. Object decodedObject = cls.newInstance();
  215. for (PropertyDescriptor pd : Introspector.getBeanInfo(cls)
  216. .getPropertyDescriptors()) {
  217. if (pd.getReadMethod() == null || pd.getWriteMethod() == null) {
  218. continue;
  219. }
  220. String fieldName = pd.getName();
  221. JSONArray encodedObject = serializedObject
  222. .getJSONArray(fieldName);
  223. pd.getWriteMethod().invoke(decodedObject,
  224. decode(encodedObject, idMapper));
  225. }
  226. return decodedObject;
  227. } catch (ClassNotFoundException e) {
  228. throw new JSONException(e);
  229. } catch (IllegalArgumentException e) {
  230. throw new JSONException(e);
  231. } catch (IllegalAccessException e) {
  232. throw new JSONException(e);
  233. } catch (InvocationTargetException e) {
  234. throw new JSONException(e);
  235. } catch (InstantiationException e) {
  236. throw new JSONException(e);
  237. } catch (IntrospectionException e) {
  238. throw new JSONException(e);
  239. }
  240. }
  241. private static JSONArray encodeArrayContents(Object[] array,
  242. PaintableIdMapper idMapper) throws JSONException {
  243. JSONArray jsonArray = new JSONArray();
  244. for (int i = 0; i < array.length; ++i) {
  245. // TODO handle object graph loops?
  246. jsonArray.put(encode(array[i], idMapper));
  247. }
  248. return jsonArray;
  249. }
  250. private static JSONObject encodeMapContents(Map<String, Object> map,
  251. PaintableIdMapper idMapper) throws JSONException {
  252. JSONObject jsonMap = new JSONObject();
  253. for (String mapKey : map.keySet()) {
  254. // TODO handle object graph loops?
  255. Object mapValue = map.get(mapKey);
  256. jsonMap.put(mapKey, encode(mapValue, idMapper));
  257. }
  258. return jsonMap;
  259. }
  260. private static JSONArray combineTypeAndValue(String type, Object value) {
  261. JSONArray outerArray = new JSONArray();
  262. outerArray.put(type);
  263. outerArray.put(value);
  264. return outerArray;
  265. }
  266. private static String getTransportType(Object value) {
  267. if (null == value) {
  268. return JsonEncoder.VTYPE_UNDEFINED;
  269. }
  270. String transportType = typeToTransportType.get(value.getClass());
  271. if (null != transportType) {
  272. return transportType;
  273. }
  274. // TODO throw exception?
  275. return JsonEncoder.VTYPE_UNDEFINED;
  276. }
  277. }