-
Notifications
You must be signed in to change notification settings - Fork 188
/
PrismBeanConverter.java
1185 lines (1065 loc) · 49 KB
/
PrismBeanConverter.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-2016 Evolveum
*
* 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.
*/
package com.evolveum.midpoint.prism.marshaller;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.lex.dom.DomLexicalProcessor;
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.XmlTypeConverter;
import com.evolveum.midpoint.prism.xml.XsdTypeMapper;
import com.evolveum.midpoint.prism.xnode.ListXNode;
import com.evolveum.midpoint.prism.xnode.MapXNode;
import com.evolveum.midpoint.prism.xnode.PrimitiveXNode;
import com.evolveum.midpoint.prism.xnode.RootXNode;
import com.evolveum.midpoint.prism.xnode.SchemaXNode;
import com.evolveum.midpoint.prism.xnode.XNode;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.Handler;
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.exception.TunnelException;
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.EncryptedDataType;
import com.evolveum.prism.xml.ns._public.types_3.ItemPathType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedByteArrayType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedDataType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
import com.evolveum.prism.xml.ns._public.types_3.RawType;
import com.evolveum.prism.xml.ns._public.types_3.SchemaDefinitionType;
import com.evolveum.prism.xml.ns._public.types_3.XmlAsStringType;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Element;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class PrismBeanConverter {
private static final Trace LOGGER = TraceManager.getTrace(PrismBeanConverter.class);
public static final String DEFAULT_PLACEHOLDER = "##default";
private PrismBeanInspector inspector;
@NotNull private final PrismContext prismContext;
public PrismBeanConverter(@NotNull PrismContext prismContext, PrismBeanInspector inspector) {
this.prismContext = prismContext;
this.inspector = inspector;
}
@NotNull
public PrismContext getPrismContext() {
return prismContext;
}
// public void setPrismContext(PrismContext prismContext) {
// this.prismContext = prismContext;
// }
private SchemaRegistry getSchemaRegistry() {
return prismContext.getSchemaRegistry();
}
public boolean canProcess(QName typeName) {
return getSchemaRegistry().determineCompileTimeClass(typeName) != null;
}
public boolean canProcess(@NotNull Class<?> clazz) {
return RawType.class.equals(clazz) || clazz.getAnnotation(XmlType.class) != null;
}
public QName determineTypeForClass(Class<?> clazz) {
return inspector.determineTypeForClass(clazz);
}
public <T> T unmarshall(MapXNode xnode, QName typeQName, ParsingContext pc) throws SchemaException {
Class<T> classType = getSchemaRegistry().determineCompileTimeClass(typeQName);
return unmarshall(xnode, classType, pc);
}
public <T> T unmarshall(XNode xnode, Class<T> beanClass, ParsingContext pc) throws SchemaException{
if (xnode instanceof PrimitiveXNode){
return unmarshallPrimitive((PrimitiveXNode<T>) xnode, beanClass, pc);
} else if (xnode instanceof MapXNode){
return unmarshall((MapXNode) xnode, beanClass, pc);
} else if (xnode instanceof RootXNode){
return unmarshall(((RootXNode) xnode).getSubnode(), beanClass, pc);
} else
throw new IllegalStateException("Unexpected xnode " + xnode +". Could not unmarshall value");
}
public <T> T unmarshall(MapXNode xnode, Class<T> beanClass, ParsingContext pc) throws SchemaException {
if (PolyStringType.class.equals(beanClass)) {
PolyString polyString = unmarshalPolyString(xnode);
return (T) polyString; // violates the method interface but ... TODO fix it
} else if (ProtectedStringType.class.equals(beanClass)) {
ProtectedStringType protectedType = new ProtectedStringType();
XNodeProcessorUtil.parseProtectedType(protectedType, xnode, prismContext, pc);
return (T) protectedType;
} else if (ProtectedByteArrayType.class.equals(beanClass)) {
ProtectedByteArrayType protectedType = new ProtectedByteArrayType();
XNodeProcessorUtil.parseProtectedType(protectedType, xnode, prismContext, pc);
return (T) protectedType;
} else if (SchemaDefinitionType.class.equals(beanClass)) {
SchemaDefinitionType schemaDefType = unmarshalSchemaDefinitionType(xnode);
return (T) schemaDefType;
} else if (prismContext.getSchemaRegistry().determineDefinitionFromClass(beanClass) != null) {
PrismObjectDefinition def = prismContext.getSchemaRegistry().determineDefinitionFromClass(beanClass);
return (T) ((PrismContextImpl) prismContext).getPrismUnmarshaller().parseObject(xnode, def, pc).asObjectable();
} else if (XmlAsStringType.class.equals(beanClass)) {
// reading a string represented a XML-style content
// used e.g. when reading report templates (embedded XML)
// A necessary condition: there may be only one map entry.
if (xnode.size() > 1) {
throw new SchemaException("Map with more than one item cannot be parsed as a string: " + xnode);
} else if (xnode.isEmpty()) {
return (T) new XmlAsStringType();
} else {
Map.Entry<QName,XNode> entry = xnode.entrySet().iterator().next();
DomLexicalProcessor domParser = ((PrismContextImpl) prismContext).getParserDom();
String value = domParser.write(entry.getValue(), entry.getKey(), null);
return (T) new XmlAsStringType(value);
}
}
T bean;
Set<String> keysToParse; // only these keys will be parsed (null if all)
if (SearchFilterType.class.isAssignableFrom(beanClass)) {
keysToParse = Collections.singleton("condition"); // TODO fix this BRUTAL HACK - it is here because of c:ConditionalSearchFilterType
bean = (T) unmarshalSearchFilterType(xnode, (Class<? extends SearchFilterType>) beanClass, pc);
} else {
keysToParse = null;
try {
bean = beanClass.newInstance();
} catch (InstantiationException e) {
throw new SystemException("Cannot instantiate bean of type "+beanClass+": "+e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new SystemException("Cannot instantiate bean of type "+beanClass+": "+e.getMessage(), e);
}
}
if (ProtectedDataType.class.isAssignableFrom(beanClass)){
ProtectedDataType protectedDataType = null;
if (bean instanceof ProtectedStringType){
protectedDataType = new ProtectedStringType();
} else if (bean instanceof ProtectedByteArrayType){
protectedDataType = new ProtectedByteArrayType();
} else{
throw new SchemaException("Unexpected subtype of protected data type: " + bean.getClass());
}
XNodeProcessorUtil.parseProtectedType(protectedDataType, xnode, prismContext, pc);
return (T) protectedDataType;
}
for (Entry<QName,XNode> entry: xnode.entrySet()) {
QName key = entry.getKey();
if (keysToParse != null && !keysToParse.contains(key.getLocalPart())) {
continue;
}
XNode xsubnode = entry.getValue();
String propName = key.getLocalPart();
Field field = inspector.findPropertyField(beanClass, propName);
Method propertyGetter = null;
if (field == null) {
propertyGetter = inspector.findPropertyGetter(beanClass, propName);
}
Method elementMethod = null;
Object objectFactory = null;
if (field == 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
Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage());
objectFactory = instantiateObjectFactory(objectFactoryClass);
elementMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass, propName);
if (elementMethod == null) {
// Check for "any" method
elementMethod = inspector.findAnyMethod(beanClass);
if (elementMethod == null) {
String m = "No field "+propName+" in class "+beanClass+" (and no element method in object factory too)";
if (pc.isCompat()) {
pc.warn(LOGGER, m);
continue;
} else {
throw new SchemaException(m);
}
}
unmarshallToAny(bean, elementMethod, key, xsubnode, pc);
continue;
}
field = inspector.lookupSubstitution(beanClass, elementMethod);
if (field == null) {
// Check for "any" field
field = inspector.findAnyField(beanClass);
if (field == null) {
elementMethod = inspector.findAnyMethod(beanClass);
if (elementMethod == null) {
String m = "No field "+propName+" in class "+beanClass+" (and no element method in object factory too)";
if (pc.isCompat()) {
pc.warn(LOGGER, m);
continue;
} else {
throw new SchemaException(m);
}
}
unmarshallToAny(bean, elementMethod, key, xsubnode, pc);
continue;
// throw new SchemaException("No field "+propName+" in class "+beanClass+" (no suitable substitution and no 'any' field)");
}
unmarshallToAny(bean, field, key, xsubnode, pc);
continue;
}
}
boolean storeAsRawType;
if (elementMethod != null) {
storeAsRawType = elementMethod.getAnnotation(Raw.class) != null;
} else if (propertyGetter != null) {
storeAsRawType = propertyGetter.getAnnotation(Raw.class) != null;
} else {
storeAsRawType = field.getAnnotation(Raw.class) != null;
}
String fieldName;
if (field != null) {
fieldName = field.getName();
} else {
fieldName = propName;
}
Method setter = inspector.findSetter(beanClass, fieldName);
Method getter = null;
boolean wrapInJaxbElement = false;
Class<?> 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, fieldName);
if (getter == null) {
String m = "Cannot find setter or getter for field " + fieldName + " in " + beanClass;
if (pc.isCompat()) {
pc.warn(LOGGER, m);
continue;
} else {
throw new SchemaException(m);
}
}
Class<?> getterReturnType = getter.getReturnType();
if (!Collection.class.isAssignableFrom(getterReturnType)) {
throw new SchemaException("Cannot find getter for field "+fieldName+" in "+beanClass+" does not return collection, cannot use it to set value");
}
Type genericReturnType = getter.getGenericReturnType();
Type typeArgument = getTypeArgument(genericReturnType, "for field "+fieldName+" in "+beanClass+", cannot determine collection type");
// System.out.println("type argument " + typeArgument);
if (typeArgument instanceof Class) {
paramType = (Class<?>) typeArgument;
} else if (typeArgument instanceof ParameterizedType) {
ParameterizedType paramTypeArgument = (ParameterizedType)typeArgument;
Type rawTypeArgument = paramTypeArgument.getRawType();
if (rawTypeArgument.equals(JAXBElement.class)) {
// This is the case of Collection<JAXBElement<....>>
wrapInJaxbElement = true;
Type innerTypeArgument = getTypeArgument(typeArgument, "for field "+fieldName+" in "+beanClass+", cannot determine collection type (inner type argument)");
if (innerTypeArgument instanceof Class) {
// This is the case of Collection<JAXBElement<Whatever>>
paramType = (Class<?>) innerTypeArgument;
} else if (innerTypeArgument instanceof WildcardType) {
// This is the case of Collection<JAXBElement<?>>
// we need to exctract the specific type from the factory method
if (elementMethod == null){
// TODO: TEMPORARY CODE!!!!!!!!!! fix in 3.1 [med]
Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage());
objectFactory = instantiateObjectFactory(objectFactoryClass);
elementMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass, propName);
if (elementMethod == null) {
throw new IllegalArgumentException("Wildcard type in JAXBElement field specification and no factory method found for field "+fieldName+" in "+beanClass+", cannot determine collection type (inner type argument)");
}
}
Type factoryMethodGenericReturnType = elementMethod.getGenericReturnType();
Type factoryMethodTypeArgument = getTypeArgument(factoryMethodGenericReturnType, "in factory method "+elementMethod+" return type for field "+fieldName+" 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 "+elementMethod+" type argument is Object (and not @Raw) for field "+
fieldName+" in "+beanClass+", property "+propName);
}
} else {
throw new IllegalArgumentException("Cannot determine factory method return type, got "+factoryMethodTypeArgument+" - for field "+fieldName+" in "+beanClass+", cannot determine collection type (inner type argument)");
}
} else {
throw new IllegalArgumentException("Ejha! "+innerTypeArgument+" "+innerTypeArgument.getClass()+" from "+getterReturnType+" from "+fieldName+" in "+propName+" "+beanClass);
}
} else {
// The case of Collection<Whatever<Something>>
if (rawTypeArgument instanceof Class) {
paramType = (Class<?>) rawTypeArgument;
} else {
throw new IllegalArgumentException("EH? Eh!? "+typeArgument+" "+typeArgument.getClass()+" from "+getterReturnType+" from "+fieldName+" in "+propName+" "+beanClass);
}
}
} else {
throw new IllegalArgumentException("EH? "+typeArgument+" "+typeArgument.getClass()+" from "+getterReturnType+" from "+fieldName+" in "+propName+" "+beanClass);
}
} else {
Class<?> setterType = setter.getParameterTypes()[0];
if (JAXBElement.class.equals(setterType)){
// 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 = getTypeArgument(genericType, "add some description");
if (actualType instanceof WildcardType) {
if (elementMethod == null) {
Class objectFactoryClass = inspector.getObjectFactoryClass(beanClass.getPackage());
objectFactory = instantiateObjectFactory(objectFactoryClass);
elementMethod = inspector.findElementMethodInObjectFactory(objectFactoryClass, propName);
}
// This is the case of Collection<JAXBElement<?>>
// we need to exctract the specific type from the factory method
if (elementMethod == null) {
throw new IllegalArgumentException("Wildcard type in JAXBElement field specification and no facotry method found for field "+fieldName+" in "+beanClass+", cannot determine collection type (inner type argument)");
}
Type factoryMethodGenericReturnType = elementMethod.getGenericReturnType();
Type factoryMethodTypeArgument = getTypeArgument(factoryMethodGenericReturnType, "in factory method "+elementMethod+" return type for field "+fieldName+" 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 "+elementMethod+" type argument is Object (without @Raw) for field "+
fieldName+" in "+beanClass+", property "+propName);
}
} else {
throw new IllegalArgumentException("Cannot determine factory method return type, got "+factoryMethodTypeArgument+" - for field "+fieldName+" 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 = setterType;
}
}
if (Element.class.isAssignableFrom(paramType)) {
// DOM!
throw new IllegalArgumentException("DOM not supported in field "+fieldName+" in "+beanClass);
}
//check for subclasses???
if (!storeAsRawType && xsubnode != null && xsubnode.getTypeQName() != null) {
Class explicitParamType = getSchemaRegistry().determineCompileTimeClass(xsubnode.getTypeQName());
if (explicitParamType == null){
explicitParamType = XsdTypeMapper.toJavaTypeIfKnown(xsubnode.getTypeQName());
}
if (explicitParamType != null){
paramType = explicitParamType;
}
}
if (!(xsubnode instanceof ListXNode) && Object.class.equals(paramType) && !storeAsRawType) {
throw new IllegalArgumentException("Object property (without @Raw) not supported in field "+fieldName+" in "+beanClass);
}
String paramNamespace = inspector.determineNamespace(paramType);
boolean problem = false;
Object propValue = null;
Collection<Object> propValues = null;
if (xsubnode instanceof ListXNode) {
ListXNode xlist = (ListXNode)xsubnode;
if (setter != null) {
try {
propValue = convertSinglePropValue(xsubnode, fieldName, paramType, storeAsRawType, beanClass, paramNamespace, pc);
} catch (SchemaException e) {
problem = processSchemaException(e, xsubnode, pc);
}
} else {
// No setter, we have to use collection getter
propValues = new ArrayList<>(xlist.size());
for (XNode xsubsubnode: xlist) {
try {
propValues.add(convertSinglePropValue(xsubsubnode, fieldName, paramType, storeAsRawType, beanClass, paramNamespace, pc));
} catch (SchemaException e) {
problem = processSchemaException(e, xsubsubnode, pc);
}
}
}
} else {
try {
propValue = convertSinglePropValue(xsubnode, fieldName, paramType, storeAsRawType, beanClass, paramNamespace, pc);
} catch (SchemaException e) {
problem = processSchemaException(e, xsubnode, pc);
}
}
if (setter != null) {
Object value = null;
try {
value = prepareValueToBeStored(propValue, wrapInJaxbElement, objectFactory, elementMethod, propName, beanClass, pc);
setter.invoke(bean, value);
} 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(prepareValueToBeStored(propValue, wrapInJaxbElement, objectFactory, elementMethod, propName, beanClass, pc));
} else if (propValues != null) {
for (Object propVal: propValues) {
col.add(prepareValueToBeStored(propVal, wrapInJaxbElement, objectFactory, elementMethod, propName, beanClass, pc));
}
} else if (!problem) {
throw new IllegalStateException("Strange. Multival property "+propName+" in "+beanClass+" produced null values list, parsed from "+xnode);
}
checkJaxbElementConsistence(col, pc);
} else {
throw new IllegalStateException("Uh? No setter nor getter.");
}
}
if (prismContext != null && bean instanceof Revivable) {
((Revivable)bean).revive(prismContext);
}
return bean;
}
/*
* 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);
}
}
}
}
}
protected boolean processSchemaException(SchemaException e, XNode 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:\n{}", e, xsubnode);
pc.warn("Couldn't parse part of the document. It will be ignored. Document part:\n" + xsubnode);
return true;
}
}
private <T,S> void unmarshallToAny(T bean, Method getter, QName elementName, XNode 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 ListXNode){
for (XNode xsubSubNode : ((ListXNode) xsubnode)){
S subBean = unmarshall(xsubSubNode, subBeanClass, pc);
unmarshallToAnyValue(bean, beanClass, subBean, objectFactoryClass, objectFactory, elementFactoryMethod, getter, pc);
}
} else{
S subBean = unmarshall(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() : subBeanElement);
}
private <T,S> void unmarshallToAny(T bean, Field anyField, QName elementName, XNode xsubnode, ParsingContext pc) throws SchemaException{
Method getter = inspector.findPropertyGetter(bean.getClass(), anyField.getName());
unmarshallToAny(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);
}
}
// parses any subtype of SearchFilterType
private <T extends SearchFilterType> T unmarshalSearchFilterType(MapXNode xmap, Class<T> beanClass, ParsingContext pc) throws SchemaException {
if (xmap == null) {
return null;
}
T filterType;
try {
filterType = beanClass.newInstance();
} catch (InstantiationException|IllegalAccessException e) {
throw new SystemException("Cannot instantiate " + beanClass + ": " + e.getMessage(), e);
}
filterType.parseFromXNode(xmap, prismContext);
return filterType;
}
private MapXNode marshalSearchFilterType(SearchFilterType value) throws SchemaException {
if (value == null) {
return null;
}
return value.serializeToXNode();
}
private Type getTypeArgument(Type origType, String desc) {
if (!(origType instanceof ParameterizedType)) {
throw new IllegalArgumentException("No a parametrized type "+desc);
}
ParameterizedType parametrizedType = (ParameterizedType)origType;
Type[] actualTypeArguments = parametrizedType.getActualTypeArguments();
if (actualTypeArguments == null || actualTypeArguments.length == 0) {
throw new IllegalArgumentException("No type arguments for getter "+desc);
}
if (actualTypeArguments.length > 1) {
throw new IllegalArgumentException("Too many type arguments for getter for "+desc);
}
return actualTypeArguments[0];
}
// Prepares value to be stored into the bean - e.g. converts PolyString->PolyStringType, wraps a value to JAXB if specified, ...
private <T> Object prepareValueToBeStored(Object propVal, boolean wrapInJaxbElement, Object objectFactory, Method factoryMehtod, String propName,
Class beanClass, ParsingContext pc) {
if (propVal instanceof PolyString) {
propVal = new PolyStringType((PolyString) propVal);
}
if (wrapInJaxbElement) {
if (factoryMehtod == null) {
throw new IllegalArgumentException("Param type is JAXB element but no factory method found for it, property "+propName+" in "+beanClass);
}
try {
return factoryMehtod.invoke(objectFactory, propVal);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new SystemException("Unable to invoke factory method "+factoryMehtod+" on "+objectFactory.getClass()+" for property "+propName+" in "+beanClass);
}
} else {
return propVal;
}
}
private Object convertSinglePropValue(XNode xsubnode, String fieldName, Class paramType, boolean storeAsRawType,
Class classType, String schemaNamespace, ParsingContext pc) throws SchemaException {
Object propValue;
if (xsubnode == null) {
return null;
} else if (paramType.equals(XNode.class)) {
propValue = xsubnode;
} else if (storeAsRawType || paramType.equals(RawType.class)) {
propValue = new RawType(xsubnode, prismContext);
} else {
// paramType is what we expect e.g. based on parent definition
// but actual type (given by xsi:type/@typeDef) may be different, e.g. more specific
if (xsubnode.getTypeQName() != null) {
Class explicitParamType = getSchemaRegistry().determineCompileTimeClass(xsubnode.getTypeQName());
if (explicitParamType != null) {
paramType = explicitParamType;
} else {
// TODO or throw an exception?
LOGGER.warn("Unknown type name: " + xsubnode.getTypeQName() + ", ignoring it.");
}
}
if (xsubnode instanceof PrimitiveXNode<?>) {
propValue = unmarshallPrimitive(((PrimitiveXNode<?>)xsubnode), paramType, pc);
} else if (xsubnode instanceof MapXNode) {
propValue = unmarshall((MapXNode)xsubnode, paramType, pc);
} else if (xsubnode instanceof ListXNode) {
ListXNode xlist = (ListXNode)xsubnode;
if (xlist.size() > 1) {
throw new SchemaException("Cannot set multi-value value to a single valued property "+fieldName+" of "+classType);
} else {
if (xlist.isEmpty()) {
propValue = null;
} else {
propValue = xlist.get(0);
}
}
} else {
throw new IllegalArgumentException("Cannot parse "+xsubnode+" to a bean "+classType);
}
}
return propValue;
}
public <T> T unmarshallPrimitive(PrimitiveXNode<?> xprim, QName typeQName, ParsingContext pc) throws SchemaException {
Class<T> classType = getSchemaRegistry().determineCompileTimeClass(typeQName);
return unmarshallPrimitive(xprim, classType, pc);
}
private <T> T unmarshallPrimitive(PrimitiveXNode<?> xprim, Class<T> classType, ParsingContext pc) throws SchemaException {
if (XmlAsStringType.class.equals(classType)) {
return (T) new XmlAsStringType((String) xprim.getParsedValue(DOMUtil.XSD_STRING));
}
if (XmlTypeConverter.canConvert(classType)) {
// Trivial case, direct conversion
QName xsdType = XsdTypeMapper.toXsdType(classType);
T primValue = postConvertUnmarshall(xprim.getParsedValue(xsdType), pc);
return primValue;
}
if (RawType.class.isAssignableFrom(classType)) {
RawType rawType = new RawType(xprim, prismContext);
return (T) rawType;
}
if (PolyStringType.class.isAssignableFrom(classType)) {
String value = (String) xprim.getParsedValue(DOMUtil.XSD_STRING);
PolyString polyString = new PolyString(value);
if (value != null) {
if (prismContext != null) { // actually this should be always so [med]
// TODO should we always use default normalizer?
polyString.recompute(prismContext.getDefaultPolyStringNormalizer());
}
}
return (T) new PolyStringType(polyString);
}
if (ItemPathType.class.isAssignableFrom(classType)){
Object parsedValue = xprim.getParsedValue(ItemPathType.COMPLEX_TYPE);
T primValue = postConvertUnmarshall(parsedValue, pc);
return (T) primValue;
}
if (SearchFilterType.class.isAssignableFrom(classType)){
throw new SchemaException("Cannot unmarshall search filter from "+xprim);
}
if (xprim.isEmpty() && !classType.isEnum()) {
// Special case. Just return empty object
try {
return classType.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new SystemException("Cannot instantiate "+classType+": "+e.getMessage(), e);
}
}
if (!classType.isEnum()) {
throw new SchemaException("Cannot convert primitive value to non-enum bean of type " + classType);
}
// Assume string, maybe TODO extend later
String primValue = (String) xprim.getParsedValue(DOMUtil.XSD_STRING);
if (StringUtils.isBlank(primValue)) {
return null;
}
primValue = StringUtils.trim(primValue);
String javaEnumString = inspector.findEnumFieldName(classType, primValue);
// for (Field field: classType.getDeclaredFields()) {
// XmlEnumValue xmlEnumValue = field.getAnnotation(XmlEnumValue.class);
// if (xmlEnumValue != null && xmlEnumValue.value() != null && xmlEnumValue.value().equals(primValue)) {
// javaEnumString = field.getName();
// break;
// }
// }
if (javaEnumString == null) {
for (Field field: classType.getDeclaredFields()) {
if (field.getName().equals(primValue)) {
javaEnumString = field.getName();
break;
}
}
}
if (javaEnumString == null) {
throw new SchemaException("Cannot find enum value for string '"+primValue+"' in "+classType);
}
T bean = (T) Enum.valueOf((Class<Enum>)classType, javaEnumString);
return bean;
}
// TODO hacked, for now
// private <T> String findEnumFieldValue(Class classType, Object bean){
// String name = bean.toString();
// for (Field field: classType.getDeclaredFields()) {
// XmlEnumValue xmlEnumValue = field.getAnnotation(XmlEnumValue.class);
// if (xmlEnumValue != null && field.getName().equals(name)) {
// return xmlEnumValue.value();
// }
// }
// return null;
// }
private <T> T postConvertUnmarshall(Object parsedPrimValue, ParsingContext pc) {
if (parsedPrimValue == null) {
return null;
}
if (parsedPrimValue instanceof ItemPath) {
return (T) new ItemPathType((ItemPath)parsedPrimValue);
} else {
return (T) parsedPrimValue;
}
}
public <T> XNode marshall(T bean) throws SchemaException {
return marshall(bean, null);
}
public <T> XNode marshall(T bean, SerializationContext ctx) throws SchemaException {
if (bean == null) {
return null;
}
if (bean instanceof SchemaDefinitionType) {
return marshalSchemaDefinition((SchemaDefinitionType) bean);
} else if (bean instanceof ProtectedDataType<?>) {
MapXNode xProtected = marshalProtectedDataType((ProtectedDataType<?>) bean);
return xProtected;
} else if (bean instanceof ItemPathType){
return marshalItemPathType((ItemPathType) bean);
} else if (bean instanceof RawType) {
return marshalRawValue((RawType) bean);
} else if (bean instanceof XmlAsStringType) {
return marshalXmlAsStringType((XmlAsStringType) bean);
} else if (prismContext != null && prismContext.getSchemaRegistry().determineDefinitionFromClass(bean.getClass()) != null){
return ((PrismContextImpl) prismContext).getPrismMarshaller().marshalItem(((Objectable)bean).asPrismObject(),
null, null, ctx).getSubnode();
}
// Note: SearchFilterType is treated below
Class<? extends Object> beanClass = bean.getClass();
if (beanClass == String.class) {
return createPrimitiveXNode((String)bean, DOMUtil.XSD_STRING, false);
}
//check for enums
if (beanClass.isEnum()){
String enumValue = inspector.findEnumFieldValue(beanClass, bean.toString());
if (StringUtils.isEmpty(enumValue)){
enumValue = bean.toString();
}
QName fieldTypeName = inspector.findFieldTypeName(null, beanClass, DEFAULT_PLACEHOLDER);
return createPrimitiveXNode(enumValue, fieldTypeName, false);
}
MapXNode xmap;
if (bean instanceof SearchFilterType) {
// this hack is here because of c:ConditionalSearchFilterType - it is analogous to situation when unmarshalling this type (TODO: rework this in a nicer way)
xmap = marshalSearchFilterType((SearchFilterType) bean);
if (SearchFilterType.class.equals(bean.getClass())) {
return xmap; // nothing more to serialize; otherwise we continue, because in that case we deal with a subclass of SearchFilterType
}
} else {
xmap = new MapXNode();
}
XmlType xmlType = beanClass.getAnnotation(XmlType.class);
if (xmlType == null) {
throw new IllegalArgumentException("Cannot marshall "+beanClass+" it does not have @XmlType annotation");
}
String namespace = inspector.determineNamespace(beanClass);
if (namespace == null) {
throw new IllegalArgumentException("Cannot determine namespace of "+beanClass);
}
List<String> propOrder = inspector.getPropOrder(beanClass);
for (String fieldName: propOrder) {
QName elementName = inspector.findFieldElementQName(fieldName, beanClass, namespace);
Method getter = inspector.findPropertyGetter(beanClass, fieldName);
if (getter == null) {
throw new IllegalStateException("No getter for field "+fieldName+" in "+beanClass);
}
Object getterResult;
try {
getterResult = getter.invoke(bean);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new SystemException("Cannot invoke method for field "+fieldName+" in "+beanClass+": "+e.getMessage(), e);
}
if (getterResult == null) {
continue;
}
Field field = inspector.findPropertyField(beanClass, fieldName);
boolean isAttribute = inspector.isAttribute(field, getter);
if (getterResult instanceof Collection<?>) {
Collection col = (Collection)getterResult;
if (col.isEmpty()) {
continue;
}
Iterator i = col.iterator();
if (i == null) {
// huh?!? .. but it really happens
throw new IllegalArgumentException("Iterator of collection returned from "+getter+" is null");
}
Object getterResultValue = i.next();
if (getterResultValue == null) {
continue;
}
ListXNode xlist = new ListXNode();
// elementName will be determined from the first item on the list
// TODO make sure it will be correct with respect to other items as well!
if (getterResultValue instanceof JAXBElement && ((JAXBElement) getterResultValue).getName() != null) {
elementName = ((JAXBElement) getterResultValue).getName();
}
for (Object element: col) {
if (element == null){
continue;
}
QName fieldTypeName = inspector.findFieldTypeName(field, element.getClass(), namespace);
Object elementToMarshall = element;
if (element instanceof JAXBElement){
elementToMarshall = ((JAXBElement) element).getValue();
}
XNode marshalled = marshallValue(elementToMarshall, fieldTypeName, isAttribute, ctx);
// Brutal hack - made here just to make scripts (bulk actions) functional while not breaking anything else
// Fix it in 3.1. [med]
if (fieldTypeName == null && element instanceof JAXBElement && marshalled != null) {
QName typeName = inspector.determineTypeForClass(elementToMarshall.getClass());
if (typeName != null && !getSchemaRegistry().hasImplicitTypeDefinition(elementName, typeName)) {
marshalled.setExplicitTypeDeclaration(true);
marshalled.setTypeQName(typeName);
}
}
else {
// end of hack
setExplicitTypeDeclarationIfNeeded(getter, getterResultValue, marshalled, fieldTypeName);
}
xlist.add(marshalled);
}
xmap.put(elementName, xlist);
} else {
QName fieldTypeName = inspector.findFieldTypeName(field, getterResult.getClass(), namespace);
Object valueToMarshall = null;
if (getterResult instanceof JAXBElement){
valueToMarshall = ((JAXBElement) getterResult).getValue();
elementName = ((JAXBElement) getterResult).getName();
} else{
valueToMarshall = getterResult;
}
XNode marshelled = marshallValue(valueToMarshall, fieldTypeName, isAttribute, ctx);
if (!getter.getReturnType().equals(valueToMarshall.getClass()) && getter.getReturnType().isAssignableFrom(valueToMarshall.getClass())){
if (prismContext != null) {
PrismObjectDefinition def = prismContext.getSchemaRegistry().determineDefinitionFromClass(valueToMarshall.getClass());
if (def != null){
QName type = def.getTypeName();
marshelled.setTypeQName(type);
marshelled.setExplicitTypeDeclaration(true);
}
}
}
xmap.put(elementName, marshelled);
// setExplicitTypeDeclarationIfNeeded(getter, valueToMarshall, xmap, fieldTypeName);
}
}
return xmap;
}
private XNode marshalXmlAsStringType(XmlAsStringType bean) {
PrimitiveXNode xprim = new PrimitiveXNode<>();
xprim.setValue(bean.getContentAsString(), DOMUtil.XSD_STRING);
return xprim;
}
public void revive(Object bean, final PrismContext prismContext) throws SchemaException {
Handler<Object> visitor = new Handler<Object>() {
@Override
public boolean handle(Object o) {
if (o instanceof Revivable) {
try {
((Revivable)o).revive(prismContext);
} catch (SchemaException e) {
throw new TunnelException(e);
}
}
return true;
}
};
try {
visit(bean,visitor);
} catch (TunnelException te) {
SchemaException e = (SchemaException) te.getCause();
throw e;
}
}
public void visit(Object bean, Handler<Object> handler) {
if (bean == null) {
return;
}