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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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.server;
  17. import java.beans.IntrospectionException;
  18. import java.beans.Introspector;
  19. import java.beans.PropertyDescriptor;
  20. import java.io.Serializable;
  21. import java.lang.reflect.Array;
  22. import java.lang.reflect.Field;
  23. import java.lang.reflect.GenericArrayType;
  24. import java.lang.reflect.Method;
  25. import java.lang.reflect.Modifier;
  26. import java.lang.reflect.ParameterizedType;
  27. import java.lang.reflect.Type;
  28. import java.util.ArrayList;
  29. import java.util.Collection;
  30. import java.util.Date;
  31. import java.util.HashMap;
  32. import java.util.HashSet;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.Map.Entry;
  36. import java.util.Set;
  37. import java.util.concurrent.ConcurrentHashMap;
  38. import java.util.concurrent.ConcurrentMap;
  39. import com.vaadin.server.communication.DateSerializer;
  40. import com.vaadin.server.communication.JSONSerializer;
  41. import com.vaadin.shared.Connector;
  42. import com.vaadin.shared.JsonConstants;
  43. import com.vaadin.shared.communication.UidlValue;
  44. import com.vaadin.ui.Component;
  45. import com.vaadin.ui.ConnectorTracker;
  46. import elemental.json.Json;
  47. import elemental.json.JsonArray;
  48. import elemental.json.JsonException;
  49. import elemental.json.JsonNull;
  50. import elemental.json.JsonObject;
  51. import elemental.json.JsonString;
  52. import elemental.json.JsonType;
  53. import elemental.json.JsonValue;
  54. import elemental.json.impl.JreJsonArray;
  55. /**
  56. * Decoder for converting RPC parameters and other values from JSON in transfer
  57. * between the client and the server and vice versa.
  58. *
  59. * @since 7.0
  60. */
  61. public class JsonCodec implements Serializable {
  62. /* Immutable Encode Result representing null */
  63. private static final EncodeResult ENCODE_RESULT_NULL = new EncodeResult(
  64. Json.createNull());
  65. /* Immutable empty JSONArray */
  66. private static final JsonArray EMPTY_JSON_ARRAY = new JreJsonArray(
  67. Json.instance()) {
  68. @Override
  69. public void set(int index, JsonValue value) {
  70. throw new UnsupportedOperationException(
  71. "Immutable empty JsonArray.");
  72. }
  73. @Override
  74. public void set(int index, String string) {
  75. throw new UnsupportedOperationException(
  76. "Immutable empty JsonArray.");
  77. }
  78. @Override
  79. public void set(int index, double number) {
  80. throw new UnsupportedOperationException(
  81. "Immutable empty JsonArray.");
  82. }
  83. @Override
  84. public void set(int index, boolean bool) {
  85. throw new UnsupportedOperationException(
  86. "Immutable empty JsonArray.");
  87. }
  88. };
  89. public static interface BeanProperty extends Serializable {
  90. public Object getValue(Object bean) throws Exception;
  91. public void setValue(Object bean, Object value) throws Exception;
  92. public String getName();
  93. public Type getType();
  94. }
  95. private static class FieldProperty implements BeanProperty {
  96. private final Field field;
  97. public FieldProperty(Field field) {
  98. this.field = field;
  99. }
  100. @Override
  101. public Object getValue(Object bean) throws Exception {
  102. return field.get(bean);
  103. }
  104. @Override
  105. public void setValue(Object bean, Object value) throws Exception {
  106. field.set(bean, value);
  107. }
  108. @Override
  109. public String getName() {
  110. return field.getName();
  111. }
  112. @Override
  113. public Type getType() {
  114. return field.getGenericType();
  115. }
  116. public static Collection<FieldProperty> find(Class<?> type)
  117. throws IntrospectionException {
  118. Field[] fields = type.getFields();
  119. Collection<FieldProperty> properties = new ArrayList<FieldProperty>(
  120. fields.length);
  121. for (Field field : fields) {
  122. if (!Modifier.isStatic(field.getModifiers())) {
  123. properties.add(new FieldProperty(field));
  124. }
  125. }
  126. return properties;
  127. }
  128. }
  129. private static class MethodProperty implements BeanProperty {
  130. private final PropertyDescriptor pd;
  131. public MethodProperty(PropertyDescriptor pd) {
  132. this.pd = pd;
  133. }
  134. @Override
  135. public Object getValue(Object bean) throws Exception {
  136. Method readMethod = pd.getReadMethod();
  137. return readMethod.invoke(bean);
  138. }
  139. @Override
  140. public void setValue(Object bean, Object value) throws Exception {
  141. pd.getWriteMethod().invoke(bean, value);
  142. }
  143. @Override
  144. public String getName() {
  145. String fieldName = pd.getWriteMethod().getName().substring(3);
  146. fieldName = Character.toLowerCase(fieldName.charAt(0))
  147. + fieldName.substring(1);
  148. return fieldName;
  149. }
  150. public static Collection<MethodProperty> find(Class<?> type)
  151. throws IntrospectionException {
  152. Collection<MethodProperty> properties = new ArrayList<MethodProperty>();
  153. for (PropertyDescriptor pd : Introspector.getBeanInfo(type)
  154. .getPropertyDescriptors()) {
  155. if (pd.getReadMethod() == null || pd.getWriteMethod() == null) {
  156. continue;
  157. }
  158. properties.add(new MethodProperty(pd));
  159. }
  160. return properties;
  161. }
  162. @Override
  163. public Type getType() {
  164. return pd.getReadMethod().getGenericReturnType();
  165. }
  166. }
  167. /**
  168. * Cache the collection of bean properties for a given type to avoid doing a
  169. * quite expensive lookup multiple times. Will be used from any thread that
  170. * happens to process Vaadin requests, so it must be protected from
  171. * corruption caused by concurrent access.
  172. */
  173. private static ConcurrentMap<Class<?>, Collection<BeanProperty>> typePropertyCache = new ConcurrentHashMap<Class<?>, Collection<BeanProperty>>();
  174. private static Map<Class<?>, String> typeToTransportType = new HashMap<Class<?>, String>();
  175. /**
  176. * Note! This does not contain primitives.
  177. * <p>
  178. */
  179. private static Map<String, Class<?>> transportTypeToType = new HashMap<String, Class<?>>();
  180. private static Map<Class<?>, JSONSerializer<?>> customSerializers = new HashMap<Class<?>, JSONSerializer<?>>();
  181. static {
  182. customSerializers.put(Date.class, new DateSerializer());
  183. }
  184. static {
  185. registerType(String.class, JsonConstants.VTYPE_STRING);
  186. registerType(Connector.class, JsonConstants.VTYPE_CONNECTOR);
  187. registerType(Boolean.class, JsonConstants.VTYPE_BOOLEAN);
  188. registerType(boolean.class, JsonConstants.VTYPE_BOOLEAN);
  189. registerType(Integer.class, JsonConstants.VTYPE_INTEGER);
  190. registerType(int.class, JsonConstants.VTYPE_INTEGER);
  191. registerType(Float.class, JsonConstants.VTYPE_FLOAT);
  192. registerType(float.class, JsonConstants.VTYPE_FLOAT);
  193. registerType(Double.class, JsonConstants.VTYPE_DOUBLE);
  194. registerType(double.class, JsonConstants.VTYPE_DOUBLE);
  195. registerType(Long.class, JsonConstants.VTYPE_LONG);
  196. registerType(long.class, JsonConstants.VTYPE_LONG);
  197. registerType(String[].class, JsonConstants.VTYPE_STRINGARRAY);
  198. registerType(Object[].class, JsonConstants.VTYPE_ARRAY);
  199. registerType(Map.class, JsonConstants.VTYPE_MAP);
  200. registerType(HashMap.class, JsonConstants.VTYPE_MAP);
  201. registerType(List.class, JsonConstants.VTYPE_LIST);
  202. registerType(Set.class, JsonConstants.VTYPE_SET);
  203. registerType(Void.class, JsonConstants.VTYPE_NULL);
  204. }
  205. private static void registerType(Class<?> type, String transportType) {
  206. typeToTransportType.put(type, transportType);
  207. if (!type.isPrimitive()) {
  208. transportTypeToType.put(transportType, type);
  209. }
  210. }
  211. public static boolean isInternalTransportType(String transportType) {
  212. return transportTypeToType.containsKey(transportType);
  213. }
  214. public static boolean isInternalType(Type type) {
  215. if (type instanceof Class && ((Class<?>) type).isPrimitive()) {
  216. if (type == byte.class || type == char.class) {
  217. // Almost all primitive types are handled internally
  218. return false;
  219. }
  220. // All primitive types are handled internally
  221. return true;
  222. } else if (type == UidlValue.class) {
  223. // UidlValue is a special internal type wrapping type info and a
  224. // value
  225. return true;
  226. }
  227. return typeToTransportType.containsKey(getClassForType(type));
  228. }
  229. private static Class<?> getClassForType(Type type) {
  230. if (type instanceof ParameterizedType) {
  231. return (Class<?>) (((ParameterizedType) type).getRawType());
  232. } else if (type instanceof Class<?>) {
  233. return (Class<?>) type;
  234. } else {
  235. return null;
  236. }
  237. }
  238. private static Class<?> getType(String transportType) {
  239. return transportTypeToType.get(transportType);
  240. }
  241. public static Object decodeInternalOrCustomType(Type targetType,
  242. JsonValue value, ConnectorTracker connectorTracker) {
  243. if (isInternalType(targetType)) {
  244. return decodeInternalType(targetType, false, value,
  245. connectorTracker);
  246. } else {
  247. return decodeCustomType(targetType, value, connectorTracker);
  248. }
  249. }
  250. public static Object decodeCustomType(Type targetType, JsonValue value,
  251. ConnectorTracker connectorTracker) {
  252. if (isInternalType(targetType)) {
  253. throw new JsonException("decodeCustomType cannot be used for "
  254. + targetType + ", which is an internal type");
  255. }
  256. // Try to decode object using fields
  257. if (isJsonType(targetType)) {
  258. return value;
  259. } else if (value.getType() == JsonType.NULL) {
  260. return null;
  261. } else if (targetType == byte.class || targetType == Byte.class) {
  262. return Byte.valueOf((byte) value.asNumber());
  263. } else if (targetType == char.class || targetType == Character.class) {
  264. return Character.valueOf(value.asString().charAt(0));
  265. } else if (targetType instanceof Class<?>
  266. && ((Class<?>) targetType).isArray()) {
  267. // Legacy Object[] and String[] handled elsewhere, this takes care
  268. // of generic arrays
  269. Class<?> componentType = ((Class<?>) targetType).getComponentType();
  270. return decodeArray(componentType, (JsonArray) value,
  271. connectorTracker);
  272. } else if (targetType instanceof GenericArrayType) {
  273. Type componentType = ((GenericArrayType) targetType)
  274. .getGenericComponentType();
  275. return decodeArray(componentType, (JsonArray) value,
  276. connectorTracker);
  277. } else if (JsonValue.class
  278. .isAssignableFrom(getClassForType(targetType))) {
  279. return value;
  280. } else if (Enum.class.isAssignableFrom(getClassForType(targetType))) {
  281. Class<?> classForType = getClassForType(targetType);
  282. return decodeEnum(classForType.asSubclass(Enum.class),
  283. (JsonString) value);
  284. } else if (customSerializers.containsKey(getClassForType(targetType))) {
  285. return customSerializers.get(getClassForType(targetType))
  286. .deserialize(targetType, value, connectorTracker);
  287. } else {
  288. return decodeObject(targetType, (JsonObject) value,
  289. connectorTracker);
  290. }
  291. }
  292. private static boolean isJsonType(Type type) {
  293. return type instanceof Class<?>
  294. && JsonValue.class.isAssignableFrom((Class<?>) type);
  295. }
  296. private static Object decodeArray(Type componentType, JsonArray value,
  297. ConnectorTracker connectorTracker) {
  298. Class<?> componentClass = getClassForType(componentType);
  299. Object array = Array.newInstance(componentClass, value.length());
  300. for (int i = 0; i < value.length(); i++) {
  301. Object decodedValue = decodeInternalOrCustomType(componentType,
  302. value.get(i), connectorTracker);
  303. Array.set(array, i, decodedValue);
  304. }
  305. return array;
  306. }
  307. /**
  308. * Decodes a value that is of an internal type.
  309. * <p>
  310. * Ensures the encoded value is of the same type as target type.
  311. * </p>
  312. * <p>
  313. * Allows restricting collections so that they must be declared using
  314. * generics. If this is used then all objects in the collection are encoded
  315. * using the declared type. Otherwise only internal types are allowed in
  316. * collections.
  317. * </p>
  318. *
  319. * @param targetType
  320. * The type that should be returned by this method
  321. * @param valueAndType
  322. * The encoded value and type array
  323. * @param application
  324. * A reference to the application
  325. * @param enforceGenericsInCollections
  326. * true if generics should be enforce, false to only allow
  327. * internal types in collections
  328. * @return
  329. */
  330. public static Object decodeInternalType(Type targetType,
  331. boolean restrictToInternalTypes, JsonValue encodedJsonValue,
  332. ConnectorTracker connectorTracker) {
  333. if (!isInternalType(targetType)) {
  334. throw new JsonException("Type " + targetType
  335. + " is not a supported internal type.");
  336. }
  337. String transportType = getInternalTransportType(targetType);
  338. if (encodedJsonValue.getType() == JsonType.NULL) {
  339. return null;
  340. } else if (targetType == Void.class) {
  341. throw new JsonException(
  342. "Something other than null was encoded for a null type");
  343. }
  344. // UidlValue
  345. if (targetType == UidlValue.class) {
  346. return decodeUidlValue((JsonArray) encodedJsonValue,
  347. connectorTracker);
  348. }
  349. // Collections
  350. if (JsonConstants.VTYPE_LIST.equals(transportType)) {
  351. return decodeList(targetType, restrictToInternalTypes,
  352. (JsonArray) encodedJsonValue, connectorTracker);
  353. } else if (JsonConstants.VTYPE_SET.equals(transportType)) {
  354. return decodeSet(targetType, restrictToInternalTypes,
  355. (JsonArray) encodedJsonValue, connectorTracker);
  356. } else if (JsonConstants.VTYPE_MAP.equals(transportType)) {
  357. return decodeMap(targetType, restrictToInternalTypes,
  358. encodedJsonValue, connectorTracker);
  359. }
  360. // Arrays
  361. if (JsonConstants.VTYPE_ARRAY.equals(transportType)) {
  362. return decodeObjectArray(targetType, (JsonArray) encodedJsonValue,
  363. connectorTracker);
  364. } else if (JsonConstants.VTYPE_STRINGARRAY.equals(transportType)) {
  365. return decodeArray(String.class, (JsonArray) encodedJsonValue, null);
  366. }
  367. // Special Vaadin types
  368. if (JsonConstants.VTYPE_CONNECTOR.equals(transportType)) {
  369. return connectorTracker.getConnector(encodedJsonValue.asString());
  370. }
  371. // Legacy types
  372. if (JsonConstants.VTYPE_STRING.equals(transportType)) {
  373. return encodedJsonValue.asString();
  374. } else if (JsonConstants.VTYPE_INTEGER.equals(transportType)) {
  375. return (int) encodedJsonValue.asNumber();
  376. } else if (JsonConstants.VTYPE_LONG.equals(transportType)) {
  377. return (long) encodedJsonValue.asNumber();
  378. } else if (JsonConstants.VTYPE_FLOAT.equals(transportType)) {
  379. return (float) encodedJsonValue.asNumber();
  380. } else if (JsonConstants.VTYPE_DOUBLE.equals(transportType)) {
  381. return encodedJsonValue.asNumber();
  382. } else if (JsonConstants.VTYPE_BOOLEAN.equals(transportType)) {
  383. return encodedJsonValue.asBoolean();
  384. }
  385. throw new JsonException("Unknown type " + transportType);
  386. }
  387. private static UidlValue decodeUidlValue(JsonArray encodedJsonValue,
  388. ConnectorTracker connectorTracker) {
  389. String type = encodedJsonValue.getString(0);
  390. Object decodedValue = decodeInternalType(getType(type), true,
  391. encodedJsonValue.get(1), connectorTracker);
  392. return new UidlValue(decodedValue);
  393. }
  394. private static Map<Object, Object> decodeMap(Type targetType,
  395. boolean restrictToInternalTypes, JsonValue jsonMap,
  396. ConnectorTracker connectorTracker) {
  397. if (jsonMap.getType() == JsonType.ARRAY) {
  398. // Client-side has no declared type information to determine
  399. // encoding method for empty maps, so these are handled separately.
  400. // See #8906.
  401. JsonArray jsonArray = (JsonArray) jsonMap;
  402. if (jsonArray.length() == 0) {
  403. return new HashMap<Object, Object>();
  404. }
  405. }
  406. if (!restrictToInternalTypes && targetType instanceof ParameterizedType) {
  407. Type keyType = ((ParameterizedType) targetType)
  408. .getActualTypeArguments()[0];
  409. Type valueType = ((ParameterizedType) targetType)
  410. .getActualTypeArguments()[1];
  411. if (keyType == String.class) {
  412. return decodeStringMap(valueType, (JsonObject) jsonMap,
  413. connectorTracker);
  414. } else if (keyType == Connector.class) {
  415. return decodeConnectorMap(valueType, (JsonObject) jsonMap,
  416. connectorTracker);
  417. } else {
  418. return decodeObjectMap(keyType, valueType, (JsonArray) jsonMap,
  419. connectorTracker);
  420. }
  421. } else {
  422. return decodeStringMap(UidlValue.class, (JsonObject) jsonMap,
  423. connectorTracker);
  424. }
  425. }
  426. private static Map<Object, Object> decodeObjectMap(Type keyType,
  427. Type valueType, JsonArray jsonMap, ConnectorTracker connectorTracker) {
  428. JsonArray keys = jsonMap.getArray(0);
  429. JsonArray values = jsonMap.getArray(1);
  430. assert (keys.length() == values.length());
  431. Map<Object, Object> map = new HashMap<Object, Object>(keys.length() * 2);
  432. for (int i = 0; i < keys.length(); i++) {
  433. Object key = decodeInternalOrCustomType(keyType, keys.get(i),
  434. connectorTracker);
  435. Object value = decodeInternalOrCustomType(valueType, values.get(i),
  436. connectorTracker);
  437. map.put(key, value);
  438. }
  439. return map;
  440. }
  441. private static Map<Object, Object> decodeConnectorMap(Type valueType,
  442. JsonObject jsonMap, ConnectorTracker connectorTracker) {
  443. Map<Object, Object> map = new HashMap<Object, Object>();
  444. for (String key : jsonMap.keys()) {
  445. Object value = decodeInternalOrCustomType(valueType,
  446. jsonMap.get(key), connectorTracker);
  447. if (valueType == UidlValue.class) {
  448. value = ((UidlValue) value).getValue();
  449. }
  450. map.put(connectorTracker.getConnector(key), value);
  451. }
  452. return map;
  453. }
  454. private static Map<Object, Object> decodeStringMap(Type valueType,
  455. JsonObject jsonMap, ConnectorTracker connectorTracker) {
  456. Map<Object, Object> map = new HashMap<Object, Object>();
  457. for (String key : jsonMap.keys()) {
  458. Object value = decodeInternalOrCustomType(valueType,
  459. jsonMap.get(key), connectorTracker);
  460. if (valueType == UidlValue.class) {
  461. value = ((UidlValue) value).getValue();
  462. }
  463. map.put(key, value);
  464. }
  465. return map;
  466. }
  467. /**
  468. * @param targetType
  469. * @param restrictToInternalTypes
  470. * @param typeIndex
  471. * The index of a generic type to use to define the child type
  472. * that should be decoded
  473. * @param encodedValueAndType
  474. * @param application
  475. * @return
  476. */
  477. private static Object decodeParametrizedType(Type targetType,
  478. boolean restrictToInternalTypes, int typeIndex, JsonValue value,
  479. ConnectorTracker connectorTracker) {
  480. if (!restrictToInternalTypes && targetType instanceof ParameterizedType) {
  481. Type childType = ((ParameterizedType) targetType)
  482. .getActualTypeArguments()[typeIndex];
  483. // Only decode the given type
  484. return decodeInternalOrCustomType(childType, value,
  485. connectorTracker);
  486. } else {
  487. // Only UidlValue when not enforcing a given type to avoid security
  488. // issues
  489. UidlValue decodeInternalType = (UidlValue) decodeInternalType(
  490. UidlValue.class, true, value, connectorTracker);
  491. return decodeInternalType.getValue();
  492. }
  493. }
  494. private static Object decodeEnum(Class<? extends Enum> cls, JsonString value) {
  495. return Enum.valueOf(cls, value.getString());
  496. }
  497. private static Object[] decodeObjectArray(Type targetType,
  498. JsonArray jsonArray, ConnectorTracker connectorTracker) {
  499. List<Object> list = decodeList(List.class, true, jsonArray,
  500. connectorTracker);
  501. return list.toArray(new Object[list.size()]);
  502. }
  503. private static List<Object> decodeList(Type targetType,
  504. boolean restrictToInternalTypes, JsonArray jsonArray,
  505. ConnectorTracker connectorTracker) {
  506. int arrayLength = jsonArray.length();
  507. List<Object> list = new ArrayList<Object>(arrayLength);
  508. for (int i = 0; i < arrayLength; ++i) {
  509. // each entry always has two elements: type and value
  510. JsonValue encodedValue = jsonArray.get(i);
  511. Object decodedChild = decodeParametrizedType(targetType,
  512. restrictToInternalTypes, 0, encodedValue, connectorTracker);
  513. list.add(decodedChild);
  514. }
  515. return list;
  516. }
  517. private static Set<Object> decodeSet(Type targetType,
  518. boolean restrictToInternalTypes, JsonArray jsonArray,
  519. ConnectorTracker connectorTracker) {
  520. HashSet<Object> set = new HashSet<Object>();
  521. set.addAll(decodeList(targetType, restrictToInternalTypes, jsonArray,
  522. connectorTracker));
  523. return set;
  524. }
  525. private static Object decodeObject(Type targetType,
  526. JsonObject serializedObject, ConnectorTracker connectorTracker) {
  527. Class<?> targetClass = getClassForType(targetType);
  528. try {
  529. Object decodedObject = targetClass.newInstance();
  530. for (BeanProperty property : getProperties(targetClass)) {
  531. String fieldName = property.getName();
  532. JsonValue encodedFieldValue = serializedObject.get(fieldName);
  533. Type fieldType = property.getType();
  534. Object decodedFieldValue = decodeInternalOrCustomType(
  535. fieldType, encodedFieldValue, connectorTracker);
  536. property.setValue(decodedObject, decodedFieldValue);
  537. }
  538. return decodedObject;
  539. } catch (Exception e) {
  540. throw new RuntimeException(e);
  541. }
  542. }
  543. public static EncodeResult encode(Object value, JsonValue diffState,
  544. Type valueType, ConnectorTracker connectorTracker) {
  545. if (null == value) {
  546. return ENCODE_RESULT_NULL;
  547. }
  548. // Storing a single reference and only returning the EncodeResult at the
  549. // end the method is much shorter in bytecode which allows inlining
  550. JsonValue toReturn;
  551. if (value instanceof JsonValue) {
  552. // all JSON compatible types are returned as is.
  553. toReturn = (JsonValue) value;
  554. } else if (value instanceof String) {
  555. toReturn = Json.create((String) value);
  556. } else if (value instanceof Boolean) {
  557. toReturn = Json.create((Boolean) value);
  558. } else if (value instanceof Number) {
  559. toReturn = Json.create(((Number) value).doubleValue());
  560. } else if (value instanceof Character) {
  561. toReturn = Json.create(Character.toString((Character) value));
  562. } else if (value instanceof Collection) {
  563. toReturn = encodeCollection(valueType, (Collection<?>) value,
  564. connectorTracker);
  565. } else if (value instanceof Map) {
  566. toReturn = encodeMap(valueType, (Map<?, ?>) value, connectorTracker);
  567. } else if (value instanceof Connector) {
  568. if (value instanceof Component
  569. && !(LegacyCommunicationManager
  570. .isComponentVisibleToClient((Component) value))) {
  571. // an encoded null is cached, return it directly.
  572. return ENCODE_RESULT_NULL;
  573. }
  574. // Connectors are simply serialized as ID.
  575. toReturn = Json.create(((Connector) value).getConnectorId());
  576. } else if (value instanceof Enum) {
  577. toReturn = Json.create(((Enum<?>) value).name());
  578. } else if (customSerializers.containsKey(value.getClass())) {
  579. toReturn = serializeJson(value, connectorTracker);
  580. } else if (valueType instanceof GenericArrayType) {
  581. toReturn = encodeArrayContents(
  582. ((GenericArrayType) valueType).getGenericComponentType(),
  583. value, connectorTracker);
  584. } else if (valueType instanceof Class<?>) {
  585. if (((Class<?>) valueType).isArray()) {
  586. toReturn = encodeArrayContents(
  587. ((Class<?>) valueType).getComponentType(), value,
  588. connectorTracker);
  589. } else {
  590. // encodeObject returns an EncodeResult with a diff, thus it
  591. // needs to return it directly rather than assigning it to
  592. // toReturn.
  593. return encodeObject(value, (Class<?>) valueType,
  594. (JsonObject) diffState, connectorTracker);
  595. }
  596. } else {
  597. throw new JsonException("Can not encode type " + valueType);
  598. }
  599. return new EncodeResult(toReturn);
  600. }
  601. public static Collection<BeanProperty> getProperties(Class<?> type)
  602. throws IntrospectionException {
  603. Collection<BeanProperty> cachedProperties = typePropertyCache.get(type);
  604. if (cachedProperties != null) {
  605. return cachedProperties;
  606. }
  607. Collection<BeanProperty> properties = new ArrayList<BeanProperty>();
  608. properties.addAll(MethodProperty.find(type));
  609. properties.addAll(FieldProperty.find(type));
  610. // Doesn't matter if the same calculation is done multiple times from
  611. // different threads, so there's no need to do e.g. putIfAbsent
  612. typePropertyCache.put(type, properties);
  613. return properties;
  614. }
  615. /*
  616. * Loops through the fields of value and encodes them.
  617. */
  618. private static EncodeResult encodeObject(Object value, Class<?> valueType,
  619. JsonObject referenceValue, ConnectorTracker connectorTracker) {
  620. JsonObject encoded = Json.createObject();
  621. JsonObject diff = Json.createObject();
  622. try {
  623. for (BeanProperty property : getProperties(valueType)) {
  624. String fieldName = property.getName();
  625. // We can't use PropertyDescriptor.getPropertyType() as it does
  626. // not support generics
  627. Type fieldType = property.getType();
  628. Object fieldValue = property.getValue(value);
  629. if (encoded.hasKey(fieldName)) {
  630. throw new RuntimeException(
  631. "Can't encode "
  632. + valueType.getName()
  633. + " as it has multiple properties with the name "
  634. + fieldName.toLowerCase()
  635. + ". This can happen if there are getters and setters for a public field (the framework can't know which to ignore) or if there are properties with only casing distinguishing between the names (e.g. getFoo() and getFOO())");
  636. }
  637. JsonValue fieldReference;
  638. if (referenceValue != null) {
  639. fieldReference = referenceValue.get(fieldName);
  640. if (fieldReference instanceof JsonNull) {
  641. fieldReference = null;
  642. }
  643. } else {
  644. fieldReference = null;
  645. }
  646. EncodeResult encodeResult = encode(fieldValue, fieldReference,
  647. fieldType, connectorTracker);
  648. encoded.put(fieldName, encodeResult.getEncodedValue());
  649. if (valueChanged(encodeResult.getEncodedValue(), fieldReference)) {
  650. diff.put(fieldName, encodeResult.getDiffOrValue());
  651. }
  652. }
  653. } catch (Exception e) {
  654. // TODO: Should exceptions be handled in a different way?
  655. throw new RuntimeException(e);
  656. }
  657. return new EncodeResult(encoded, diff);
  658. }
  659. /**
  660. * Compares the value with the reference. If they match, returns false.
  661. *
  662. * @param fieldValue
  663. * @param referenceValue
  664. * @return
  665. */
  666. private static boolean valueChanged(JsonValue fieldValue,
  667. JsonValue referenceValue) {
  668. if (fieldValue instanceof JsonNull) {
  669. fieldValue = null;
  670. }
  671. if (fieldValue == referenceValue) {
  672. return false;
  673. } else if (fieldValue == null || referenceValue == null) {
  674. return true;
  675. } else {
  676. return !jsonEquals(fieldValue, referenceValue);
  677. }
  678. }
  679. /**
  680. * Compares two json values for deep equality.
  681. *
  682. * This is a helper for overcoming the fact that
  683. * {@link JsonValue#equals(Object)} only does an identity check and
  684. * {@link JsonValue#jsEquals(JsonValue)} is defined to use JavaScript
  685. * semantics where arrays and objects are equals only based on identity.
  686. *
  687. * @since 7.4
  688. * @param a
  689. * the first json value to check, may not be null
  690. * @param b
  691. * the second json value to check, may not be null
  692. * @return <code>true</code> if both json values are the same;
  693. * <code>false</code> otherwise
  694. */
  695. public static boolean jsonEquals(JsonValue a, JsonValue b) {
  696. assert a != null;
  697. assert b != null;
  698. if (a == b) {
  699. return true;
  700. }
  701. JsonType type = a.getType();
  702. if (type != b.getType()) {
  703. return false;
  704. }
  705. switch (type) {
  706. case NULL:
  707. return true;
  708. case BOOLEAN:
  709. return a.asBoolean() == b.asBoolean();
  710. case NUMBER:
  711. return a.asNumber() == b.asNumber();
  712. case STRING:
  713. return a.asString().equals(b.asString());
  714. case OBJECT:
  715. return jsonObjectEquals((JsonObject) a, (JsonObject) b);
  716. case ARRAY:
  717. return jsonArrayEquals((JsonArray) a, (JsonArray) b);
  718. default:
  719. throw new RuntimeException("Unsupported JsonType: " + type);
  720. }
  721. }
  722. private static boolean jsonObjectEquals(JsonObject a, JsonObject b) {
  723. String[] keys = a.keys();
  724. if (keys.length != b.keys().length) {
  725. return false;
  726. }
  727. for (String key : keys) {
  728. JsonValue value = b.get(key);
  729. if (value == null || !jsonEquals(a.get(key), value)) {
  730. return false;
  731. }
  732. }
  733. return true;
  734. }
  735. private static boolean jsonArrayEquals(JsonArray a, JsonArray b) {
  736. if (a.length() != b.length()) {
  737. return false;
  738. }
  739. for (int i = 0; i < a.length(); i++) {
  740. if (!jsonEquals(a.get(i), b.get(i))) {
  741. return false;
  742. }
  743. }
  744. return true;
  745. }
  746. private static JsonArray encodeArrayContents(Type componentType,
  747. Object array, ConnectorTracker connectorTracker) {
  748. JsonArray jsonArray = Json.createArray();
  749. for (int i = 0; i < Array.getLength(array); i++) {
  750. EncodeResult encodeResult = encode(Array.get(array, i), null,
  751. componentType, connectorTracker);
  752. jsonArray.set(i, encodeResult.getEncodedValue());
  753. }
  754. return jsonArray;
  755. }
  756. private static JsonArray encodeCollection(Type targetType,
  757. Collection<?> collection, ConnectorTracker connectorTracker) {
  758. JsonArray jsonArray = Json.createArray();
  759. for (Object o : collection) {
  760. jsonArray.set(jsonArray.length(),
  761. encodeChild(targetType, 0, o, connectorTracker));
  762. }
  763. return jsonArray;
  764. }
  765. private static JsonValue encodeChild(Type targetType, int typeIndex,
  766. Object o, ConnectorTracker connectorTracker) {
  767. if (targetType instanceof ParameterizedType) {
  768. Type childType = ((ParameterizedType) targetType)
  769. .getActualTypeArguments()[typeIndex];
  770. // Encode using the given type
  771. EncodeResult encodeResult = encode(o, null, childType,
  772. connectorTracker);
  773. return encodeResult.getEncodedValue();
  774. } else {
  775. throw new JsonException("Collection is missing generics");
  776. }
  777. }
  778. private static JsonValue encodeMap(Type mapType, Map<?, ?> map,
  779. ConnectorTracker connectorTracker) {
  780. Type keyType, valueType;
  781. if (mapType instanceof ParameterizedType) {
  782. keyType = ((ParameterizedType) mapType).getActualTypeArguments()[0];
  783. valueType = ((ParameterizedType) mapType).getActualTypeArguments()[1];
  784. } else {
  785. throw new JsonException("Map is missing generics");
  786. }
  787. if (map.isEmpty()) {
  788. // Client -> server encodes empty map as an empty array because of
  789. // #8906. Do the same for server -> client to maintain symmetry.
  790. return EMPTY_JSON_ARRAY;
  791. }
  792. if (keyType == String.class) {
  793. return encodeStringMap(valueType, map, connectorTracker);
  794. } else if (keyType == Connector.class) {
  795. return encodeConnectorMap(valueType, map, connectorTracker);
  796. } else {
  797. return encodeObjectMap(keyType, valueType, map, connectorTracker);
  798. }
  799. }
  800. private static JsonArray encodeObjectMap(Type keyType, Type valueType,
  801. Map<?, ?> map, ConnectorTracker connectorTracker) {
  802. JsonArray keys = Json.createArray();
  803. JsonArray values = Json.createArray();
  804. for (Entry<?, ?> entry : map.entrySet()) {
  805. EncodeResult encodedKey = encode(entry.getKey(), null, keyType,
  806. connectorTracker);
  807. EncodeResult encodedValue = encode(entry.getValue(), null,
  808. valueType, connectorTracker);
  809. keys.set(keys.length(), encodedKey.getEncodedValue());
  810. values.set(values.length(), encodedValue.getEncodedValue());
  811. }
  812. JsonArray jsonMap = Json.createArray();
  813. jsonMap.set(0, keys);
  814. jsonMap.set(1, values);
  815. return jsonMap;
  816. }
  817. /*
  818. * Encodes a connector map. Invisible connectors are skipped.
  819. */
  820. private static JsonObject encodeConnectorMap(Type valueType, Map<?, ?> map,
  821. ConnectorTracker connectorTracker) {
  822. JsonObject jsonMap = Json.createObject();
  823. for (Entry<?, ?> entry : map.entrySet()) {
  824. ClientConnector key = (ClientConnector) entry.getKey();
  825. if (LegacyCommunicationManager.isConnectorVisibleToClient(key)) {
  826. EncodeResult encodedValue = encode(entry.getValue(), null,
  827. valueType, connectorTracker);
  828. jsonMap.put(key.getConnectorId(),
  829. encodedValue.getEncodedValue());
  830. }
  831. }
  832. return jsonMap;
  833. }
  834. private static JsonObject encodeStringMap(Type valueType, Map<?, ?> map,
  835. ConnectorTracker connectorTracker) {
  836. JsonObject jsonMap = Json.createObject();
  837. for (Entry<?, ?> entry : map.entrySet()) {
  838. String key = (String) entry.getKey();
  839. EncodeResult encodedValue = encode(entry.getValue(), null,
  840. valueType, connectorTracker);
  841. jsonMap.put(key, encodedValue.getEncodedValue());
  842. }
  843. return jsonMap;
  844. }
  845. /*
  846. * These methods looks good to inline, but are on a cold path of the
  847. * otherwise hot encode method, which needed to be shorted to allow inlining
  848. * of the hot part.
  849. */
  850. private static String getInternalTransportType(Type valueType) {
  851. return typeToTransportType.get(getClassForType(valueType));
  852. }
  853. private static JsonValue serializeJson(Object value,
  854. ConnectorTracker connectorTracker) {
  855. JSONSerializer serializer = customSerializers.get(value.getClass());
  856. return serializer.serialize(value, connectorTracker);
  857. }
  858. }