-
Notifications
You must be signed in to change notification settings - Fork 188
/
BeanUnmarshaller.java
1294 lines (1180 loc) · 66.5 KB
/
BeanUnmarshaller.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
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2010-2019 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.prism.impl.marshaller;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.impl.PrismContextImpl;
import com.evolveum.midpoint.prism.impl.lex.dom.DomLexicalProcessor;
import com.evolveum.midpoint.prism.impl.xnode.*;
import com.evolveum.midpoint.prism.marshaller.ParsingMigrator;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.schema.SchemaRegistry;
import com.evolveum.midpoint.prism.xml.XsdTypeMapper;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType;
import com.evolveum.prism.xml.ns._public.types_3.*;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.w3c.dom.Element;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import static java.util.Collections.emptySet;
/**
* Analogous to PrismUnmarshaller, this class unmarshals atomic values from XNode tree structures.
* Atomic values are values that can be used as property values (i.e. either simple types, or
* beans that are not containerables).
*/
public class BeanUnmarshaller {
private static final Trace LOGGER = TraceManager.getTrace(BeanUnmarshaller.class);
@NotNull private final PrismBeanInspector inspector;
@NotNull private final BeanMarshaller beanMarshaller;
@NotNull private final PrismContext prismContext;
@NotNull private final Map<Class,PrimitiveUnmarshaller> specialPrimitiveUnmarshallers = new HashMap<>();
@NotNull private final Map<Class,MapUnmarshaller> specialMapUnmarshallers = new HashMap<>();
public BeanUnmarshaller(@NotNull PrismContext prismContext, @NotNull PrismBeanInspector inspector,
@NotNull BeanMarshaller beanMarshaller) {
this.prismContext = prismContext;
this.inspector = inspector;
this.beanMarshaller = beanMarshaller;
createSpecialUnmarshallerMaps();
}
@FunctionalInterface
private interface PrimitiveUnmarshaller<T> {
T unmarshal(PrimitiveXNodeImpl node, Class<T> beanClass, ParsingContext pc) throws SchemaException;
}
@FunctionalInterface
private interface MapUnmarshaller<T> {
T unmarshal(MapXNodeImpl node, Class<T> beanClass, ParsingContext pc) throws SchemaException;
}
private void add(Class<?> beanClass, PrimitiveUnmarshaller primitive, MapUnmarshaller map) {
specialPrimitiveUnmarshallers.put(beanClass, primitive);
specialMapUnmarshallers.put(beanClass, map);
}
private void createSpecialUnmarshallerMaps() {
add(XmlAsStringType.class, this::unmarshalXmlAsStringFromPrimitive, this::unmarshalXmlAsStringFromMap);
add(RawType.class, this::unmarshalRawType, this::unmarshalRawType);
add(PolyString.class, this::unmarshalPolyStringFromPrimitive, this::unmarshalPolyStringFromMap);
add(PolyStringType.class, this::unmarshalPolyStringFromPrimitive, this::unmarshalPolyStringFromMap);
add(ItemPathType.class, this::unmarshalItemPath, this::notSupported);
add(ProtectedStringType.class, this::unmarshalProtectedString, this::unmarshalProtectedString);
add(ProtectedByteArrayType.class, this::unmarshalProtectedByteArray, this::unmarshalProtectedByteArray);
add(SchemaDefinitionType.class, this::notSupported, this::unmarshalSchemaDefinitionType);
}
//region Main entry ==========================================================================
/*
* Preconditions:
* 1. typeName is processable by unmarshaller - i.e. it corresponds to simple or complex type NOT of containerable character
*/
<T> T unmarshal(@NotNull XNodeImpl xnode, @NotNull QName typeQName, @NotNull ParsingContext pc) throws SchemaException {
Class<T> classType = getSchemaRegistry().determineClassForType(typeQName); // TODO use correct method!
if (classType == null) {
TypeDefinition td = getSchemaRegistry().findTypeDefinitionByType(typeQName);
if (td instanceof SimpleTypeDefinition) {
// most probably dynamically defined enum (TODO clarify)
classType = (Class<T>) String.class;
} else {
throw new IllegalArgumentException("Couldn't unmarshal " + typeQName + ". Type definition = " + td);
}
}
return unmarshal(xnode, classType, pc);
}
/**
* TODO: decide if this method should be marked @NotNull.
* Basically the problem is with primitives. When parsed, they sometimes return null. The question is if it's correct.
*/
<T> T unmarshal(@NotNull XNodeImpl xnode, @NotNull Class<T> beanClass, @NotNull ParsingContext pc) throws SchemaException {
T value = unmarshalInternal(xnode, beanClass, pc);
if (PrismContextImpl.isExtraValidation() && value != null) {
Class<?> requested = ClassUtils.primitiveToWrapper(beanClass);
Class<?> actual = ClassUtils.primitiveToWrapper(value.getClass());
if (!requested.isAssignableFrom(actual)) {
throw new AssertionError("Postcondition fail: unmarshal returned a value of " + value + " ("
+ actual + ") which is not of requested type (" + requested + ")");
}
}
return value;
}
private <T> T unmarshalInternal(@NotNull XNodeImpl xnode, @NotNull Class<T> beanClass, @NotNull ParsingContext pc) throws SchemaException {
if (beanClass == null) {
throw new IllegalStateException("No bean class for node: " + xnode.debugDump());
}
if (xnode instanceof RootXNodeImpl) {
XNodeImpl subnode = ((RootXNodeImpl) xnode).getSubnode();
if (subnode == null) {
throw new IllegalStateException("Couldn't parse " + beanClass + " from a root node with a null content: " + xnode.debugDump());
} else {
return unmarshal(subnode, beanClass, pc);
}
} else if (!(xnode instanceof MapXNodeImpl) && !(xnode instanceof PrimitiveXNodeImpl) && !xnode.isHeterogeneousList()) {
throw new IllegalStateException("Couldn't parse " + beanClass + " from non-map/non-primitive/non-hetero-list node: " + xnode.debugDump());
}
// only maps and primitives and heterogeneous lists after this point
if (xnode instanceof PrimitiveXNodeImpl) {
//noinspection unchecked
PrimitiveXNodeImpl<T> prim = (PrimitiveXNodeImpl) xnode;
QName xsdType = XsdTypeMapper.getJavaToXsdMapping(beanClass);
if (xsdType != null) {
return prim.getParsedValue(xsdType, beanClass);
} else if (beanClass.isEnum()) {
return unmarshalEnumFromPrimitive(prim, beanClass, pc);
} else {
@SuppressWarnings("unchecked")
PrimitiveUnmarshaller<T> unmarshaller = specialPrimitiveUnmarshallers.get(beanClass);
if (unmarshaller != null) {
return unmarshaller.unmarshal(prim, beanClass, pc);
} else {
return unmarshalPrimitiveOther(prim, beanClass, pc);
}
}
} else {
if (beanClass.getPackage() == null || beanClass.getPackage().getName().equals("java.lang")) {
// We obviously have primitive data type, but we are asked to unmarshal from map xnode
// NOTE: this may happen in XML when we have "empty" element, but it has some whitespace in it
// such as those troublesome newlines. This also happens if there is "empty" element
// but it contains an expression (so it is not PrimitiveXNode but MapXNode).
// TODO: more robust implementation
// TODO: look for "value" subnode with primitive value and try that.
// This is most likely attempt to parse primitive value with dynamic expression.
// Therefore just ignore entire map content.
// This may also happen when schema elements are renamed. E.g. in 4.0 the complex "iteration" element of
// object template was replaced by s primitive int "iteration" element from AssignmentHolderType.
// Currently we do not have any good idea how to graciously handle such situation. Therefore we have
// to live with that, just make sure it is clearly documented in the release notes.
// MID-5198
return null;
}
@SuppressWarnings("unchecked")
MapUnmarshaller<T> unmarshaller = specialMapUnmarshallers.get(beanClass);
if (xnode instanceof MapXNodeImpl && unmarshaller != null) { // TODO: what about special unmarshaller + hetero list?
return unmarshaller.unmarshal((MapXNodeImpl) xnode, beanClass, pc);
}
return unmarshalFromMapOrHeteroList(xnode, beanClass, pc);
}
}
/**
* For cases when XSD complex type has a simple content. In that case the resulting class has @XmlValue annotation.
*/
private <T> T unmarshalPrimitiveOther(PrimitiveXNodeImpl<T> prim, Class<T> beanClass, ParsingContext pc) throws SchemaException {
if (prim.isEmpty()) {
return instantiateWithSubtypeGuess(beanClass, emptySet()); // Special case. Just return empty object
}
Field valueField = XNodeProcessorUtil.findXmlValueField(beanClass);
if (valueField == null) {
ParsingMigrator parsingMigrator = prismContext.getParsingMigrator();
if (parsingMigrator != null) {
T bean = parsingMigrator.tryParsingPrimitiveAsBean(prim, beanClass, pc);
if (bean != null) {
return bean;
}
}
throw new SchemaException("Cannot convert primitive value to bean of type " + beanClass);
}
T instance = instantiate(beanClass);
if (!valueField.isAccessible()) {
valueField.setAccessible(true);
}
T value;
if (prim.isParsed()) {
value = prim.getValue();
} else {
Class<?> fieldType = valueField.getType();
QName xsdType = XsdTypeMapper.toXsdType(fieldType);
value = prim.getParsedValue(xsdType, (Class<T>) fieldType);
}
try {
valueField.set(instance, value);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new SchemaException("Cannot set primitive value to field " + valueField.getName() + " of bean " + beanClass + ": "+e.getMessage(), e);
}
return instance;
}
boolean canProcess(QName typeName) {
return beanMarshaller.canProcess(typeName);
}
boolean canProcess(Class<?> clazz) {
return beanMarshaller.canProcess(clazz);
}
//endregion
@NotNull
private <T> T unmarshalFromMapOrHeteroList(@NotNull XNodeImpl mapOrList, @NotNull Class<T> beanClass, @NotNull ParsingContext pc) throws SchemaException {
if (Containerable.class.isAssignableFrom(beanClass)) {
// This could have come from inside; note we MUST NOT parse this as PrismValue, because for objects we would lose oid/version
return prismContext.parserFor(mapOrList.toRootXNode()).type(beanClass).parseRealValue();
} else if (SearchFilterType.class.isAssignableFrom(beanClass)) {
if (mapOrList instanceof MapXNodeImpl) {
T bean = (T) unmarshalSearchFilterType((MapXNodeImpl) mapOrList, (Class<? extends SearchFilterType>) beanClass, pc);
// TODO fix this BRUTAL HACK - it is here because of c:ConditionalSearchFilterType
return unmarshalFromMapOrHeteroListToBean(bean, mapOrList, Collections.singleton("condition"), pc);
} else {
throw new SchemaException("SearchFilterType is not supported in combination of heterogeneous list.");
}
} else {
T bean = instantiateWithSubtypeGuess(beanClass, mapOrList);
return unmarshalFromMapOrHeteroListToBean(bean, mapOrList, null, pc);
}
}
private <T> T instantiateWithSubtypeGuess(@NotNull Class<T> beanClass, XNodeImpl mapOrList) throws SchemaException {
if (!(mapOrList instanceof MapXNodeImpl)) {
return instantiate(beanClass); // guessing is supported only for traditional maps now
}
return instantiateWithSubtypeGuess(beanClass, ((MapXNodeImpl) mapOrList).keySet());
}
private <T> T instantiateWithSubtypeGuess(@NotNull Class<T> beanClass, Collection<QName> fields) throws SchemaException {
if (!Modifier.isAbstract(beanClass.getModifiers())) {
return instantiate(beanClass); // non-abstract classes are currently instantiated directly (could be changed)
}
Class<? extends T> subclass = inspector.findMatchingSubclass(beanClass, fields);
return instantiate(subclass);
}
private <T> T instantiate(@NotNull Class<T> beanClass) {
T bean;
try {
bean = beanClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new SystemException("Cannot instantiate bean of type " + beanClass + ": " + e.getMessage(), e);
}
return bean;
}
@NotNull
private <T> T unmarshalFromMapOrHeteroListToBean(@NotNull T bean, @NotNull XNodeImpl mapOrList, @Nullable Collection<String> keysToParse, @NotNull ParsingContext pc) throws SchemaException {
@SuppressWarnings("unchecked")
Class<T> beanClass = (Class<T>) bean.getClass();
if (mapOrList instanceof MapXNodeImpl) {
MapXNodeImpl map = (MapXNodeImpl) mapOrList;
for (Entry<QName, XNodeImpl> entry : map.entrySet()) {
QName key = entry.getKey();
if (keysToParse != null && !keysToParse.contains(key.getLocalPart())) {
continue;
}
if (entry.getValue() == null) {
continue;
}
unmarshalEntry(bean, beanClass, entry.getKey(), entry.getValue(), mapOrList, false, pc);
}
} else if (mapOrList.isHeterogeneousList()) {
QName keyQName = beanMarshaller.getHeterogeneousListPropertyName(beanClass);
unmarshalEntry(bean, beanClass, keyQName, mapOrList, mapOrList, true, pc);
} else {
throw new IllegalStateException("Not a map nor heterogeneous list: " + mapOrList.debugDump());
}
return bean;
}
/**
* Parses either a map entry, or a fictitious heterogeneous list property.
*
* It makes sure that a 'key' property is inserted into 'bean' object, being sourced from 'node' structure.
* Node itself can be single-valued or multi-valued, corresponding to single or multi-valued 'key' property.
* ---
* A notable (and quite ugly) exception is processing of fictitious heterogeneous lists.
* In this case we have a ListXNode that should be interpreted as a MapXNode, inserting fictitious property
* named after abstract multivalued property in the parent bean.
*
* For example, when we have (embedded in ExecuteScriptType):
* {
* pipeline: *[
* { element: search, ... },
* { element: sequence, ... }
* ]
* }
*
* ...it should be, in fact, read as if it would be:
*
* {
* pipeline: {
* scriptingExpression: [
* { type: SearchExpressionType, ... },
* { type: ExpressionSequenceType, ... }
* ]
* }
* }
*
* (The only difference is in element names, which are missing in the latter snippet, but let's ignore that here.)
*
* Fictitious heterogeneous list entry here is "scriptingExpression", a property of pipeline (ExpressionPipelineType).
*
* We have to create the following data structure (corresponding to latter snippet):
*
* instance of ExecuteScriptType:
* scriptingExpression = instance of JAXBElement(pipeline, ExpressionPipelineType): [1]
* scriptingExpression = List of [2]
* - JAXBElement(search, SearchExpressionType)
* - JAXBElement(sequence, ExpressionSequenceType)
*
* We in fact invoke this method twice with the same node (a two-entry list, marked as '*' in the first snippet):
* 1) bean=ExecuteScriptType, key=pipeline, node=HList(*), isHeteroListProperty=false
* 2) bean=ExpressionPipelineType, key=scriptingExpression, node=HList(*), isHeteroListProperty=true <<<
*
* During the first call we fill in scriptingExpression (single value) in ExecuteScriptType [1]; during the second one
* we fill in scriptingExpression (multivalued) in ExpressionPipelineType [2].
*
* Now let's expand the sample.
*
* This XNode tree:
* {
* pipeline: *[
* { element: search, type: RoleType, searchFilter: {...}, action: log },
* { element: sequence, value: **[
* { element: action, type: delete },
* { element: action, type: assign, parameter: {...} },
* { element: search, type: UserType }
* ] }
* ]
* }
*
* Should be interpreted as:
* {
* pipeline: {
* scriptingExpression: [
* { type: SearchExpressionType, type: RoleType, searchFilter: {...}, action: log }
* { type: ExpressionSequenceType, scriptingExpression: [
* { type: ActionExpressionType, type: delete },
* { type: ActionExpressionType, type: assign, parameter: {...} },
* { type: SearchExpressionType, type: UserType }
* ] }
* ]
* }
* }
*
* Producing the following data:
*
* instance of ExecuteScriptType:
* scriptingExpression = instance of JAXBElement(pipeline, ExpressionPipelineType): [1]
* scriptingExpression = List of [2]
* - JAXBElement(search, instance of SearchExpressionType):
* type: RoleType,
* searchFilter: (...),
* action: log,
* - JAXBElement(sequence, instance of ExpressionSequenceType):
* scriptingExpression = List of
* - JAXBElement(action, instance of ActionExpressionType):
* type: delete
* - JAXBElement(action, instance of ActionExpressionType):
* type: assign
* parameter: (...),
* - JAXBElement(search, instance of SearchExpressionType):
* type: UserType
*
* Invocations of this method will be:
* 1) bean=ExecuteScriptType, key=pipeline, node=HList(*), isHeteroListProperty=false
* 2) bean=ExpressionPipelineType, key=scriptingExpression, node=HList(*), isHeteroListProperty=true <<<
* 3) bean=SearchExpressionType, key=type, node='type: c:RoleType', isHeteroListProperty=false
* 4) bean=SearchExpressionType, key=searchFilter, node=XNode(map:1 entries), isHeteroListProperty=false
* 5) bean=SearchExpressionType, key=action, node=XNode(map:1 entries), isHeteroListProperty=false
* 6) bean=ActionExpressionType, key=type, node='type: log', isHeteroListProperty=false
* 7) bean=ExpressionSequenceType, key=scriptingExpression, node=HList(**), isHeteroListProperty=true <<<
* 8) bean=ActionExpressionType, key=type, node='type: delete', isHeteroListProperty=false
* 9) bean=ActionExpressionType, key=type, node='type: assign', isHeteroListProperty=false
* 10) bean=ActionExpressionType, key=parameter, node=XNode(map:2 entries), isHeteroListProperty=false
* 11) bean=ActionParameterValueType, key=name, node='name: role', isHeteroListProperty=false
* 12) bean=ActionParameterValueType, key=value, node='value: rome555c-7797-11e2-94a6-001e8c717e5b', isHeteroListProperty=false
* 13) bean=SearchExpressionType, key=type, node='type: UserType', isHeteroListProperty=false
*
* Here we have 2 calls with isHeteroListProperty=true; first for pipeline.scriptingExpression, second for
* sequence.scriptingExpression.
*/
private <T> void unmarshalEntry(@NotNull T bean, @NotNull Class<T> beanClass,
@NotNull QName key, @NotNull XNodeImpl node, @NotNull XNodeImpl containingNode,
boolean isHeteroListProperty, @NotNull ParsingContext pc) throws SchemaException {
//System.out.println("bean=" + bean.getClass().getSimpleName() + ", key=" + key.getLocalPart() + ", node=" + node + ", isHeteroListProperty=" + isHeteroListProperty);
final String propName = key.getLocalPart();
// this code is just to keep this method reasonably short
PropertyAccessMechanism mechanism = new PropertyAccessMechanism();
if (!mechanism.compute(bean, beanClass, propName, key, node, pc)) {
return;
}
final String actualPropertyName = mechanism.actualPropertyName;
final boolean storeAsRawType = mechanism.storeAsRawType;
final Method getter = mechanism.getter;
final Method setter = mechanism.setter;
final boolean wrapInJaxbElement = mechanism.wrapInJaxbElement;
if (Element.class.isAssignableFrom(mechanism.paramType)) {
throw new IllegalArgumentException("DOM not supported in field "+actualPropertyName+" in "+beanClass);
}
// The type T that is expected by the bean, i.e. either by
// - setMethod(T value), or
// - Collection<T> getMethod()
// We use it to retrieve the correct value when parsing the node.
// We might specialize it using the information derived from the node (to deal with inclusive polymorphism,
// i.e. storing ExclusionPolicyConstraintType where AbstractPolicyConstraintType is expected).
@NotNull Class<?> paramType;
if (!storeAsRawType && !isHeteroListProperty) {
Class<?> t = specializeParamType(node, mechanism.paramType, pc);
if (t == null) { // indicates a problem
return;
} else {
paramType = t;
}
} else {
paramType = mechanism.paramType;
}
if (!(node instanceof ListXNodeImpl) && Object.class.equals(paramType) && !storeAsRawType) {
throw new IllegalArgumentException("Object property (without @Raw) not supported in field "+actualPropertyName+" in "+beanClass);
}
// String paramNamespace = inspector.determineNamespace(paramType);
boolean problem = false;
Object propValue = null;
Collection<Object> propValues = null;
// For heterogeneous lists we have to create multi-valued fictitious property first. So we have to treat node as a map
// (instead of list) and process it as a single value. Only when
if (node instanceof ListXNodeImpl && (!node.isHeterogeneousList() || isHeteroListProperty)) {
ListXNodeImpl xlist = (ListXNodeImpl) node;
if (setter != null) {
try {
Object value = unmarshalSinglePropValue(node, actualPropertyName, paramType, storeAsRawType, beanClass, pc);
if (wrapInJaxbElement) {
propValue = wrapInJaxbElement(value, mechanism.objectFactory,
mechanism.elementFactoryMethod, propName, beanClass, pc);
} else {
propValue = value;
}
} catch (SchemaException e) {
problem = processSchemaException(e, node, pc);
}
} else {
// No setter, we have to use collection getter
propValues = new ArrayList<>(xlist.size());
for (XNodeImpl xsubsubnode: xlist) {
try {
Object valueToAdd;
Object value = unmarshalSinglePropValue(xsubsubnode, actualPropertyName, paramType, storeAsRawType, beanClass, pc);
if (value != null) {
if (isHeteroListProperty) {
QName elementName = xsubsubnode.getElementName();
if (elementName == null) {
// TODO better error handling
throw new SchemaException("Heterogeneous list with a no-elementName node: " + xsubsubnode);
}
Class valueClass = value.getClass();
QName jaxbElementName;
if (QNameUtil.hasNamespace(elementName)) {
jaxbElementName = elementName;
} else {
// Approximate solution: find element in schema registry - check for type compatibility
// in order to exclude accidental name matches (like c:expression/s:expression).
Optional<ItemDefinition> itemDefOpt = getSchemaRegistry().findItemDefinitionsByElementName(elementName)
.stream()
.filter(def ->
getSchemaRegistry().findTypeDefinitionsByType(def.getTypeName()).stream()
.anyMatch(typeDef -> typeDef.getCompileTimeClass() != null
&& typeDef.getCompileTimeClass()
.isAssignableFrom(valueClass)))
.findFirst();
if (itemDefOpt.isPresent()) {
jaxbElementName = itemDefOpt.get().getItemName();
} else {
LOGGER.warn("Heterogeneous list member with unknown element name '" + elementName + "': " + value);
jaxbElementName = elementName; // unqualified
}
}
@SuppressWarnings("unchecked")
JAXBElement jaxbElement = new JAXBElement<>(jaxbElementName, valueClass, value);
valueToAdd = jaxbElement;
} else {
if (wrapInJaxbElement) {
valueToAdd = wrapInJaxbElement(value, mechanism.objectFactory,
mechanism.elementFactoryMethod, propName, beanClass, pc);
} else {
valueToAdd = value;
}
}
propValues.add(valueToAdd);
}
} catch (SchemaException e) {
problem = processSchemaException(e, xsubsubnode, pc);
}
}
}
} else {
try {
propValue = unmarshalSinglePropValue(node, actualPropertyName, paramType, storeAsRawType, beanClass, pc);
if (wrapInJaxbElement) {
propValue = wrapInJaxbElement(propValue, mechanism.objectFactory,
mechanism.elementFactoryMethod, propName, beanClass, pc);
}
} catch (SchemaException e) {
problem = processSchemaException(e, node, pc);
}
}
if (setter != null) {
try {
setter.invoke(bean, propValue);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new SystemException("Cannot invoke setter "+setter+" on bean of type "+beanClass+": "+e.getMessage(), e);
}
} else if (getter != null) {
Object getterReturn;
Collection<Object> col;
try {
getterReturn = getter.invoke(bean);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new SystemException("Cannot invoke getter "+getter+" on bean of type "+beanClass+": "+e.getMessage(), e);
}
try {
col = (Collection<Object>)getterReturn;
} catch (ClassCastException e) {
throw new SystemException("Getter "+getter+" on bean of type "+beanClass+" returned "+getterReturn+" instead of collection");
}
if (propValue != null) {
col.add(propValue);
} else if (propValues != null) {
for (Object propVal: propValues) {
col.add(propVal);
}
} else if (!problem) {
throw new IllegalStateException("Strange. Multival property "+propName+" in "+beanClass+" produced null values list, parsed from "+containingNode);
}
if (!isHeteroListProperty) {
checkJaxbElementConsistence(col, pc);
}
} else {
throw new IllegalStateException("Uh? No setter nor getter.");
}
}
private Class<?> specializeParamType(@NotNull XNodeImpl node, @NotNull Class<?> expectedType, @NotNull ParsingContext pc)
throws SchemaException {
if (node.getTypeQName() != null) {
Class explicitType = getSchemaRegistry().determineClassForType(node.getTypeQName());
return explicitType != null && expectedType.isAssignableFrom(explicitType) ? explicitType : expectedType;
// (if not assignable, we hope the adaptation will do it)
} else if (node.getElementName() != null) {
Collection<TypeDefinition> candidateTypes = getSchemaRegistry()
.findTypeDefinitionsByElementName(node.getElementName(), TypeDefinition.class);
List<TypeDefinition> suitableTypes = candidateTypes.stream()
.filter(def -> def.getCompileTimeClass() != null && expectedType.isAssignableFrom(def.getCompileTimeClass()))
.collect(Collectors.toList());
if (suitableTypes.isEmpty()) {
pc.warnOrThrow(LOGGER, "Couldn't derive suitable type based on element name ("
+ node.getElementName() + "). Candidate types: " + candidateTypes + "; expected type: " + expectedType);
return null;
} else if (suitableTypes.size() > 1) {
pc.warnOrThrow(LOGGER, "Couldn't derive single suitable type based on element name ("
+ node.getElementName() + "). Suitable types: " + suitableTypes);
return null;
}
return suitableTypes.get(0).getCompileTimeClass();
} else {
return expectedType;
}
}
private class PropertyAccessMechanism {
Class<?> beanClass;
// phase1
String actualPropertyName; // This is the name of property we will really use. (Considering e.g. substitutions.)
boolean storeAsRawType; // Whether the data will be stored as RawType.
Object objectFactory; // JAXB object factory instance (e.g. xxxx.common-3.ObjectFactory).
Method elementFactoryMethod; // Method in object factory that creates a given JAXB element (e.g. createAsIs(value))
// phase2
Method getter, setter; // Getter or setter that will be used to put a value (getter in case of collections)
Class<?> paramType; // Actual parameter type; unwrapped: Collection<X> -> X, JAXBElement<X> -> X
boolean wrapInJaxbElement; // If the paramType contained JAXBElement, i.e. if the value should be wrapped into it before using
// returns true if the processing is to be continued;
// false in case of using alternative way of unmarshalling (e.g. use of "any" method), or in case of error (in COMPAT mode)
private <T> boolean compute(T bean, Class<T> beanClass, String propName, QName key, XNodeImpl node, ParsingContext pc)
throws SchemaException {
this.beanClass = beanClass;
// phase1
if (!computeActualPropertyName(bean, propName, key, node, pc)) {
return false;
}
// phase2
return computeGetterAndSetter(propName, pc);
}
// computes actualPropertyName + storeAsRawType
// if necessary, fills-in also objectFactory + elementFactoryMethod
private <T> boolean computeActualPropertyName(T bean, String propName, QName key, XNodeImpl node, ParsingContext pc)
throws SchemaException {
Field propertyField = inspector.findPropertyField(beanClass, propName);
Method propertyGetter = null;
if (propertyField == null) {
propertyGetter = inspector.findPropertyGetter(beanClass, propName);
}
// Maybe this is not used in this context, because node.elementName is filled-in only for heterogeneous list
// members - and they are iterated through elsewhere. Nevertheless, it is more safe to include it also here.
// QName realElementName = getRealElementName(node, key, pc);
// String realElementLocalName = realElementName.getLocalPart();
elementFactoryMethod = null;
objectFactory = null;
if (propertyField == null && propertyGetter == null) {
// We have to try to find a more generic field, such as xsd:any or substitution element
// check for global element definition first
elementFactoryMethod = findElementFactoryMethod(propName); // realElementLocalName
if (elementFactoryMethod != null) {
// great - global element found, let's look up the field
propertyField = inspector.lookupSubstitution(beanClass, elementFactoryMethod);
if (propertyField == null) {
propertyField = inspector.findAnyField(beanClass); // Check for "any" field
if (propertyField != null) {
unmarshalToAnyUsingField(bean, propertyField, key, node, pc);
} else {
unmarshalToAnyUsingGetterIfExists(bean, key, node, pc, propName);
}
return false;
}
} else {
unmarshalToAnyUsingGetterIfExists(bean, key, node, pc, propName); // e.g. "getAny()"
return false;
}
}
// At this moment, property getter is the exact getter matching key.localPart (propName).
// Property field may be either exact field matching key.localPart (propName), or more generic one (substitution, any).
//noinspection ConstantConditions
assert propertyGetter != null || propertyField != null;
if (elementFactoryMethod != null) {
storeAsRawType = elementFactoryMethod.getAnnotation(Raw.class) != null;
} else if (propertyGetter != null) {
storeAsRawType = propertyGetter.getAnnotation(Raw.class) != null;
} else {
storeAsRawType = propertyField.getAnnotation(Raw.class) != null;
}
if (propertyField != null) {
actualPropertyName = propertyField.getName();
} else {
actualPropertyName = propName;
}
return true;
}
private Method findElementFactoryMethod(String propName) {
Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage());
objectFactory = instantiateObjectFactory(objectFactoryClass);
return inspector.findElementMethodInObjectFactory(objectFactoryClass, propName);
}
private boolean computeGetterAndSetter(String propName, ParsingContext pc) throws SchemaException {
setter = inspector.findSetter(beanClass, actualPropertyName);
wrapInJaxbElement = false;
paramType = null;
if (setter == null) {
// No setter. But if the property is multi-value we need to look
// for a getter that returns a collection (Collection<Whatever>)
getter = inspector.findPropertyGetter(beanClass, actualPropertyName);
if (getter == null) {
pc.warnOrThrow(LOGGER, "Cannot find setter or getter for field " + actualPropertyName + " in " + beanClass);
return false;
}
computeParamTypeFromGetter(propName, getter.getReturnType());
} else {
getter = null;
Class<?> setterType = setter.getParameterTypes()[0];
computeParamTypeFromSetter(propName, setterType);
}
return true;
}
private void computeParamTypeFromSetter(String propName, Class<?> setterParamType) {
if (JAXBElement.class.equals(setterParamType)) {
// TODO some handling for the returned generic parameter types
Type[] genericTypes = setter.getGenericParameterTypes();
if (genericTypes.length != 1) {
throw new IllegalArgumentException("Too lazy to handle this.");
}
Type genericType = genericTypes[0];
if (genericType instanceof ParameterizedType) {
Type actualType = inspector.getTypeArgument(genericType, "add some description");
if (actualType instanceof WildcardType) {
if (elementFactoryMethod == null) {
elementFactoryMethod = findElementFactoryMethod(propName);
}
// This is the case of Collection<JAXBElement<?>>
// we need to extract the specific type from the factory method
if (elementFactoryMethod == null) {
throw new IllegalArgumentException(
"Wildcard type in JAXBElement field specification and no factory method found for field "
+ actualPropertyName + " in " + beanClass
+ ", cannot determine collection type (inner type argument)");
}
Type factoryMethodGenericReturnType = elementFactoryMethod.getGenericReturnType();
Type factoryMethodTypeArgument = inspector.getTypeArgument(factoryMethodGenericReturnType,
"in factory method " + elementFactoryMethod + " return type for field " + actualPropertyName
+ " in " + beanClass + ", cannot determine collection type");
if (factoryMethodTypeArgument instanceof Class) {
// This is the case of JAXBElement<Whatever>
paramType = (Class<?>) factoryMethodTypeArgument;
if (Object.class.equals(paramType) && !storeAsRawType) {
throw new IllegalArgumentException("Factory method " + elementFactoryMethod
+ " type argument is Object (without @Raw) for field " +
actualPropertyName + " in " + beanClass + ", property " + propName);
}
} else {
throw new IllegalArgumentException(
"Cannot determine factory method return type, got " + factoryMethodTypeArgument
+ " - for field " + actualPropertyName + " in " + beanClass
+ ", cannot determine collection type (inner type argument)");
}
}
}
// Class enclosing = paramType.getEnclosingClass();
// Class clazz = paramType.getClass();
// Class declaring = paramType.getDeclaringClass();
wrapInJaxbElement = true;
} else {
paramType = setterParamType;
}
}
private void computeParamTypeFromGetter(String propName, Class<?> getterReturnType) throws SchemaException {
if (!Collection.class.isAssignableFrom(getterReturnType)) {
throw new SchemaException("Cannot find getter for field " + actualPropertyName + " in " + beanClass
+ " does not return collection, cannot use it to set value");
}
// getter.genericReturnType = Collection<...>
Type typeArgument = inspector.getTypeArgument(getter.getGenericReturnType(),
"for field " + actualPropertyName + " in " + beanClass + ", cannot determine collection type");
if (typeArgument instanceof Class) {
paramType = (Class<?>) typeArgument; // ok, like Collection<AssignmentType>
} else if (typeArgument instanceof ParameterizedType) { // something more complex
ParameterizedType paramTypeArgument = (ParameterizedType) typeArgument;
Type rawTypeArgument = paramTypeArgument.getRawType();
if (rawTypeArgument.equals(JAXBElement.class)) {
// This is the case of Collection<JAXBElement<....>>
wrapInJaxbElement = true;
Type innerTypeArgument = inspector.getTypeArgument(typeArgument,
"for field " + actualPropertyName + " in " + beanClass
+ ", cannot determine collection type (inner type argument)");
if (innerTypeArgument instanceof Class) {
// This is the case of Collection<JAXBElement<Whatever>> (note that wrapInJaxbElement is now true)
paramType = (Class<?>) innerTypeArgument;
} else if (innerTypeArgument instanceof WildcardType) {
// This is the case of Collection<JAXBElement<?>>
// we need to extract the specific type from the factory method
if (elementFactoryMethod == null) {
elementFactoryMethod = findElementFactoryMethod(propName);
if (elementFactoryMethod == null) {
throw new IllegalArgumentException(
"Wildcard type in JAXBElement field specification and no factory method found for field "
+ actualPropertyName + " in " + beanClass
+ ", cannot determine collection type (inner type argument)");
}
}
// something like JAXBElement<AsIsExpressionEvaluatorType>
Type factoryMethodGenericReturnType = elementFactoryMethod.getGenericReturnType();
Type factoryMethodTypeArgument = inspector.getTypeArgument(factoryMethodGenericReturnType,
"in factory method " + elementFactoryMethod + " return type for field " + actualPropertyName
+ " in " + beanClass + ", cannot determine collection type");
if (factoryMethodTypeArgument instanceof Class) {
// This is the case of JAXBElement<Whatever>
paramType = (Class<?>) factoryMethodTypeArgument;
if (Object.class.equals(paramType) && !storeAsRawType) {
throw new IllegalArgumentException("Factory method " + elementFactoryMethod
+ " type argument is Object (and not @Raw) for field " +
actualPropertyName + " in " + beanClass + ", property " + propName);
}
} else {
throw new IllegalArgumentException(
"Cannot determine factory method return type, got " + factoryMethodTypeArgument
+ " - for field " + actualPropertyName + " in " + beanClass
+ ", cannot determine collection type (inner type argument)");
}
} else {
throw new IllegalArgumentException(
"Ejha! " + innerTypeArgument + " " + innerTypeArgument.getClass() + " from "
+ getterReturnType + " from " + actualPropertyName + " in " + propName + " "
+ beanClass);
}
} else {
// The case of Collection<Whatever<Something>>
if (rawTypeArgument instanceof Class) { // ??? rawTypeArgument is the 'Whatever' part
paramType = (Class<?>) rawTypeArgument;
} else {
throw new IllegalArgumentException(
"EH? Eh!? " + typeArgument + " " + typeArgument.getClass() + " from " + getterReturnType
+ " from " + actualPropertyName + " in " + propName + " " + beanClass);
}
}
} else {
throw new IllegalArgumentException(
"EH? " + typeArgument + " " + typeArgument.getClass() + " from " + getterReturnType + " from "
+ actualPropertyName + " in " + propName + " " + beanClass);
}
}
}
private <T> void unmarshalToAnyUsingGetterIfExists(@NotNull T bean, @NotNull QName key, @NotNull XNodeImpl node,
@NotNull ParsingContext pc, String propName) throws SchemaException {
Method elementMethod = inspector.findAnyMethod(bean.getClass());
if (elementMethod != null) {
unmarshallToAnyUsingGetter(bean, elementMethod, key, node, pc);
} else {
pc.warnOrThrow(LOGGER, "No field '"+propName+"' in class "+bean.getClass()+" (and no element method in object factory too)");
}
}
// Prepares value to be stored into the bean - e.g. converts PolyString->PolyStringType, wraps a value to JAXB if specified, ...
private Object wrapInJaxbElement(Object propVal, Object objectFactory, Method factoryMethod, String propName,
Class beanClass, ParsingContext pc) {
if (factoryMethod == null) {
throw new IllegalArgumentException("Param type is JAXB element but no factory method found for it, property "+propName+" in "+beanClass);
}
try {
return factoryMethod.invoke(objectFactory, propVal);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new SystemException("Unable to invoke factory method "+factoryMethod+" on "+objectFactory.getClass()+" for property "+propName+" in "+beanClass);
}
}
/*
* We want to avoid this:
* <expression>
* <script>
* <code>'up'</code>
* </script>
* <value>up</value>
* </expression>
*
* Because it cannot be reasonably serialized in XNode (<value> gets changed to <script>).
*/
private void checkJaxbElementConsistence(Collection<Object> collection, ParsingContext pc) throws SchemaException {
QName elementName = null;
for (Object object : collection) {
if (!(object instanceof JAXBElement)) {
continue;
}
JAXBElement element = (JAXBElement) object;
if (elementName == null) {
elementName = element.getName();
} else {
if (!QNameUtil.match(elementName, element.getName())) {
String m = "Mixing incompatible element names in one property: "
+ elementName + " and " + element.getName();
if (pc.isStrict()) {
throw new SchemaException(m);
} else {
pc.warn(LOGGER, m);
}
}
}
}
}
private boolean processSchemaException(SchemaException e, XNodeImpl xsubnode, ParsingContext pc) throws SchemaException {
if (pc.isStrict()) {
throw e;
} else {
LoggingUtils.logException(LOGGER, "Couldn't parse part of the document. It will be ignored. Document part: {}", e, xsubnode);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Part that couldn't be parsed:\n{}", xsubnode.debugDump());
}
pc.warn("Couldn't parse part of the document. It will be ignored. Document part:\n" + xsubnode);
return true;
}
}
private <T,S> void unmarshallToAnyUsingGetter(T bean, Method getter, QName elementName, XNodeImpl xsubnode, ParsingContext pc) throws SchemaException{
Class<T> beanClass = (Class<T>) bean.getClass();
Class objectFactoryClass = inspector.getObjectFactoryClass(elementName.getNamespaceURI());
Object objectFactory = instantiateObjectFactory(objectFactoryClass);
Method elementFactoryMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass, elementName.getLocalPart());
Class<S> subBeanClass = (Class<S>) elementFactoryMethod.getParameterTypes()[0];
if (xsubnode instanceof ListXNodeImpl){
for (XNodeImpl xsubSubNode : ((ListXNodeImpl) xsubnode)){
S subBean = unmarshal(xsubSubNode, subBeanClass, pc);
unmarshallToAnyValue(bean, beanClass, subBean, objectFactoryClass, objectFactory, elementFactoryMethod, getter, pc);
}
} else{
S subBean = unmarshal(xsubnode, subBeanClass, pc);
unmarshallToAnyValue(bean, beanClass, subBean, objectFactoryClass, objectFactory, elementFactoryMethod, getter, pc);
}
}
private <T, S> void unmarshallToAnyValue(T bean, Class beanClass, S subBean, Class objectFactoryClass, Object objectFactory,
Method elementFactoryMethod, Method getter, ParsingContext pc) {
JAXBElement<S> subBeanElement;
try {
subBeanElement = (JAXBElement<S>) elementFactoryMethod.invoke(objectFactory, subBean);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
throw new IllegalArgumentException("Cannot invoke factory method "+elementFactoryMethod+" on "+objectFactoryClass+" with "+subBean+": "+e1, e1);
}
Collection<Object> col;
Object getterReturn;
try {
getterReturn = getter.invoke(bean);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new SystemException("Cannot invoke getter "+getter+" on bean of type "+beanClass+": "+e.getMessage(), e);
}
try {
col = (Collection<Object>)getterReturn;
} catch (ClassCastException e) {
throw new SystemException("Getter "+getter+" on bean of type "+beanClass+" returned "+getterReturn+" instead of collection");
}
col.add(subBeanElement != null ? subBeanElement.getValue() : null);
}
private <T,S> void unmarshalToAnyUsingField(T bean, Field anyField, QName elementName, XNodeImpl xsubnode, ParsingContext pc) throws SchemaException{
Method getter = inspector.findPropertyGetter(bean.getClass(), anyField.getName());
unmarshallToAnyUsingGetter(bean, getter, elementName, xsubnode, pc);
}
private Object instantiateObjectFactory(Class objectFactoryClass) {
try {
return objectFactoryClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException("Cannot instantiate object factory class "+objectFactoryClass.getName()+": "+e.getMessage(), e);
}