1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
|
/*
@VaadinApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.server;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.vaadin.Application;
import com.vaadin.external.json.JSONArray;
import com.vaadin.external.json.JSONException;
import com.vaadin.external.json.JSONObject;
import com.vaadin.external.json.JSONTokener;
import com.vaadin.terminal.gwt.client.Connector;
import com.vaadin.terminal.gwt.client.communication.JsonEncoder;
import com.vaadin.terminal.gwt.client.communication.UidlValue;
import com.vaadin.ui.Component;
/**
* Decoder for converting RPC parameters and other values from JSON in transfer
* between the client and the server and vice versa.
*
* @since 7.0
*/
public class JsonCodec implements Serializable {
private static Map<Class<?>, String> typeToTransportType = new HashMap<Class<?>, String>();
/**
* Note! This does not contain primitives.
* <p>
*/
private static Map<String, Class<?>> transportTypeToType = new HashMap<String, Class<?>>();
static {
registerType(String.class, JsonEncoder.VTYPE_STRING);
registerType(Connector.class, JsonEncoder.VTYPE_CONNECTOR);
registerType(Boolean.class, JsonEncoder.VTYPE_BOOLEAN);
registerType(boolean.class, JsonEncoder.VTYPE_BOOLEAN);
registerType(Integer.class, JsonEncoder.VTYPE_INTEGER);
registerType(int.class, JsonEncoder.VTYPE_INTEGER);
registerType(Float.class, JsonEncoder.VTYPE_FLOAT);
registerType(float.class, JsonEncoder.VTYPE_FLOAT);
registerType(Double.class, JsonEncoder.VTYPE_DOUBLE);
registerType(double.class, JsonEncoder.VTYPE_DOUBLE);
registerType(Long.class, JsonEncoder.VTYPE_LONG);
registerType(long.class, JsonEncoder.VTYPE_LONG);
registerType(String[].class, JsonEncoder.VTYPE_STRINGARRAY);
registerType(Object[].class, JsonEncoder.VTYPE_ARRAY);
registerType(Map.class, JsonEncoder.VTYPE_MAP);
registerType(HashMap.class, JsonEncoder.VTYPE_MAP);
registerType(List.class, JsonEncoder.VTYPE_LIST);
registerType(Set.class, JsonEncoder.VTYPE_SET);
}
private static void registerType(Class<?> type, String transportType) {
typeToTransportType.put(type, transportType);
if (!type.isPrimitive()) {
transportTypeToType.put(transportType, type);
}
}
public static boolean isInternalTransportType(String transportType) {
return transportTypeToType.containsKey(transportType);
}
public static boolean isInternalType(Type type) {
if (type instanceof Class && ((Class<?>) type).isPrimitive()) {
// All primitive types are handled internally
return true;
} else if (type == UidlValue.class) {
// UidlValue is a special internal type wrapping type info and a
// value
return true;
}
return typeToTransportType.containsKey(getClassForType(type));
}
private static Class<?> getClassForType(Type type) {
if (type instanceof ParameterizedType) {
return (Class<?>) (((ParameterizedType) type).getRawType());
} else {
return (Class<?>) type;
}
}
private static Class<?> getType(String transportType) {
return transportTypeToType.get(transportType);
}
public static Object decodeInternalOrCustomType(Type targetType,
Object value, Application application) throws JSONException {
if (isInternalType(targetType)) {
return decodeInternalType(targetType, false, value, application);
} else {
return decodeCustomType(targetType, value, application);
}
}
public static Object decodeCustomType(Type targetType, Object value,
Application application) throws JSONException {
if (isInternalType(targetType)) {
throw new JSONException("decodeCustomType cannot be used for "
+ targetType + ", which is an internal type");
}
// Try to decode object using fields
if (value == JSONObject.NULL) {
return null;
} else {
return decodeObject(targetType, (JSONObject) value, application);
}
}
/**
* Decodes a value that is of an internal type.
* <p>
* Ensures the encoded value is of the same type as target type.
* </p>
* <p>
* Allows restricting collections so that they must be declared using
* generics. If this is used then all objects in the collection are encoded
* using the declared type. Otherwise only internal types are allowed in
* collections.
* </p>
*
* @param targetType
* The type that should be returned by this method
* @param valueAndType
* The encoded value and type array
* @param application
* A reference to the application
* @param enforceGenericsInCollections
* true if generics should be enforce, false to only allow
* internal types in collections
* @return
* @throws JSONException
*/
public static Object decodeInternalType(Type targetType,
boolean restrictToInternalTypes, Object encodedJsonValue,
Application application) throws JSONException {
if (!isInternalType(targetType)) {
throw new JSONException("Type " + targetType
+ " is not a supported internal type.");
}
String transportType = getInternalTransportType(targetType);
if (encodedJsonValue == JSONObject.NULL) {
return null;
}
// UidlValue
if (targetType == UidlValue.class) {
return decodeUidlValue((JSONArray) encodedJsonValue, application);
}
// Collections
if (JsonEncoder.VTYPE_LIST.equals(transportType)) {
return decodeList(targetType, restrictToInternalTypes,
(JSONArray) encodedJsonValue, application);
} else if (JsonEncoder.VTYPE_SET.equals(transportType)) {
return decodeSet(targetType, restrictToInternalTypes,
(JSONArray) encodedJsonValue, application);
} else if (JsonEncoder.VTYPE_MAP.equals(transportType)) {
return decodeMap(targetType, restrictToInternalTypes,
(JSONObject) encodedJsonValue, application);
}
// Arrays
if (JsonEncoder.VTYPE_ARRAY.equals(transportType)) {
return decodeObjectArray(targetType, (JSONArray) encodedJsonValue,
application);
} else if (JsonEncoder.VTYPE_STRINGARRAY.equals(transportType)) {
return decodeStringArray((JSONArray) encodedJsonValue);
}
// Special Vaadin types
String stringValue = String.valueOf(encodedJsonValue);
if (JsonEncoder.VTYPE_CONNECTOR.equals(transportType)) {
return application.getConnector(stringValue);
}
// Standard Java types
if (JsonEncoder.VTYPE_STRING.equals(transportType)) {
return stringValue;
} else if (JsonEncoder.VTYPE_INTEGER.equals(transportType)) {
return Integer.valueOf(stringValue);
} else if (JsonEncoder.VTYPE_LONG.equals(transportType)) {
return Long.valueOf(stringValue);
} else if (JsonEncoder.VTYPE_FLOAT.equals(transportType)) {
return Float.valueOf(stringValue);
} else if (JsonEncoder.VTYPE_DOUBLE.equals(transportType)) {
return Double.valueOf(stringValue);
} else if (JsonEncoder.VTYPE_BOOLEAN.equals(transportType)) {
return Boolean.valueOf(stringValue);
}
throw new JSONException("Unknown type " + transportType);
}
private static UidlValue decodeUidlValue(JSONArray encodedJsonValue,
Application application) throws JSONException {
String type = encodedJsonValue.getString(0);
Object decodedValue = decodeInternalType(getType(type), true,
encodedJsonValue.get(1), application);
return new UidlValue(decodedValue);
}
private static boolean transportTypesCompatible(
String encodedTransportType, String transportType) {
if (encodedTransportType == null) {
return false;
}
if (encodedTransportType.equals(transportType)) {
return true;
}
if (encodedTransportType.equals(JsonEncoder.VTYPE_NULL)) {
return true;
}
return false;
}
private static Map<Object, Object> decodeMap(Type targetType,
boolean restrictToInternalTypes, JSONObject jsonMap,
Application application) throws JSONException {
HashMap<Object, Object> map = new HashMap<Object, Object>();
Iterator<String> it = jsonMap.keys();
while (it.hasNext()) {
String key = it.next();
String keyString = (String) new JSONTokener(key).nextValue();
Object encodedKey = new JSONTokener(keyString).nextValue();
Object encodedValue = jsonMap.get(key);
Object decodedKey = decodeParametrizedType(targetType,
restrictToInternalTypes, 0, encodedKey, application);
Object decodedValue = decodeParametrizedType(targetType,
restrictToInternalTypes, 1, encodedValue, application);
map.put(decodedKey, decodedValue);
}
return map;
}
/**
* @param targetType
* @param restrictToInternalTypes
* @param typeIndex
* The index of a generic type to use to define the child type
* that should be decoded
* @param encodedValueAndType
* @param application
* @return
* @throws JSONException
*/
private static Object decodeParametrizedType(Type targetType,
boolean restrictToInternalTypes, int typeIndex, Object value,
Application application) throws JSONException {
if (!restrictToInternalTypes && targetType instanceof ParameterizedType) {
Type childType = ((ParameterizedType) targetType)
.getActualTypeArguments()[typeIndex];
// Only decode the given type
return decodeInternalOrCustomType(childType, value, application);
} else {
// Only UidlValue when not enforcing a given type to avoid security
// issues
UidlValue decodeInternalType = (UidlValue) decodeInternalType(
UidlValue.class, true, value, application);
return decodeInternalType.getValue();
}
}
private static Object decodeEnum(Class<? extends Enum> cls, JSONObject value) {
String enumIdentifier = String.valueOf(value);
return Enum.valueOf(cls, enumIdentifier);
}
private static String[] decodeStringArray(JSONArray jsonArray)
throws JSONException {
int length = jsonArray.length();
List<String> tokens = new ArrayList<String>(length);
for (int i = 0; i < length; ++i) {
tokens.add(jsonArray.getString(i));
}
return tokens.toArray(new String[tokens.size()]);
}
private static Object[] decodeObjectArray(Type targetType,
JSONArray jsonArray, Application application) throws JSONException {
List list = decodeList(List.class, true, jsonArray, application);
return list.toArray(new Object[list.size()]);
}
private static List<Object> decodeList(Type targetType,
boolean restrictToInternalTypes, JSONArray jsonArray,
Application application) throws JSONException {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < jsonArray.length(); ++i) {
// each entry always has two elements: type and value
JSONArray encodedValueAndType = jsonArray.getJSONArray(i);
Object decodedChild = decodeParametrizedType(targetType,
restrictToInternalTypes, 0, encodedValueAndType,
application);
list.add(decodedChild);
}
return list;
}
private static Set<Object> decodeSet(Type targetType,
boolean restrictToInternalTypes, JSONArray jsonArray,
Application application) throws JSONException {
HashSet<Object> set = new HashSet<Object>();
set.addAll(decodeList(List.class, restrictToInternalTypes, jsonArray,
application));
return set;
}
/**
* Returns the name that should be used as field name in the JSON. We strip
* "set" from the setter, keeping the result - this is easy to do on both
* server and client, avoiding some issues with cASE. E.g setZIndex()
* becomes "ZIndex". Also ensures that both getter and setter are present,
* returning null otherwise.
*
* @param pd
* @return the name to be used or null if both getter and setter are not
* found.
*/
static String getTransportFieldName(PropertyDescriptor pd) {
if (pd.getReadMethod() == null || pd.getWriteMethod() == null) {
return null;
}
return pd.getWriteMethod().getName().substring(3);
}
private static Object decodeObject(Type targetType,
JSONObject serializedObject, Application application)
throws JSONException {
Class<?> targetClass = getClassForType(targetType);
if (Enum.class.isAssignableFrom(targetClass)) {
return decodeEnum(targetClass.asSubclass(Enum.class),
serializedObject);
}
try {
Object decodedObject = targetClass.newInstance();
for (PropertyDescriptor pd : Introspector.getBeanInfo(targetClass)
.getPropertyDescriptors()) {
String fieldName = getTransportFieldName(pd);
if (fieldName == null) {
continue;
}
Object encodedFieldValue = serializedObject.get(fieldName);
Type fieldType = pd.getReadMethod().getGenericReturnType();
Object decodedFieldValue = decodeInternalOrCustomType(
fieldType, encodedFieldValue, application);
pd.getWriteMethod().invoke(decodedObject, decodedFieldValue);
}
return decodedObject;
} catch (IllegalArgumentException e) {
throw new JSONException(e);
} catch (IllegalAccessException e) {
throw new JSONException(e);
} catch (InvocationTargetException e) {
throw new JSONException(e);
} catch (InstantiationException e) {
throw new JSONException(e);
} catch (IntrospectionException e) {
throw new JSONException(e);
}
}
public static Object encode(Object value, Object referenceValue,
Type valueType, Application application) throws JSONException {
if (valueType == null) {
throw new IllegalArgumentException("type must be defined");
}
if (null == value) {
return encodeNull();
}
if (value instanceof String[]) {
String[] array = (String[]) value;
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < array.length; ++i) {
jsonArray.put(array[i]);
}
return jsonArray;
} else if (value instanceof String) {
return value;
} else if (value instanceof Boolean) {
return value;
} else if (value instanceof Number) {
return value;
} else if (value instanceof Collection) {
Collection<?> collection = (Collection<?>) value;
JSONArray jsonArray = encodeCollection(valueType, collection,
application);
return jsonArray;
} else if (value instanceof Object[]) {
Object[] array = (Object[]) value;
JSONArray jsonArray = encodeArrayContents(array, application);
return jsonArray;
} else if (value instanceof Map) {
JSONObject jsonMap = encodeMap(valueType, (Map<?, ?>) value,
application);
return jsonMap;
} else if (value instanceof Connector) {
Connector connector = (Connector) value;
if (value instanceof Component
&& !(AbstractCommunicationManager
.isVisible((Component) value))) {
return encodeNull();
}
return connector.getConnectorId();
} else if (value instanceof Enum) {
return encodeEnum((Enum<?>) value, application);
} else {
// Any object that we do not know how to encode we encode by looping
// through fields
return encodeObject(value, referenceValue, application);
}
}
private static Object encodeNull() {
return JSONObject.NULL;
}
private static Object encodeObject(Object value, Object referenceValue,
Application application) throws JSONException {
JSONObject jsonMap = new JSONObject();
try {
for (PropertyDescriptor pd : Introspector.getBeanInfo(
value.getClass()).getPropertyDescriptors()) {
String fieldName = getTransportFieldName(pd);
if (fieldName == null) {
continue;
}
Method getterMethod = pd.getReadMethod();
// We can't use PropertyDescriptor.getPropertyType() as it does
// not support generics
Type fieldType = getterMethod.getGenericReturnType();
Object fieldValue = getterMethod.invoke(value, (Object[]) null);
boolean equals = false;
Object referenceFieldValue = null;
if (referenceValue != null) {
referenceFieldValue = getterMethod.invoke(referenceValue,
(Object[]) null);
equals = equals(fieldValue, referenceFieldValue);
}
if (!equals) {
jsonMap.put(
fieldName,
encode(fieldValue, referenceFieldValue, fieldType,
application));
// } else {
// System.out.println("Skipping field " + fieldName
// + " of type " + fieldType.getName()
// + " for object " + value.getClass().getName()
// + " as " + fieldValue + "==" + referenceFieldValue);
}
}
} catch (Exception e) {
// TODO: Should exceptions be handled in a different way?
throw new JSONException(e);
}
return jsonMap;
}
/**
* Compares the value with the reference. If they match, returns true.
*
* @param fieldValue
* @param referenceValue
* @return
*/
private static boolean equals(Object fieldValue, Object referenceValue) {
if (fieldValue == null) {
return referenceValue == null;
}
if (fieldValue.equals(referenceValue)) {
return true;
}
return false;
}
private static String encodeEnum(Enum<?> e, Application application)
throws JSONException {
return e.name();
}
private static JSONArray encodeArrayContents(Object[] array,
Application application) throws JSONException {
JSONArray jsonArray = new JSONArray();
for (Object o : array) {
jsonArray.put(encode(o, null, null, application));
}
return jsonArray;
}
private static JSONArray encodeCollection(Type targetType,
Collection collection, Application application)
throws JSONException {
JSONArray jsonArray = new JSONArray();
for (Object o : collection) {
jsonArray.put(encodeChild(targetType, 0, o, application));
}
return jsonArray;
}
private static Object encodeChild(Type targetType, int typeIndex, Object o,
Application application) throws JSONException {
if (targetType instanceof ParameterizedType) {
Type childType = ((ParameterizedType) targetType)
.getActualTypeArguments()[typeIndex];
// Encode using the given type
return encode(o, null, childType, application);
} else {
throw new JSONException("Collection is missing generics");
}
}
private static JSONObject encodeMap(Type mapType, Map<?, ?> map,
Application application) throws JSONException {
Type keyType, valueType;
if (mapType instanceof ParameterizedType) {
keyType = ((ParameterizedType) mapType).getActualTypeArguments()[0];
valueType = ((ParameterizedType) mapType).getActualTypeArguments()[1];
} else {
throw new JSONException("Map is missing generics");
}
JSONObject jsonMap = new JSONObject();
for (Object mapKey : map.keySet()) {
Object mapValue = map.get(mapKey);
Object encodedKey = encode(mapKey, null, keyType, application);
Object encodedValue = encode(mapValue, null, valueType, application);
jsonMap.put(JSONObject.quote(encodedKey.toString()), encodedValue);
}
return jsonMap;
}
/**
* Gets the transport type for the given class. Returns null if no transport
* type can be found.
*
* @param valueType
* The type that should be transported
* @return
* @throws JSONException
*/
private static String getInternalTransportType(Type valueType) {
return typeToTransportType.get(getClassForType(valueType));
}
private static String getCustomTransportType(Class<?> targetType) {
return targetType.getName();
}
}
|