/
Beany.java
590 lines (460 loc) · 15.4 KB
/
Beany.java
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
package org.rapidoid.beany;
import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.annotation.ToString;
import org.rapidoid.annotation.Transient;
import org.rapidoid.cls.Cls;
import org.rapidoid.cls.TypeKind;
import org.rapidoid.collection.Coll;
import org.rapidoid.commons.Dates;
import org.rapidoid.lambda.Mapper;
import org.rapidoid.log.Log;
import org.rapidoid.u.U;
import org.rapidoid.var.Var;
import org.rapidoid.var.Vars;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.Map.Entry;
/*
* #%L
* rapidoid-commons
* %%
* Copyright (C) 2014 - 2017 Nikolche Mihajlovski and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
@Authors("Nikolche Mihajlovski")
@Since("2.0.0")
public class Beany extends RapidoidThing {
private static final String GETTER = "^(get|is)[A-Z].*";
private static final String SETTER = "^set[A-Z].*";
protected static final Map<Class<?>, BeanProperties> BEAN_PROPERTIES = Coll
.autoExpandingMap(new Mapper<Class<?>, BeanProperties>() {
@Override
public BeanProperties map(Class<?> clazz) throws Exception {
Map<String, BeanProp> properties = new LinkedHashMap<String, BeanProp>();
getBeanProperties(clazz, properties);
for (Entry<String, BeanProp> e : properties.entrySet()) {
e.getValue().init();
}
return new BeanProperties(properties);
}
});
private static void getBeanProperties(Class<?> clazz, Map<String, BeanProp> properties) {
if (clazz == null || clazz == Object.class) {
return;
} else {
getBeanProperties(clazz.getSuperclass(), properties);
for (Class<?> interf : clazz.getInterfaces()) {
getBeanProperties(interf, properties);
}
}
if (Proxy.isProxyClass(clazz)) {
return;
}
try {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
int modif = method.getModifiers();
Class<?>[] params = method.getParameterTypes();
Class<?> ret = method.getReturnType();
String name = method.getName();
if (!name.startsWith("_") && !name.contains("$")
&& !Modifier.isPrivate(modif) && !Modifier.isProtected(modif) && !Modifier.isStatic(modif)
&& !method.isAnnotationPresent(Transient.class)) {
if ((name.matches(GETTER) && params.length == 0) || (name.matches(SETTER) && params.length == 1)) {
String propName;
if (name.startsWith("is")) {
propName = name.substring(2, 3).toLowerCase() + name.substring(3);
} else {
propName = name.substring(3, 4).toLowerCase() + name.substring(4);
}
BeanProp prop = properties.get(propName);
if (prop == null) {
prop = new BeanProp(propName);
properties.put(propName, prop);
}
if (name.startsWith("set")) {
prop.setSetter(method);
prop.setReadOnly(false);
} else {
prop.setGetter(method);
}
} else if (!name.matches("^to[A-Z].*") && !name.equals("hashCode")) {
if (params.length == 0 && !ret.equals(void.class)) {
String propName = name;
BeanProp prop = properties.get(propName);
if (prop == null) {
prop = new BeanProp(propName);
properties.put(propName, prop);
}
prop.setGetter(method);
} else if (params.length == 1) {
String propName = name;
BeanProp prop = properties.get(propName);
if (prop == null) {
prop = new BeanProp(propName);
properties.put(propName, prop);
}
prop.setReadOnly(false);
prop.setSetter(method);
}
}
}
}
// remove properties with setters, without getters
for (Iterator<Entry<String, BeanProp>> it = properties.entrySet().iterator(); it.hasNext(); ) {
Entry<String, BeanProp> entry = it.next();
BeanProp minfo = entry.getValue();
if (minfo.getGetter() == null && minfo.getSetter() != null) {
it.remove();
}
}
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
int modif = field.getModifiers();
if (!Modifier.isPrivate(modif) && !Modifier.isProtected(modif) && !Modifier.isStatic(modif)) {
String fieldName = field.getName();
if (!fieldName.startsWith("_") && !fieldName.contains("$")
&& !field.isAnnotationPresent(Transient.class)) {
BeanProp prop = properties.get(fieldName);
if (prop == null) {
prop = new BeanProp(fieldName, field, (modif & Modifier.FINAL) != 0);
properties.put(fieldName, prop);
}
}
}
}
} catch (Exception e) {
throw U.rte(e);
}
}
public static void reset() {
BEAN_PROPERTIES.clear();
}
public static BeanProperties propertiesOf(Class<?> clazz) {
return BEAN_PROPERTIES.get(clazz);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static BeanProperties propertiesOf(Object obj) {
if (obj == null) {
return BeanProperties.NONE;
} else if (obj instanceof Map) {
return BeanProperties.from(((Map) obj));
} else if (obj instanceof Class) {
return propertiesOf((Class) obj);
} else {
return propertiesOf(obj.getClass());
}
}
public static Prop property(Class<?> clazz, String property, boolean mandatory) {
Prop prop = BEAN_PROPERTIES.get(clazz).get(property);
if (prop == null && JSProp.is(property)) {
prop = new JSProp(property);
}
if (prop == null && ActionsProp.is(property)) {
prop = new ActionsProp();
}
if (mandatory && prop == null) {
throw U.rte("Cannot find the property '%s' in the class '%s'", property, clazz);
}
return prop;
}
public static Object serialize(Object value) {
if (Cls.kindOf(value) != TypeKind.UNKNOWN || value instanceof Enum) {
return value;
} else if (value instanceof Var<?>) {
Var<?> var = (Var<?>) value;
return serialize(U.map(var.name(), var.get()));
} else if (value instanceof Set) {
Set<Object> set = U.set();
for (Object item : ((Set<?>) value)) {
set.add(serialize(item));
}
return set;
} else if (value instanceof List) {
List<Object> list = U.list();
for (Object item : ((List<?>) value)) {
list.add(serialize(item));
}
return list;
} else if (value instanceof Object[]) {
Object[] vals = (Object[]) value;
Object[] arr = new Object[vals.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = serialize(vals[i]);
}
return arr;
} else if (value instanceof Map) {
Map<Object, Object> map = U.map();
for (Entry<?, ?> e : ((Map<?, ?>) value).entrySet()) {
map.put(serialize(e.getKey()), serialize(e.getValue()));
}
return map;
} else if (value.getClass().isArray()) {
// a primitive array
return value;
} else {
return read(value);
}
}
public static Map<String, Object> read(Object bean) {
Map<String, Object> props = U.map();
read(bean, props);
return props;
}
public static void read(Object bean, Map<String, Object> dest) {
U.notNull(bean, "bean");
U.must(!(bean instanceof Collection));
U.must(!bean.getClass().isArray());
U.must(!bean.getClass().isEnum());
U.must(Cls.kindOf(bean) == TypeKind.UNKNOWN);
for (Prop prop : propertiesOf(bean)) {
Object value = prop.getRaw(bean);
if (value instanceof SerializableBean<?>) {
SerializableBean<?> ser = (SerializableBean<?>) value;
value = ser.serializeBean();
} else {
value = serialize(unwrap(value));
}
dest.put(prop.getName(), value);
}
}
public static void bind(Object destBean, Map<String, ?> src) {
Method bind = Cls.findMethod(destBean.getClass(), "bind", Map.class);
if (bind != null) {
Cls.invoke(bind, destBean, src);
} else {
update(destBean, src, false, false);
}
}
public static void update(Object destBean, Map<String, ?> src) {
update(destBean, src, false, false);
}
public static void update(Object destBean, Map<String, ?> src, boolean ignoreNullValues) {
update(destBean, src, ignoreNullValues, false);
}
@SuppressWarnings("unchecked")
public static void update(Object destBean, Map<String, ?> src, boolean ignoreNullValues,
boolean ignoreReadOnlyProperties) {
if (destBean instanceof Map) {
((Map<String, Object>) destBean).putAll(src);
return;
}
for (Prop prop : propertiesOf(destBean)) {
Object value = src.get(prop.getName());
if (ignoreReadOnlyProperties && prop.isReadOnly()) {
continue;
}
if (value == null) {
// differentiate non-existing entries from existing entries with null value
if (ignoreNullValues || !src.containsKey(prop.getName())) {
continue;
}
}
Object propValue = prop.getRaw(destBean);
if (propValue != null && propValue instanceof SerializableBean) {
SerializableBean<Object> ser = (SerializableBean<Object>) propValue;
ser.deserializeBean(value);
} else {
prop.set(destBean, value);
}
}
}
@SuppressWarnings("rawtypes")
public static Prop property(Object obj, String property, boolean mandatory) {
if (obj instanceof Map) {
Object value = ((Map) obj).get(property);
return new MapProp(property, property, Cls.of(value));
} else {
return property(obj.getClass(), property, mandatory);
}
}
public static boolean hasProperty(Class<?> clazz, String property) {
return property(clazz, property, false) != null;
}
public static boolean hasProperty(Object obj, String property) {
return property(obj, property, false) != null;
}
@SuppressWarnings("unchecked")
public static void setPropValue(Object instance, String propertyName, Object value) {
if (instance instanceof Map) {
((Map<Object, Object>) instance).put(propertyName, value);
} else {
property(instance, propertyName, true).set(instance, value);
}
}
@SuppressWarnings("unchecked")
public static <T> T getPropValue(Object instance, String propertyName, T defaultValue) {
if (instance instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) instance;
return (T) (map.containsKey(propertyName) ? map.get(propertyName) : defaultValue);
} else {
Prop prop = property(instance, propertyName, false);
return prop != null ? (T) prop.get(instance) : defaultValue;
}
}
@SuppressWarnings("unchecked")
public static <T> T getPropValue(Object instance, String propertyName) {
if (instance instanceof Map<?, ?>) {
Map<?, ?> map = (Map<?, ?>) instance;
U.must(map.containsKey(propertyName), "The map must contain key: %s", propertyName);
return (T) map.get(propertyName);
} else {
return property(instance.getClass(), propertyName, true).get(instance);
}
}
public static <T> T getPropValueOfType(Object obj, String property, Class<T> returnType) {
T value = getPropValueOfType(obj, property, returnType, null);
if (value == null) {
throw U.rte("The property '%s' cannot be null!", property);
}
return value;
}
public static <T> T getPropValueOfType(Object obj, String property, Class<T> returnType, T defaultValue) {
Object id = getPropValue(obj, property, null);
return id != null ? Cls.convert(id, returnType) : defaultValue;
}
public static void setId(Object obj, Object id) {
setPropValue(obj, "id", id);
}
public static void setId(Object obj, long id) {
setId(obj, "" + id);
}
public static Object getId(Object obj) {
return getPropValueOfType(obj, "id", Object.class);
}
public static long getLongId(Object obj) {
return getPropValueOfType(obj, "id", Long.class);
}
public static Object getIdIfExists(Object obj) {
return getPropValueOfType(obj, "id", Object.class, null);
}
public static Long getLongIdIfExists(Object obj) {
return getPropValueOfType(obj, "id", Long.class, null);
}
public static Object[] getIds(Object... objs) {
Object[] ids = new String[objs.length];
for (int i = 0; i < objs.length; i++) {
ids[i] = getId(objs[i]);
}
return ids;
}
public static String beanToStr(Object bean, boolean allowCustom) {
Class<?> clazz = Cls.unproxy(bean.getClass());
if (allowCustom) {
Method m = Cls.getMethod(clazz, "toString");
if (!m.getDeclaringClass().equals(Object.class)) {
return bean.toString();
}
}
BeanProperties props = propertiesOf(bean).annotated(ToString.class);
if (props.isEmpty()) {
Prop nameProp = property(bean, "name", false);
if (nameProp != null && nameProp.getType() == String.class) {
return U.safe((String) nameProp.get(bean));
}
props = propertiesOf(bean);
}
StringBuilder sb = new StringBuilder();
for (Prop prop : props) {
String name = prop.getName();
Object value = prop.get(bean);
if (sb.length() > 0) {
sb.append(", ");
}
if (prop.getTypeKind() == TypeKind.UNKNOWN) {
value = value == bean ? "[this]" : "[obj]";
}
if (value instanceof Date) {
Date date = (Date) value;
value = Dates.str(date);
}
sb.append(name);
sb.append(": ");
sb.append(value);
}
return sb.toString();
}
public static String beanToNiceText(Object bean, boolean allowCustom) {
Class<?> clazz = Cls.unproxy(bean.getClass());
if (allowCustom) {
Method m = Cls.getMethod(clazz, "toString");
if (!m.getDeclaringClass().equals(Object.class)) {
return bean.toString();
}
}
BeanProperties props = propertiesOf(bean).annotated(ToString.class);
if (props.isEmpty()) {
Prop nameProp = property(bean, "name", false);
if (nameProp != null && nameProp.getType() == String.class) {
return U.safe((String) nameProp.get(bean));
}
props = propertiesOf(bean);
}
StringBuilder sb = new StringBuilder();
for (Prop prop : props) {
String name = prop.getName();
Object value = prop.get(bean);
if (value != null && prop.getTypeKind() != TypeKind.UNKNOWN && prop.getTypeKind() != TypeKind.DATE) {
if (sb.length() > 0) {
sb.append(", ");
}
if (!(value instanceof String)) {
sb.append(name);
sb.append(": ");
}
sb.append(value);
}
}
return sb.toString();
}
public static <E> Comparator<E> comparator(final String orderBy) {
final int sign = orderBy.startsWith("-") ? -1 : 1;
final String order = sign == 1 ? orderBy : orderBy.substring(1);
Comparator<E> comparator = new Comparator<E>() {
@Override
public int compare(E o1, E o2) {
try {
E val1 = getPropValue(o1, order);
E val2 = getPropValue(o2, order);
U.must(val1 == null || val1 instanceof Comparable, "The property '%s' (%s) is not comparable!",
order, Cls.of((val1)));
U.must(val2 == null || val2 instanceof Comparable, "The property '%s' (%s) is not comparable!",
order, Cls.of((val2)));
return sign * U.compare(val1, val2);
} catch (Exception e) {
Log.error("Cannot compare values by: " + orderBy, e);
return 0;
}
}
};
return comparator;
}
@SuppressWarnings("unchecked")
public static <FROM, TO> List<TO> projection(Collection<FROM> coll, String propertyName) {
List<TO> projection = U.list();
for (FROM item : coll) {
projection.add((TO) getPropValue(item, propertyName));
}
return projection;
}
public static Object unwrap(Object value) {
return Vars.unwrap(value);
}
}