-
Notifications
You must be signed in to change notification settings - Fork 188
/
BeanMarshaller.java
564 lines (494 loc) · 21.7 KB
/
BeanMarshaller.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
/*
* Copyright (c) 2010-2017 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.polystring.PolyString;
import com.evolveum.midpoint.prism.schema.SchemaRegistry;
import com.evolveum.midpoint.prism.xml.XsdTypeMapper;
import com.evolveum.midpoint.prism.xnode.*;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.Handler;
import com.evolveum.midpoint.util.MiscUtil;
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.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.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.namespace.QName;
import java.lang.reflect.*;
import java.util.*;
public class BeanMarshaller {
private static final Trace LOGGER = TraceManager.getTrace(BeanMarshaller.class);
public static final String DEFAULT_PLACEHOLDER = "##default";
@NotNull private final PrismBeanInspector inspector;
@NotNull private final PrismContext prismContext;
@NotNull private final Map<Class,Marshaller> specialMarshallers = new HashMap<>();
@FunctionalInterface
private interface Marshaller {
XNode marshal(Object bean, SerializationContext sc) throws SchemaException;
}
private void createSpecialMarshallerMap() {
specialMarshallers.put(XmlAsStringType.class, this::marshalXmlAsStringType);
specialMarshallers.put(SchemaDefinitionType.class, this::marshalSchemaDefinition);
specialMarshallers.put(ProtectedByteArrayType.class, this::marshalProtectedDataType);
specialMarshallers.put(ProtectedStringType.class, this::marshalProtectedDataType);
specialMarshallers.put(ItemPathType.class, this::marshalItemPathType);
specialMarshallers.put(RawType.class, this::marshalRawType);
// add(PolyString.class, this::unmarshalPolyStringFromPrimitive, this::unmarshalPolyStringFromMap);
// add(PolyStringType.class, this::unmarshalPolyStringFromPrimitive, this::unmarshalPolyStringFromMap);
}
public BeanMarshaller(@NotNull PrismContext prismContext, @NotNull PrismBeanInspector inspector) {
this.prismContext = prismContext;
this.inspector = inspector;
createSpecialMarshallerMap();
}
@Nullable
public <T> XNode marshall(@Nullable T bean) throws SchemaException {
return marshall(bean, null);
}
@Nullable
public <T> XNode marshall(@Nullable T bean, @Nullable SerializationContext ctx) throws SchemaException {
if (bean == null) {
return null;
}
Marshaller marshaller = specialMarshallers.get(bean.getClass());
if (marshaller != null) {
return marshaller.marshal(bean, ctx);
}
// avoiding chatty PolyString serializations (namespace declaration + orig + norm)
if (bean instanceof PolyString) {
bean = (T) ((PolyString) bean).getOrig();
} else if (bean instanceof PolyStringType) {
bean = (T) ((PolyStringType) bean).getOrig();
}
if (bean instanceof Containerable) {
return prismContext.xnodeSerializer().context(ctx).serializeRealValue(bean, new QName("dummy")).getSubnode();
} else if (bean instanceof Enum) {
return marshalEnum((Enum) bean, ctx);
} else if (bean.getClass().getAnnotation(XmlType.class) != null) {
return marshalXmlType(bean, ctx);
} else {
return marshalToPrimitive(bean, ctx);
}
}
private XNode marshalToPrimitive(Object bean, SerializationContext ctx) {
return createPrimitiveXNode(bean, null, false);
}
private XNode marshalXmlType(Object bean, SerializationContext ctx) throws SchemaException {
Class<?> beanClass = bean.getClass();
ComplexTypeDefinition ctd = getSchemaRegistry()
.findTypeDefinitionByCompileTimeClass(beanClass, ComplexTypeDefinition.class);
Field valueField = XNodeProcessorUtil.findXmlValueField(beanClass);
if (valueField != null) {
return marshallBeanToPrimitive(bean, ctx, valueField);
}
if (ctd != null && ctd.isListMarker()) {
return marshalHeterogeneousList(bean, ctx);
} else {
return marshalXmlTypeToMap(bean, ctx);
}
}
/**
* For cases when XSD complex type has a simple content. In that case the resulting class has @XmlValue annotation.
*/
private <T> PrimitiveXNode<T> marshallBeanToPrimitive(Object bean, SerializationContext ctx, Field valueField) throws SchemaException {
if (!valueField.isAccessible()) {
valueField.setAccessible(true);
}
T value;
try {
value = (T) valueField.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new SchemaException("Cannot get primitive value from field " + valueField.getName() + " of bean " + bean + ": "+e.getMessage(), e);
}
PrimitiveXNode<T> xnode = new PrimitiveXNode<>(value);
Class<?> fieldType = valueField.getType();
QName xsdType = XsdTypeMapper.toXsdType(fieldType);
xnode.setTypeQName(xsdType);
return xnode;
}
private XNode marshalHeterogeneousList(Object bean, SerializationContext ctx) throws SchemaException {
// structurally similar to a specific path through marshalXmlTypeToMap
Class<?> beanClass = bean.getClass();
QName propertyName = getHeterogeneousListPropertyName(beanClass);
Method getter = inspector.findPropertyGetter(beanClass, propertyName.getLocalPart());
Object getterResult = getValue(bean, getter, propertyName.getLocalPart());
if (!(getterResult instanceof Collection)) {
throw new IllegalStateException("Heterogeneous list property " + propertyName
+ " does not contain a collection but " + MiscUtil.getObjectName(getterResult));
}
ListXNode xlist = new ListXNode();
for (Object value : (Collection) getterResult) {
if (!(value instanceof JAXBElement)) {
throw new IllegalStateException("Heterogeneous list contains a value that is not a JAXBElement: " + value);
}
JAXBElement jaxbElement = (JAXBElement) value;
Object realValue = jaxbElement.getValue();
if (realValue == null) {
throw new IllegalStateException("Heterogeneous list contains a null value"); // TODO
}
QName typeName = inspector.determineTypeForClass(realValue.getClass());
XNode marshaled = marshallValue(realValue, typeName, false, ctx);
marshaled.setElementName(jaxbElement.getName());
setExplicitTypeDeclarationIfNeededForHeteroList(marshaled, realValue);
xlist.add(marshaled);
}
return xlist;
}
private XNode marshalXmlTypeToMap(Object bean, SerializationContext ctx) throws SchemaException {
Class<?> beanClass = bean.getClass();
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();
}
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) {
Method getter = inspector.findPropertyGetter(beanClass, fieldName);
if (getter == null) {
throw new IllegalStateException("No getter for field "+fieldName+" in "+beanClass);
}
Object getterResult = getValue(bean, getter, fieldName);
if (getterResult == null) {
continue;
}
Field field = inspector.findPropertyField(beanClass, fieldName);
boolean isAttribute = inspector.isAttribute(field, getter);
QName elementName = inspector.findFieldElementQName(fieldName, beanClass, namespace);
if (getterResult instanceof Collection<?>) {
Collection collection = (Collection) getterResult;
if (collection.isEmpty()) {
continue;
}
Iterator i = collection.iterator();
Object getterResultValue = i.next();
if (getterResultValue == null) {
continue;
}
// 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();
}
ListXNode xlist = new ListXNode();
for (Object value: collection) {
if (value == null) {
continue;
}
Object valueToMarshal = value;
if (value instanceof JAXBElement) {
valueToMarshal = ((JAXBElement) value).getValue();
}
QName typeName = inspector.findTypeName(field, valueToMarshal.getClass(), namespace);
// note: fieldTypeName is used only for attribute values here (when constructing PrimitiveXNode)
XNode marshaled = marshallValue(valueToMarshal, typeName, isAttribute, ctx);
setExplicitTypeDeclarationIfNeeded(marshaled, getter, valueToMarshal, typeName);
xlist.add(marshaled);
}
xmap.put(elementName, xlist);
} else {
QName fieldTypeName = inspector.findTypeName(field, getterResult.getClass(), namespace);
Object valueToMarshall;
if (getterResult instanceof JAXBElement) {
valueToMarshall = ((JAXBElement) getterResult).getValue();
elementName = ((JAXBElement) getterResult).getName();
} else {
valueToMarshall = getterResult;
}
XNode marshaled = marshallValue(valueToMarshall, fieldTypeName, isAttribute, ctx);
// TODO reconcile with setExplicitTypeDeclarationIfNeeded
if (!getter.getReturnType().equals(valueToMarshall.getClass()) && getter.getReturnType().isAssignableFrom(valueToMarshall.getClass()) && !(valueToMarshall instanceof Enum)) {
TypeDefinition def = prismContext.getSchemaRegistry().findTypeDefinitionByCompileTimeClass(valueToMarshall.getClass(), TypeDefinition.class);
if (def != null) {
QName type = def.getTypeName();
marshaled.setTypeQName(type);
marshaled.setExplicitTypeDeclaration(true);
}
}
xmap.put(elementName, marshaled);
// setExplicitTypeDeclarationIfNeeded(getter, valueToMarshall, xmap, fieldTypeName);
}
}
return xmap;
}
private Object getValue(Object bean, Method getter, String fieldOrPropertyName) {
Object getterResult;
try {
getterResult = getter.invoke(bean);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new SystemException("Cannot invoke method for field/property "+fieldOrPropertyName+" in "+bean.getClass()+": "+e.getMessage(), e);
}
return getterResult;
}
private XNode marshalEnum(Enum enumValue, SerializationContext ctx) {
Class<? extends Enum> enumClass = enumValue.getClass();
String enumStringValue = inspector.findEnumFieldValue(enumClass, enumValue.toString());
if (StringUtils.isEmpty(enumStringValue)){
enumStringValue = enumValue.toString();
}
QName fieldTypeName = inspector.findTypeName(null, enumClass, DEFAULT_PLACEHOLDER);
return createPrimitiveXNode(enumStringValue, fieldTypeName, false);
}
private XNode marshalXmlAsStringType(Object bean, SerializationContext sc) {
PrimitiveXNode xprim = new PrimitiveXNode<>();
xprim.setValue(((XmlAsStringType) bean).getContentAsString(), DOMUtil.XSD_STRING);
return xprim;
}
public void revive(Object bean, final PrismContext prismContext) throws SchemaException {
Handler<Object> visitor = 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;
}
Class<? extends Object> beanClass = bean.getClass();
handler.handle(bean);
if (beanClass.isEnum() || beanClass.isPrimitive()){
//nothing more to do
return;
}
// TODO: implement special handling for RawType, if necessary (it has no XmlType annotation any more)
XmlType xmlType = beanClass.getAnnotation(XmlType.class);
if (xmlType == null) {
// no @XmlType annotation, we are not interested to go any deeper
return;
}
List<String> propOrder = inspector.getPropOrder(beanClass);
for (String fieldName: propOrder) {
Method getter = inspector.findPropertyGetter(beanClass, fieldName);
if (getter == null) {
throw new IllegalStateException("No getter for field "+fieldName+" in "+beanClass);
}
Object getterResult = getValue(bean, getter, fieldName);
if (getterResult == null) {
continue;
}
if (getterResult instanceof Collection<?>) {
Collection col = (Collection)getterResult;
if (col.isEmpty()) {
continue;
}
for (Object element: col) {
visitValue(element, handler);
}
} else {
visitValue(getterResult, handler);
}
}
}
private void visitValue(Object element, Handler<Object> handler) {
Object elementToMarshall = element;
if (element instanceof JAXBElement){
elementToMarshall = ((JAXBElement) element).getValue();
}
visit(elementToMarshall, handler);
}
private void setExplicitTypeDeclarationIfNeededForHeteroList(XNode node, Object realValue) {
QName elementName = node.getElementName();
QName typeName = inspector.determineTypeForClass(realValue.getClass());
if (typeName != null && !getSchemaRegistry().hasImplicitTypeDefinition(elementName, typeName)
&& getSchemaRegistry().findTypeDefinitionByType(typeName, TypeDefinition.class) != null) {
node.setExplicitTypeDeclaration(true);
node.setTypeQName(typeName);
}
}
// TODO shouldn't we use here the same approach as above?
private void setExplicitTypeDeclarationIfNeeded(XNode node, Method getter, Object getterResult, QName typeName) {
if (typeName == null) {
// the idea is not to overwrite pre-existing explicit type declaration with null value
// TODO reconsider
return;
}
Class getterReturnType = getter.getReturnType();
Class getterType = null;
if (Collection.class.isAssignableFrom(getterReturnType)) {
Type genericReturnType = getter.getGenericReturnType();
if (genericReturnType instanceof ParameterizedType) {
Type actualType = inspector.getTypeArgument(genericReturnType, "explicit type declaration");
if (actualType instanceof Class) {
getterType = (Class) actualType;
} else if (actualType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) actualType;
Type typeArgument = inspector.getTypeArgument(parameterizedType, "JAXBElement return type");
getterType = inspector.getUpperBound(typeArgument, "JAXBElement return type");
}
}
}
if (getterType == null) {
getterType = getterReturnType;
}
Class getterResultReturnType = getterResult.getClass();
if (node != null && getterType != getterResultReturnType && getterType.isAssignableFrom(getterResultReturnType)) {
node.setExplicitTypeDeclaration(true);
node.setTypeQName(typeName);
}
}
// bean should have only two features: "list" attribute and multivalued property into which we should store the elements
@NotNull
<T> QName getHeterogeneousListPropertyName(Class<T> beanClass) throws SchemaException {
List<String> properties = inspector.getPropOrder(beanClass);
if (!properties.contains(DOMUtil.IS_LIST_ATTRIBUTE_NAME)) {
throw new SchemaException("Couldn't unmarshal heterogeneous list into class without '"
+ DOMUtil.IS_LIST_ATTRIBUTE_NAME + "' attribute. Class: "
+ beanClass.getName() + " has the following properties: " + properties);
}
if (properties.size() > 2) {
throw new SchemaException("Couldn't unmarshal heterogeneous list into class with more than one property "
+ "other than '" + DOMUtil.IS_LIST_ATTRIBUTE_NAME + "'. Class " + beanClass.getName()
+ " has the following properties: " + properties);
}
String contentProperty = properties.stream()
.filter(p -> !DOMUtil.IS_LIST_ATTRIBUTE_NAME.equals(p))
.findFirst()
.orElseThrow(() -> new SchemaException("Couldn't unmarshal heterogeneous list into class without "
+ "content-holding property. Class: " + beanClass.getName() + "."));
return new QName(inspector.determineNamespace(beanClass), contentProperty);
}
private <T> XNode marshallValue(T value, QName valueType, boolean isAttribute, SerializationContext ctx) throws SchemaException {
if (value == null) {
return null;
}
if (isAttribute) {
// hoping the value fits into primitive!
return createPrimitiveXNode(value, valueType, true);
} else {
return marshall(value, ctx);
}
}
private <T> PrimitiveXNode<T> createPrimitiveXNode(T value, QName valueType, boolean isAttribute) {
PrimitiveXNode<T> xprim = new PrimitiveXNode<>();
xprim.setValue(value, valueType);
xprim.setAttribute(isAttribute);
return xprim;
}
private <T> PrimitiveXNode<T> createPrimitiveXNode(T val, QName type) {
return createPrimitiveXNode(val, type, false);
}
private XNode marshalRawType(Object value, SerializationContext sc) throws SchemaException {
return ((RawType) value).serializeToXNode();
}
private XNode marshalItemPathType(Object o, SerializationContext sc) {
ItemPathType itemPath = (ItemPathType) o;
PrimitiveXNode<ItemPathType> xprim = new PrimitiveXNode<>();
if (itemPath != null) {
xprim.setValue(itemPath, ItemPathType.COMPLEX_TYPE);
}
return xprim;
}
private XNode marshalSchemaDefinition(Object o, SerializationContext ctx) {
SchemaDefinitionType schemaDefinitionType = (SchemaDefinitionType) o;
SchemaXNode xschema = new SchemaXNode();
xschema.setSchemaElement(schemaDefinitionType.getSchema());
MapXNode xmap = new MapXNode();
xmap.put(DOMUtil.XSD_SCHEMA_ELEMENT, xschema);
return xmap;
}
// TODO create more appropriate interface to be able to simply serialize ProtectedStringType instances
public <T> MapXNode marshalProtectedDataType(Object o, SerializationContext sc) throws SchemaException {
ProtectedDataType<T> protectedType = (ProtectedDataType<T>) o;
MapXNode xmap = new MapXNode();
if (protectedType.getEncryptedDataType() != null) {
EncryptedDataType encryptedDataType = protectedType.getEncryptedDataType();
MapXNode xEncryptedDataType = (MapXNode) marshall(encryptedDataType);
xmap.put(ProtectedDataType.F_ENCRYPTED_DATA, xEncryptedDataType);
} else if (protectedType.getHashedDataType() != null) {
HashedDataType hashedDataType = protectedType.getHashedDataType();
MapXNode xHashedDataType = (MapXNode) marshall(hashedDataType);
xmap.put(ProtectedDataType.F_HASHED_DATA, xHashedDataType);
} else if (protectedType.getClearValue() != null){
QName type = XsdTypeMapper.toXsdType(protectedType.getClearValue().getClass());
PrimitiveXNode xClearValue = createPrimitiveXNode(protectedType.getClearValue(), type);
xmap.put(ProtectedDataType.F_CLEAR_VALUE, xClearValue);
}
// TODO: clearValue
return xmap;
}
//region Specific marshallers ==============================================================
private MapXNode marshalSearchFilterType(SearchFilterType value) throws SchemaException {
if (value == null) {
return null;
}
return value.serializeToXNode();
}
//endregion
@NotNull
public PrismContext getPrismContext() {
return prismContext;
}
private SchemaRegistry getSchemaRegistry() {
return prismContext.getSchemaRegistry();
}
public boolean canProcess(QName typeName) {
Class<Object> clazz = getSchemaRegistry().determineClassForType(typeName);
if (clazz != null && canProcess(clazz)) {
return true;
}
TypeDefinition td = getSchemaRegistry().findTypeDefinitionByType(typeName);
if (td instanceof SimpleTypeDefinition) {
return true; // most probably dynamic enum, at this point
}
return false;
}
public boolean canProcess(@NotNull Class<?> clazz) {
return !Containerable.class.isAssignableFrom(clazz) &&
(RawType.class.equals(clazz) || clazz.getAnnotation(XmlType.class) != null || XsdTypeMapper.getTypeFromClass(clazz) != null);
}
public QName determineTypeForClass(Class<?> clazz) {
return inspector.determineTypeForClass(clazz);
}
}
// 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;
// }