forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParamValueLoaderService.java
More file actions
833 lines (763 loc) · 32.1 KB
/
ParamValueLoaderService.java
File metadata and controls
833 lines (763 loc) · 32.1 KB
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
package act.inject.param;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* 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%
*/
import act.Act;
import act.app.ActionContext;
import act.app.App;
import act.app.data.BinderManager;
import act.app.data.StringValueResolverManager;
import act.controller.ActionMethodParamAnnotationHandler;
import act.db.AdaptiveRecord;
import act.db.DbBind;
import act.db.di.FindBy;
import act.inject.DefaultValue;
import act.inject.DependencyInjector;
import act.inject.SessionVariable;
import act.inject.genie.DependentScope;
import act.inject.genie.GenieInjector;
import act.inject.genie.RequestScope;
import act.inject.genie.SessionScope;
import act.util.*;
import org.osgl.$;
import org.osgl.Lang;
import org.osgl.OsglConfig;
import org.osgl.exception.UnexpectedException;
import org.osgl.inject.BeanSpec;
import org.osgl.inject.InjectException;
import org.osgl.inject.util.AnnotationUtil;
import org.osgl.inject.util.ArrayLoader;
import org.osgl.logging.LogManager;
import org.osgl.logging.Logger;
import org.osgl.mvc.annotation.Bind;
import org.osgl.mvc.annotation.Param;
import org.osgl.mvc.result.Result;
import org.osgl.mvc.util.Binder;
import org.osgl.util.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.New;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.validation.*;
import javax.validation.executable.ExecutableValidator;
/**
* Manage {@link ParamValueLoader} grouped by Method
*/
public abstract class ParamValueLoaderService extends DestroyableBase {
protected Logger logger = LogManager.get(getClass());
private static final ParamValueLoader[] DUMB = new ParamValueLoader[0];
private static final ThreadLocal<ParamTree> PARAM_TREE = new ThreadLocal<ParamTree>();
private static final ParamValueLoader RESULT_LOADER = new ParamValueLoader() {
@Override
public Object load(Object bean, ActContext<?> context, boolean noDefaultValue) {
return ((ActionContext)context).result();
}
@Override
public String bindName() {
return null;
}
};
private static class ThrowableLoader implements ParamValueLoader {
private Class<? extends Throwable> throwableType;
public ThrowableLoader(Class<? extends Throwable> throwableType) {
this.throwableType = throwableType;
}
@Override
public Object load(Object bean, ActContext<?> context, boolean noDefaultValue) {
Object o = context.attribute(ActionContext.ATTR_EXCEPTION);
return throwableType.isInstance(o) ? o : null;
}
@Override
public String bindName() {
return null;
}
}
// contains field names that should be waived when looking for value loader
private static final Set<String> fieldBlackList = new HashSet<>();
protected StringValueResolverManager resolverManager;
protected BinderManager binderManager;
protected GenieInjector injector;
ConcurrentMap<Method, ParamValueLoader[]> methodRegistry = new ConcurrentHashMap<>();
Map<Method, Boolean> methodValidationConstraintLookup = new HashMap();
ConcurrentMap<Class, Map<Field, ParamValueLoader>> fieldRegistry = new ConcurrentHashMap<>();
ConcurrentMap<Class, ParamValueLoader> classRegistry = new ConcurrentHashMap<>();
private ConcurrentMap<$.T2<Type, Annotation[]>, ParamValueLoader> paramRegistry = new ConcurrentHashMap<>();
private ConcurrentMap<BeanSpec, Map<Class<? extends Annotation>, ActionMethodParamAnnotationHandler>> annoHandlers = new ConcurrentHashMap<>();
private Map<Class<? extends Annotation>, ActionMethodParamAnnotationHandler> allAnnotationHandlers;
private Validator validator;
private volatile ExecutableValidator executableValidator;
public ParamValueLoaderService(App app) {
resolverManager = app.resolverManager();
binderManager = app.binderManager();
injector = app.injector();
allAnnotationHandlers = new HashMap<>();
List<ActionMethodParamAnnotationHandler> list = Act.pluginManager().pluginList(ActionMethodParamAnnotationHandler.class);
for (ActionMethodParamAnnotationHandler h : list) {
Set<Class<? extends Annotation>> set = h.listenTo();
for (Class<? extends Annotation> c : set) {
allAnnotationHandlers.put(c, h);
}
}
}
@Override
protected void releaseResources() {
DestroyableBase.Util.tryDestroyAll(classRegistry.values(), ApplicationScoped.class);
DestroyableBase.Util.tryDestroyAll(paramRegistry.values(), ApplicationScoped.class);
noBindCache.clear();
}
public Object loadHostBean(Class beanClass, ActContext<?> ctx) {
ParamValueLoader loader = classRegistry.get(beanClass);
if (null == loader) {
ParamValueLoader newLoader = findBeanLoader(beanClass);
loader = classRegistry.putIfAbsent(beanClass, newLoader);
if (null == loader) {
loader = newLoader;
}
}
return loader.load(null, ctx, false);
}
public ParamValueLoader[] methodParamLoaders(Object host, Method method, ActContext ctx) {
ParamValueLoader[] loaders = methodRegistry.get(method);
if (null == loaders) {
$.Var<Boolean> boolBag = $.var(Boolean.FALSE);
Class hostClass = null == host ? null : host.getClass();
ParamValueLoader[] newLoaders = findMethodParamLoaders(method, hostClass, ctx, boolBag);
loaders = methodRegistry.putIfAbsent(method, newLoaders);
if (null == loaders) {
loaders = newLoaders;
}
boolean hasValidationConstraint = boolBag.get();
if (hasValidationConstraint && null == host) {
logger.error("Cannot validate static method: %s", method);
hasValidationConstraint = false;
}
methodValidationConstraintLookup.put(method, hasValidationConstraint);
}
return loaders;
}
public Object[] loadMethodParams(Object host, Method method, ActContext ctx) {
try {
ParamValueLoader[] loaders = methodParamLoaders(host, method, ctx);
Boolean hasValidationConstraint = methodValidationConstraintLookup.get(method);
int sz = loaders.length;
Object[] params = new Object[sz];
for (int i = 0; i < sz; ++i) {
params[i] = loaders[i].load(null, ctx, false);
}
if (null != hasValidationConstraint && hasValidationConstraint) {
Set<ConstraintViolation> violations = $.cast(executableValidator().validateParameters(host, method, params));
if (!violations.isEmpty()) {
Map<String, ConstraintViolation> map = new HashMap<>();
for (ConstraintViolation v : violations) {
S.Buffer buf = S.buffer();
for (Path.Node node : v.getPropertyPath()) {
if (node.getKind() == ElementKind.METHOD) {
continue;
} else if (node.getKind() == ElementKind.PARAMETER) {
Path.ParameterNode pnode = node.as(Path.ParameterNode.class);
int paramIdx = pnode.getParameterIndex();
ParamValueLoader ploader = loaders[paramIdx];
buf.append(ploader.bindName());
} else if (node.getKind() == ElementKind.PROPERTY) {
buf.append(".").append(node.toString());
}
}
map.put(buf.toString(), v);
}
ctx.addViolations(map);
}
}
return params;
} finally {
PARAM_TREE.remove();
}
}
protected <T> ParamValueLoader findBeanLoader(Class<T> beanClass) {
final Provider<T> provider = injector.getProvider(beanClass);
final Map<Field, ParamValueLoader> loaders = fieldLoaders(beanClass);
final boolean hasField = !loaders.isEmpty();
final $.Var<Boolean> hasValidateConstraint = $.var();
ParamValueLoader loader = new ParamValueLoader() {
@Override
public Object load(Object bean, ActContext<?> context, boolean noDefaultValue) {
if (null == bean) {
bean = provider.get();
}
if (!hasField) {
return bean;
}
try {
for (Map.Entry<Field, ParamValueLoader> entry : loaders.entrySet()) {
Field field = entry.getKey();
ParamValueLoader loader = entry.getValue();
Object fieldValue = loader.load(null, context, noDefaultValue);
if (null != fieldValue) {
field.set(bean, fieldValue);
} else {
fieldValue = field.get(bean);
}
if (hasValidationConstraint(BeanSpec.of(field, injector))) {
hasValidateConstraint.set(true);
}
}
} catch (IllegalAccessException e) {
throw new InjectException(e);
}
return bean;
}
@Override
public String bindName() {
return null;
}
};
return decorate(loader, BeanSpec.of(beanClass, injector), false, true);
}
public static boolean shouldWaive(Field field) {
int modifiers = field.getModifiers();
if (Modifier.isTransient(modifiers) || Modifier.isStatic(modifiers)) {
return true;
}
String fieldName = field.getName();
return noBind(field.getDeclaringClass())
|| field.isAnnotationPresent(NoBind.class)
|| field.isAnnotationPresent(Stateless.class)
|| field.isAnnotationPresent(Global.class)
|| fieldBlackList.contains(fieldName)
|| Object.class.equals(field.getDeclaringClass())
|| OsglConfig.globalMappingFilter_shouldIgnore(fieldName);
}
private static ConcurrentMap<Class, Boolean> noBindCache;
public static void classInit(App app) {
noBindCache = app.createConcurrentMap();
}
private static boolean noBind(Class c) {
Boolean b = noBindCache.get(c);
if (null != b) {
return b;
}
if (SingletonBase.class.isAssignableFrom(c)
|| c.isAnnotationPresent(NoBind.class)
|| c.isAnnotationPresent(Stateless.class)
|| c.isAnnotationPresent(Singleton.class)) {
noBindCache.putIfAbsent(c, true);
return true;
}
return false;
}
private <T> Map<Field, ParamValueLoader> fieldLoaders(Class<T> beanClass) {
Map<Field, ParamValueLoader> fieldLoaders = fieldRegistry.get(beanClass);
if (null == fieldLoaders) {
Map<Field, ParamValueLoader> newFieldLoaders = new HashMap<>();
for (Field field : $.fieldsOf(beanClass, true)) {
if (shouldWaive(field)) {
continue;
}
BeanSpec spec = BeanSpec.of(field, injector);
ParamValueLoader loader = paramValueLoaderOf(spec, null);
boolean provided = (loader instanceof ProvidedValueLoader);
if (null != loader && !provided) {
newFieldLoaders.put(field, loader);
}
}
fieldLoaders = fieldRegistry.putIfAbsent(beanClass, newFieldLoaders);
if (null == fieldLoaders) {
fieldLoaders = newFieldLoaders;
}
}
return fieldLoaders;
}
protected ParamValueLoader[] findMethodParamLoaders(
Method method, Class host,
ActContext ctx, $.Var<Boolean> hasValidationConstraint) {
Type[] types = method.getGenericParameterTypes();
int sz = types.length;
if (0 == sz) {
return DUMB;
}
ParamValueLoader[] loaders = new ParamValueLoader[sz];
Annotation[][] annotations = method.getParameterAnnotations();
for (int i = 0; i < sz; ++i) {
String name = paramName(i);
Type type = types[i];
if (type instanceof TypeVariable) {
TypeVariable var = $.cast(type);
if (null != host) {
type = Generics.buildTypeParamImplLookup(host).get(var.getName());
}
if (null == type) {
throw new UnexpectedException("Cannot infer param type: %s", var.getName());
}
}
BeanSpec spec = BeanSpec.of(type, annotations[i], name, injector);
if (hasValidationConstraint(spec)) {
hasValidationConstraint.set(true);
}
ParamValueLoader loader = paramValueLoaderOf(spec, ctx);
if (null == loader) {
throw new UnexpectedException("Cannot find param value loader for param: " + spec);
}
loaders[i] = loader;
}
return loaders;
}
private ParamValueLoader paramValueLoaderOf(BeanSpec spec, ActContext ctx) {
return paramValueLoaderOf(spec, null, ctx);
}
private ParamValueLoader paramValueLoaderOf(BeanSpec spec, String bindName, ActContext ctx) {
Class<?> rawType = spec.rawType();
if (Result.class.isAssignableFrom(rawType)) {
return RESULT_LOADER;
} else if (Throwable.class.isAssignableFrom(rawType)) {
return new ThrowableLoader((Class<? extends Throwable>)rawType);
} else if (Annotation.class.isAssignableFrom(rawType)) {
return findHandlerMethodAnnotation((Class<? extends Annotation>) rawType, ctx);
}
Type type = spec.type();
Annotation[] annotations = spec.allAnnotations();
$.T2<Type, Annotation[]> key = $.T2(type, annotations);
ParamValueLoader loader = paramRegistry.get(key);
if (null == loader) {
ParamValueLoader newLoader = findLoader(bindName, spec);
if (null != newLoader) {
// Cannot use spec as the key here because
// spec does not compare Scoped annotation
loader = paramRegistry.putIfAbsent(key, newLoader);
if (null == loader) {
loader = newLoader;
}
}
}
return loader;
}
/**
* Returns a `ParamValueLoader` that load annotation from:
* * the handler method
* * the current method (might be a intercepter method)
*
* @param annoType the annotation type
* @param ctx the current {@link ActContext}
* @return a `ParamValueLoader` instance
*/
private ParamValueLoader findHandlerMethodAnnotation(final Class<? extends Annotation> annoType, ActContext<?> ctx) {
if (null == ctx) {
return ParamValueLoader.NIL;
}
return new ParamValueLoader() {
@Override
public Object load(Object bean, ActContext<?> ctx, boolean noDefaultValue) {
Method handlerMethod = ctx.handlerMethod();
Method curMethod = ctx.currentMethod();
boolean methodIsCurrent = handlerMethod == curMethod || null == curMethod;
Annotation anno = handlerMethod.getAnnotation(annoType);
if (null == anno && !methodIsCurrent) {
anno = curMethod.getAnnotation(annoType);
}
return anno;
}
@Override
public String bindName() {
return null;
}
};
}
protected abstract ParamValueLoader findContextSpecificLoader(
String bindName,
BeanSpec spec
);
protected final ParamValueLoader binder(BeanSpec spec, String bindName) {
Class rawType = spec.rawType();
ParamValueLoader loader = null;
{
Bind bind = spec.getAnnotation(Bind.class);
if (null != bind) {
for (Class<? extends Binder> binderClass : bind.value()) {
Binder binder = injector.get(binderClass);
if (rawType.isAssignableFrom(binder.targetType())) {
loader = new BoundedValueLoader(binder, bindName);
break;
}
}
}
}
if (null == loader) {
Annotation[] aa = spec.taggedAnnotations(Bind.class);
if (aa.length > 0) {
for (Annotation a: aa) {
Bind bind = AnnotationUtil.tagAnnotation(a, Bind.class);
for (Class<? extends Binder> binderClass : bind.value()) {
Binder binder = injector.get(binderClass);
binder.attributes($.evaluate(a));
if (rawType.isAssignableFrom(binder.targetType())) {
loader = new BoundedValueLoader(binder, bindName);
break;
}
}
}
}
}
if (null == loader) {
Binder binder = binderManager.binder(rawType);
if (null != binder) {
loader = new BoundedValueLoader(binder, bindName);
}
}
return loader;
}
protected String paramName(int i) {
return null;
}
protected boolean supportJsonDecorator() {
return false;
}
private ParamValueLoader findLoader(
String bindName,
BeanSpec spec
) {
if (provided(spec, injector)) {
return ProvidedValueLoader.get(spec, injector);
}
if (spec.hasAnnotation(NoBind.class)) {
return null;
}
if (null == bindName) {
bindName = bindName(spec.allAnnotations(), spec.name());
}
ParamValueLoader loader = findContextSpecificLoader(bindName, spec);
if (null == loader) {
return null;
}
return decorate(loader, spec, supportJsonDecorator(), false);
}
ParamValueLoader buildLoader(final ParamKey key, BeanSpec spec) {
Type type = spec.type();
Class rawType = spec.rawType();
if (rawType.isArray()) {
return buildArrayLoader(key, rawType.getComponentType(), spec);
}
if (Collection.class.isAssignableFrom(rawType)) {
Type elementType = Object.class;
if (type instanceof ParameterizedType) {
elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
}
return buildCollectionLoader(key, rawType, elementType, spec);
}
if (Map.class.isAssignableFrom(rawType)) {
Class<?> mapClass = rawType;
Type mapType = type;
boolean canProceed = false;
Type[] typeParams = null;
while (true) {
if (mapType instanceof ParameterizedType) {
typeParams = ((ParameterizedType) mapType).getActualTypeArguments();
if (typeParams.length == 2) {
canProceed = true;
break;
}
}
boolean foundInInterfaces = false;
Type[] ta = mapClass.getGenericInterfaces();
if (ta.length > 0) {
mapType = null;
for (Type t : ta) {
if (t instanceof ParameterizedType) {
if (Map.class.isAssignableFrom((Class) ((ParameterizedType) t).getRawType())) {
mapType = t;
mapClass = mapClass.getSuperclass();
foundInInterfaces = true;
break;
}
}
}
}
if (!foundInInterfaces) {
mapType = mapClass.getGenericSuperclass();
mapClass = mapClass.getSuperclass();
}
if (mapClass == Object.class) {
break;
}
}
E.unexpectedIf(!canProceed, "Cannot load Map type parameter loader: no generic type info available");
Type keyType = typeParams[0];
Type valType = typeParams[1];
return buildMapLoader(key, rawType, keyType, valType, spec);
}
if (AdaptiveRecord.class.isAssignableFrom(rawType)) {
return buildAdaptiveRecordLoader(key, spec);
}
return buildPojoLoader(key, spec);
}
private ParamValueLoader buildArrayLoader(
final ParamKey key,
final Type elementType,
final BeanSpec targetSpec
) {
final CollectionLoader collectionLoader = new CollectionLoader(key, ArrayList.class, elementType, targetSpec, injector, this);
return new ParamValueLoader() {
@Override
public Object load(Object bean, ActContext<?> context, boolean noDefaultValue) {
List list = new ArrayList();
if (null != bean) {
int len = Array.getLength(bean);
for (int i = 0; i < len; ++i) {
list.add(Array.get(bean, i));
}
}
list = (List) collectionLoader.load(list, context, false);
return null == list ? null : ArrayLoader.listToArray(list, BeanSpec.rawTypeOf(elementType));
}
@Override
public String bindName() {
return key.toString();
}
};
}
private ParamValueLoader buildCollectionLoader(
final ParamKey key,
final Class<? extends Collection> collectionClass,
final Type elementType,
BeanSpec targetSpec
) {
return new CollectionLoader(key, collectionClass, elementType, targetSpec, injector, this);
}
private ParamValueLoader buildMapLoader(
final ParamKey key,
final Class<? extends Map> mapClass,
final Type keyType,
final Type valType,
final BeanSpec targetSpec
) {
return new MapLoader(key, mapClass, keyType, valType, targetSpec, injector, this);
}
private ParamValueLoader buildAdaptiveRecordLoader(
final ParamKey key, final BeanSpec spec) {
return new AdaptiveRecordLoader(key, spec, this);
}
static ParamTree paramTree() {
return PARAM_TREE.get();
}
static ParamTree ensureParamTree(ActContext context) {
ParamTree tree = PARAM_TREE.get();
if (null == tree) {
tree = new ParamTree();
tree.build(context);
PARAM_TREE.set(tree);
}
return tree;
}
private ParamValueLoader buildPojoLoader(final ParamKey key, final BeanSpec spec) {
return new PojoLoader(key, spec, this);
}
private ParamValueLoader findLoader(ParamKey paramKey, BeanSpec spec) {
if (provided(spec, injector)) {
return ProvidedValueLoader.get(spec, injector);
}
String name = spec.name();
ParamKey key = paramKey.child(name);
ParamValueLoader loader = binder(spec, key.toString());
if (null != loader) {
return loader;
}
Class fieldType = spec.rawType();
StringValueResolver resolver = resolverManager.resolver(fieldType, spec);
if (null != resolver) {
DefaultValue def = spec.getAnnotation(DefaultValue.class);
return new StringValueResolverValueLoader(key, resolver, null, def, fieldType);
}
return buildLoader(key, spec);
}
FieldLoader fieldLoader(ParamKey key, Field field, BeanSpec fieldSpec) {
if (field.isAnnotationPresent(ManyToOne.class) || field.isAnnotationPresent(OneToOne.class)) {
final FindBy findBy = new FindBy();
Map map = new HashMap<>();
map.put("byId", true);
findBy.init(map, BeanSpec.of(field, Act.injector()));
Lang.TypeConverter<Object, Object> converter = new Lang.TypeConverter<Object, Object>() {
@Override
public Object convert(Object s) {
findBy.setOnetimeValue(S.string(s));
return findBy.get();
}
};
return new FieldLoader(field, findLoader(key, fieldSpec), findLoader(key, BeanSpec.of(String.class, new Annotation[]{}, fieldSpec.name(), fieldSpec.injector())), converter);
}
return new FieldLoader(field, findLoader(key, fieldSpec));
}
static <T extends Annotation> T filter(Annotation[] annotations, Class<T> annoType) {
for (Annotation annotation : annotations) {
if (annoType == annotation.annotationType()) {
return (T) annotation;
}
}
return null;
}
private ParamValueLoader decorate(
final ParamValueLoader loader,
final BeanSpec spec,
boolean useJsonDecorator,
boolean useValidationDecorator
) {
final ParamValueLoader jsonDecorated = useJsonDecorator ? new JsonParamValueLoader(loader, spec, injector) : loader;
ParamValueLoader validationDecorated = jsonDecorated;
if (useValidationDecorator) {
validationDecorated = new ParamValueLoader() {
private Validator validator = Act.app().getInstance(Validator.class);
@Override
public Object load(Object bean, ActContext<?> context, boolean noDefaultValue) {
Object object = jsonDecorated.load(bean, context, noDefaultValue);
Set<ConstraintViolation> violations = $.cast(validator.validate(object));
if (!violations.isEmpty()) {
Map<String, ConstraintViolation> map = new HashMap<>();
for (ConstraintViolation v : violations) {
map.put(v.getPropertyPath().toString(), v);
}
context.addViolations(map);
}
return object;
}
@Override
public String bindName() {
return jsonDecorated.bindName();
}
};
}
return new ScopedParamValueLoader(validationDecorated, spec, scopeCacheSupport(spec));
}
private boolean hasValidationConstraint(BeanSpec spec) {
for (Annotation anno : spec.allAnnotations()) {
Class<? extends Annotation> annoType = anno.annotationType();
if (Valid.class == annoType || annoType.isAnnotationPresent(Constraint.class)) {
return true;
}
}
return false;
}
private Map<Class<? extends Annotation>, ActionMethodParamAnnotationHandler> paramAnnoHandlers(BeanSpec spec) {
Map<Class<? extends Annotation>, ActionMethodParamAnnotationHandler> handlers = annoHandlers.get(spec);
if (null != handlers) {
return handlers;
}
Map<Class<? extends Annotation>, ActionMethodParamAnnotationHandler> newHandlers = new HashMap<>();
for (Annotation annotation : spec.allAnnotations()) {
Class<? extends Annotation> c = annotation.annotationType();
ActionMethodParamAnnotationHandler h = allAnnotationHandlers.get(c);
if (null != h) {
newHandlers.put(c, h);
}
}
handlers = annoHandlers.putIfAbsent(spec, newHandlers);
if (null == handlers) {
handlers = newHandlers;
}
return handlers;
}
private ExecutableValidator executableValidator() {
if (null == executableValidator) {
synchronized (this) {
if (null == executableValidator) {
validator = Act.getInstance(Validator.class);
executableValidator = validator.forExecutables();
}
}
}
return executableValidator;
}
private static ScopeCacheSupport scopeCacheSupport(BeanSpec spec) {
if (spec.hasAnnotation(RequestScoped.class) || spec.hasAnnotation(org.osgl.inject.annotation.RequestScoped.class)) {
return RequestScope.INSTANCE;
} else if (sessionScoped(spec)) {
return SessionScope.INSTANCE;
} else if (spec.hasAnnotation(Dependent.class) || spec.hasAnnotation(New.class)) {
return DependentScope.INSTANCE;
}
// Default to Request Scope
return RequestScope.INSTANCE;
}
static boolean sessionScoped(BeanSpec spec) {
return spec.hasAnnotation(SessionScoped.class)
|| spec.hasAnnotation(org.osgl.inject.annotation.SessionScoped.class)
|| spec.hasAnnotation(SessionVariable.class);
}
public static void waiveFields(String... fieldNames) {
fieldBlackList.addAll(C.listOf(fieldNames));
}
public static String bindName(Annotation[] annotations, String defVal) {
String name = tryFindBindName(annotations, defVal);
E.illegalStateIf(null == name, "Cannot find bind name");
return name;
}
static String tryFindBindName(Annotation[] annotations, String defVal) {
Param param = filter(annotations, Param.class);
if (null != param && S.notBlank(param.value())) {
return param.value();
}
Bind bind = filter(annotations, Bind.class);
if (null != bind && S.notBlank(bind.model())) {
return bind.model();
}
Named named = filter(annotations, Named.class);
if (null != named && S.notBlank(named.value())) {
return named.value();
}
if (S.notBlank(defVal)) {
return defVal;
}
return null;
}
public static String bindName(BeanSpec beanSpec) {
return bindName(beanSpec.allAnnotations(), beanSpec.name());
}
public static boolean isThrowable(BeanSpec beanSpec) {
return beanSpec.isInstanceOf(Throwable.class);
}
public static boolean provided(BeanSpec beanSpec, DependencyInjector<?> injector) {
if (isThrowable(beanSpec)) {
return true;
}
GenieInjector genieInjector = $.cast(injector);
return genieInjector.isProvided(beanSpec);
}
public static boolean providedButNotDbBind(BeanSpec beanSpec, DependencyInjector<?> injector) {
if (!provided(beanSpec, injector)) {
return false;
}
Annotation[] aa = beanSpec.allAnnotations();
return !hasDbBind(aa);
}
// DbBind is special: it's class loader is AppClassLoader
public static boolean hasDbBind(Annotation[] annotations) {
for (Annotation a : annotations) {
if (a.annotationType().getName().equals(DbBind.class.getName())) {
return true;
}
}
return false;
}
}