1 package org.opendaylight.controller.sal.binding.dom.serializer.impl;
3 import java.awt.CompositeContext;
4 import java.lang.ref.WeakReference;
5 import java.lang.reflect.Field;
6 import java.lang.reflect.ParameterizedType;
7 import java.util.ArrayList;
8 import java.util.Collection;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.Iterator;
13 import java.util.List;
15 import java.util.Map.Entry;
16 import java.util.Objects;
17 import java.util.concurrent.Callable;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ConcurrentMap;
21 import java.util.WeakHashMap;
23 import org.apache.commons.lang3.text.translate.AggregateTranslator;
24 import org.opendaylight.controller.sal.binding.dom.serializer.api.AugmentationCodec;
25 import org.opendaylight.controller.sal.binding.dom.serializer.api.ChoiceCaseCodec;
26 import org.opendaylight.controller.sal.binding.dom.serializer.api.ChoiceCodec;
27 import org.opendaylight.controller.sal.binding.dom.serializer.api.CodecRegistry;
28 import org.opendaylight.controller.sal.binding.dom.serializer.api.DataContainerCodec;
29 import org.opendaylight.controller.sal.binding.dom.serializer.api.DomCodec;
30 import org.opendaylight.controller.sal.binding.dom.serializer.api.IdentifierCodec;
31 import org.opendaylight.controller.sal.binding.dom.serializer.api.IdentitityCodec;
32 import org.opendaylight.controller.sal.binding.dom.serializer.api.InstanceIdentifierCodec;
33 import org.opendaylight.controller.sal.binding.dom.serializer.api.ValueWithQName;
34 import org.opendaylight.controller.sal.binding.impl.util.ClassLoaderUtils;
35 import org.opendaylight.controller.sal.core.api.model.SchemaServiceListener;
36 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
37 import org.opendaylight.yangtools.binding.generator.util.Types;
38 import org.opendaylight.yangtools.concepts.Delegator;
39 import org.opendaylight.yangtools.concepts.Identifiable;
40 import org.opendaylight.yangtools.yang.binding.Augmentable;
41 import org.opendaylight.yangtools.yang.binding.Augmentation;
42 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
43 import org.opendaylight.yangtools.yang.binding.BindingCodec;
44 import org.opendaylight.yangtools.yang.binding.DataContainer;
45 import org.opendaylight.yangtools.yang.binding.DataObject;
46 import org.opendaylight.yangtools.yang.binding.Identifier;
47 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
50 import org.opendaylight.yangtools.yang.data.api.Node;
51 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
52 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
53 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
55 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
56 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
57 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
62 import org.opendaylight.yangtools.yang.model.api.UsesNode;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 import static com.google.common.base.Preconditions.*;
67 import static org.opendaylight.controller.sal.binding.dom.serializer.impl.IntermediateMapping.*;
69 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
70 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
71 import org.opendaylight.yangtools.sal.binding.model.api.Type;
72 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
73 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
74 import org.opendaylight.yangtools.yang.model.api.Module;
75 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
77 import com.google.common.collect.FluentIterable;
78 import com.google.common.util.concurrent.CycleDetectingLockFactory.WithExplicitOrdering;
80 public class LazyGeneratedCodecRegistry implements //
82 SchemaServiceListener, //
85 private final static Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
86 private final static LateMixinCodec NOT_READY_CODEC = new LateMixinCodec();
88 private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
89 private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
91 private TransformerGenerator generator;
93 // Concrete class to codecs
94 private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = new WeakHashMap<>();
95 private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = new WeakHashMap<>();
96 private static final Map<Class<?>, ChoiceCodecImpl<?>> choiceCodecs = new WeakHashMap<>();
97 private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = new WeakHashMap<>();
98 private static final Map<Class<?>, AugmentableCompositeCodec> augmentableCodecs = new WeakHashMap<>();
99 private static final Map<Class<?>, AugmentationCodec<?>> augmentationCodecs = new WeakHashMap<>();
100 private static final Map<Class<?>, QName> identityQNames = new WeakHashMap<>();
101 private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
102 /** Binding type to encountered classes mapping **/
103 @SuppressWarnings("rawtypes")
104 private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
106 @SuppressWarnings("rawtypes")
107 private static final ConcurrentMap<Type, ChoiceCaseCodecImpl> typeToCaseCodecs = new ConcurrentHashMap<>();
109 private CaseClassMapFacade classToCaseRawCodec = new CaseClassMapFacade();
111 private static final Map<SchemaPath, GeneratedTypeBuilder> pathToType = new ConcurrentHashMap<>();
112 private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
113 private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
115 private SchemaContext currentSchema;
117 public TransformerGenerator getGenerator() {
121 public void setGenerator(TransformerGenerator generator) {
122 this.generator = generator;
126 public InstanceIdentifierCodec getInstanceIdentifierCodec() {
127 return instanceIdentifierCodec;
131 public <T extends Augmentation<?>> AugmentationCodec<T> getCodecForAugmentation(Class<T> object) {
132 AugmentationCodec<T> codec = null;
133 @SuppressWarnings("rawtypes")
134 AugmentationCodec potentialCodec = augmentationCodecs.get(object);
135 if (potentialCodec != null) {
136 codec = potentialCodec;
139 Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
140 .augmentationTransformerFor(object);
141 BindingCodec<Map<QName, Object>, Object> rawCodec = augmentRawCodec.newInstance();
142 codec = new AugmentationCodecWrapper<T>(rawCodec);
143 augmentationCodecs.put(augmentRawCodec, codec);
144 } catch (InstantiationException e) {
145 LOG.error("Can not instantiate raw augmentation codec {}", object.getSimpleName(), e);
146 } catch (IllegalAccessException e) {
147 LOG.debug("BUG: Constructor for {} is not accessible.", object.getSimpleName(), e);
149 Class<? extends Augmentable<?>> objectSupertype = getAugmentableArgumentFrom(object);
150 if (objectSupertype != null) {
151 getAugmentableCodec(objectSupertype).addAugmentationCodec(object, codec);
153 LOG.warn("Could not find augmentation target for augmentation {}", object);
159 public QName getQNameForAugmentation(Class<?> cls) {
160 checkArgument(Augmentation.class.isAssignableFrom(cls));
161 return getCodecForAugmentation((Class<? extends Augmentation>)cls).getAugmentationQName();
164 private static Class<? extends Augmentable<?>> getAugmentableArgumentFrom(
165 final Class<? extends Augmentation<?>> augmentation) {
167 Class<? extends Augmentable<?>> ret = ClassLoaderUtils.withClassLoader(augmentation.getClassLoader(),
168 new Callable<Class<? extends Augmentable<?>>>() {
170 @SuppressWarnings("unchecked")
171 public Class<? extends Augmentable<?>> call() throws Exception {
172 for (java.lang.reflect.Type supertype : augmentation.getGenericInterfaces()) {
173 if (supertype instanceof ParameterizedType
174 && Augmentation.class.equals(((ParameterizedType) supertype).getRawType())) {
175 ParameterizedType augmentationGeneric = (ParameterizedType) supertype;
176 return (Class<? extends Augmentable<?>>) augmentationGeneric
177 .getActualTypeArguments()[0];
184 } catch (Exception e) {
185 LOG.debug("Could not find augmentable for {} using {}", augmentation, augmentation.getClassLoader(), e);
191 public Class<?> getClassForPath(List<QName> names) {
192 DataSchemaNode node = getSchemaNode(names);
193 SchemaPath path = node.getPath();
194 Type type = pathToType.get(path);
196 type = new ReferencedTypeImpl(type.getPackageName(), type.getName());
198 type = pathToInstantiatedType.get(names);
200 @SuppressWarnings("rawtypes")
201 WeakReference<Class> weakRef = typeToClass.get(type);
202 if (weakRef == null) {
203 LOG.error("Could not find loaded class for path: {} and type: {}", path, type.getFullyQualifiedName());
205 return weakRef.get();
209 public void putPathToClass(List<QName> names, Class<?> cls) {
210 Type reference = Types.typeForClass(cls);
211 pathToInstantiatedType.put(names, reference);
212 bindingClassEncountered(cls);
216 public IdentifierCodec<?> getKeyCodecForPath(List<QName> names) {
217 @SuppressWarnings("unchecked")
218 Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
219 return getIdentifierCodecForIdentifiable(cls);
223 public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(Class<T> type) {
224 @SuppressWarnings("unchecked")
225 DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
229 Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
230 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
231 DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
232 containerCodecs.put(type, newWrapper);
236 @SuppressWarnings("rawtypes")
237 public void bindingClassEncountered(Class cls) {
239 ConcreteType typeRef = Types.typeForClass(cls);
240 if (typeToClass.containsKey(typeRef)) {
243 LOG.trace("Binding Class {} encountered.", cls);
244 WeakReference<Class> weakRef = new WeakReference<>(cls);
245 typeToClass.put(typeRef, weakRef);
246 if (Augmentation.class.isAssignableFrom(cls)) {
248 } else if (DataObject.class.isAssignableFrom(cls)) {
249 @SuppressWarnings({ "unchecked", "unused" })
250 Object cdc = getCodecForDataObject((Class<? extends DataObject>) cls);
255 public void onClassProcessed(Class<?> cls) {
256 ConcreteType typeRef = Types.typeForClass(cls);
257 if (typeToClass.containsKey(typeRef)) {
260 LOG.trace("Binding Class {} encountered.", cls);
261 WeakReference<Class> weakRef = new WeakReference<>((Class) cls);
262 typeToClass.put(typeRef, weakRef);
265 private DataSchemaNode getSchemaNode(List<QName> path) {
266 QName firstNode = path.get(0);
267 DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
268 firstNode.getRevision());
269 Iterator<QName> iterator = path.iterator();
270 while (iterator.hasNext()) {
271 QName arg = iterator.next();
272 DataSchemaNode currentNode = previous.getDataChildByName(arg);
273 if (currentNode == null && previous instanceof DataNodeContainer) {
274 currentNode = searchInChoices(previous, arg);
276 if (currentNode instanceof DataNodeContainer) {
277 previous = (DataNodeContainer) currentNode;
278 } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
279 checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
283 return (DataSchemaNode) previous;
286 private DataSchemaNode searchInChoices(DataNodeContainer node, QName arg) {
287 Set<DataSchemaNode> children = node.getChildNodes();
288 for (DataSchemaNode child : children) {
289 if (child instanceof ChoiceNode) {
290 ChoiceNode choiceNode = (ChoiceNode) child;
291 DataSchemaNode potential = searchInCases(choiceNode, arg);
292 if (potential != null) {
300 private DataSchemaNode searchInCases(ChoiceNode choiceNode, QName arg) {
301 Set<ChoiceCaseNode> cases = choiceNode.getCases();
302 for (ChoiceCaseNode caseNode : cases) {
303 DataSchemaNode node = caseNode.getDataChildByName(arg);
311 private <T> T newInstanceOf(Class<?> newType) {
313 @SuppressWarnings("unchecked")
314 T ret = (T) newType.newInstance();
316 } catch (InstantiationException e) {
317 throw new IllegalStateException(e);
318 } catch (IllegalAccessException e) {
319 throw new IllegalStateException(e);
324 public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(Class<T> type) {
325 IdentifierCodec<?> obj = identifierCodecs.get(type);
329 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
330 .keyTransformerForIdentifiable(type);
331 BindingCodec<Map<QName, Object>, Object> newInstance;
332 newInstance = newInstanceOf(newCodec);
333 IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
334 identifierCodecs.put(type, newWrapper);
339 public IdentitityCodec<?> getIdentityCodec() {
340 return identityRefCodec;
344 public <T extends BaseIdentity> IdentitityCodec<T> getCodecForIdentity(Class<T> codec) {
345 bindingClassEncountered(codec);
346 return identityRefCodec;
350 public void onCodecCreated(Class<?> cls) {
351 CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
352 CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
356 public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(Class<T> object) {
357 @SuppressWarnings("unchecked")
358 IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
362 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
363 .keyTransformerForIdentifier(object);
364 BindingCodec<Map<QName, Object>, Object> newInstance;
365 newInstance = newInstanceOf(newCodec);
366 IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
367 identifierCodecs.put(object, newWrapper);
371 @SuppressWarnings("rawtypes")
372 public ChoiceCaseCodecImpl getCaseCodecFor(Class caseClass) {
373 ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
374 if (potential != null) {
377 ConcreteType typeref = Types.typeForClass(caseClass);
378 ChoiceCaseCodecImpl caseCodec = typeToCaseCodecs.get(typeref);
380 checkState(caseCodec != null, "Case Codec was not created proactivelly for %s", caseClass.getName());
381 checkState(caseCodec.getSchema() != null, "Case schema is not available for %s", caseClass.getName());
382 @SuppressWarnings("unchecked")
383 Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseCodec.getSchema());
384 BindingCodec newInstance = newInstanceOf(newCodec);
385 caseCodec.setDelegate(newInstance);
386 caseCodecs.put(caseClass, caseCodec);
388 for (Entry<Class<?>, ChoiceCodecImpl<?>> choice : choiceCodecs.entrySet()) {
389 if (choice.getKey().isAssignableFrom(caseClass)) {
390 choice.getValue().cases.put(caseClass, caseCodec);
396 public void onModuleContextAdded(SchemaContext schemaContext, Module module, ModuleContext context) {
397 pathToType.putAll(context.getChildNodes());
398 qnamesToIdentityMap.putAll(context.getIdentities());
399 for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
401 new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
404 captureCases(context.getCases(), schemaContext);
407 private void captureCases(Map<SchemaPath, GeneratedTypeBuilder> cases, SchemaContext module) {
408 for (Entry<SchemaPath, GeneratedTypeBuilder> caseNode : cases.entrySet()) {
409 ReferencedTypeImpl typeref = new ReferencedTypeImpl(caseNode.getValue().getPackageName(), caseNode
410 .getValue().getName());
412 pathToType.put(caseNode.getKey(), caseNode.getValue());
414 ChoiceCaseNode node = (ChoiceCaseNode) SchemaContextUtil.findDataSchemaNode(module, caseNode.getKey());
417 LOG.error("YANGTools Bug: SchemaNode for {}, with path {} was not found in context.",
418 typeref.getFullyQualifiedName(), caseNode.getKey());
419 @SuppressWarnings("rawtypes")
420 ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl();
421 typeToCaseCodecs.putIfAbsent(typeref, value);
424 @SuppressWarnings("rawtypes")
425 ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl(node);
426 typeToCaseCodecs.putIfAbsent(typeref, value);
431 public void onGlobalContextUpdated(SchemaContext context) {
432 currentSchema = context;
435 @SuppressWarnings({ "unchecked", "rawtypes" })
437 public void onChoiceCodecCreated(Class<?> choiceClass,
438 Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, ChoiceNode schema) {
439 ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
440 checkState(oldCodec == null);
441 BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
442 ChoiceCodecImpl<?> newCodec = new ChoiceCodecImpl(delegate);
443 choiceCodecs.put(choiceClass, newCodec);
444 CodecMapping.setClassToCaseMap(choiceCodec, (Map<Class<?>, BindingCodec<?, ?>>) classToCaseRawCodec);
445 CodecMapping.setCompositeNodeToCaseMap(choiceCodec, newCodec.getCompositeToCase());
447 tryToCreateCasesCodecs(schema);
451 private void tryToCreateCasesCodecs(ChoiceNode schema) {
452 for (ChoiceCaseNode caseNode : schema.getCases()) {
453 SchemaPath path = caseNode.getPath();
454 GeneratedTypeBuilder type;
455 if (path != null && (type = pathToType.get(path)) != null) {
456 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
457 ChoiceCaseCodecImpl partialCodec = typeToCaseCodecs.get(typeref);
458 if (partialCodec.getSchema() == null) {
459 partialCodec.setSchema(caseNode);
462 Class<?> caseClass = ClassLoaderUtils.tryToLoadClassWithTCCL(type.getFullyQualifiedName());
463 if (caseClass != null) {
464 getCaseCodecFor(caseClass);
472 public void onValueCodecCreated(Class<?> valueClass, Class<?> valueCodec) {
476 public void onCaseCodecCreated(Class<?> choiceClass,
477 Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
481 public void onDataContainerCodecCreated(Class<?> dataClass, Class<? extends BindingCodec<?, ?>> dataCodec) {
482 if (Augmentable.class.isAssignableFrom(dataClass)) {
483 AugmentableCompositeCodec augmentableCodec = getAugmentableCodec(dataClass);
484 CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
489 public AugmentableCompositeCodec getAugmentableCodec(Class<?> dataClass) {
490 AugmentableCompositeCodec ret = augmentableCodecs.get(dataClass);
494 ret = new AugmentableCompositeCodec(dataClass);
495 augmentableCodecs.put(dataClass, ret);
499 private static abstract class IntermediateCodec<T> implements //
500 DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
502 private final BindingCodec<Map<QName, Object>, Object> delegate;
505 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
509 public IntermediateCodec(BindingCodec<Map<QName, Object>, Object> delegate) {
510 this.delegate = delegate;
514 public Node<?> serialize(ValueWithQName<T> input) {
515 Map<QName, Object> intermediateOutput = delegate.serialize(input);
516 return toNode(intermediateOutput);
520 private static class IdentifierCodecImpl<T extends Identifier<?>> //
521 extends IntermediateCodec<T> //
522 implements IdentifierCodec<T> {
524 public IdentifierCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
529 public ValueWithQName<T> deserialize(Node<?> input) {
530 QName qname = input.getNodeType();
531 @SuppressWarnings("unchecked")
532 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
533 return new ValueWithQName<T>(qname, value);
537 public CompositeNode serialize(ValueWithQName<T> input) {
538 return (CompositeNode) super.serialize(input);
542 private static class DataContainerCodecImpl<T extends DataContainer> //
543 extends IntermediateCodec<T> //
544 implements DataContainerCodec<T> {
546 public DataContainerCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
551 public ValueWithQName<T> deserialize(Node<?> input) {
555 QName qname = input.getNodeType();
556 @SuppressWarnings("unchecked")
557 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
558 return new ValueWithQName<T>(qname, value);
562 public CompositeNode serialize(ValueWithQName<T> input) {
563 return (CompositeNode) super.serialize(input);
567 @SuppressWarnings("rawtypes")
568 private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
569 Delegator<BindingCodec> {
570 private boolean augmenting;
571 private BindingCodec delegate;
573 private Set<String> validNames;
574 private Set<QName> validQNames;
575 private ChoiceCaseNode schema;
577 public void setSchema(ChoiceCaseNode caseNode) {
578 this.schema = schema;
579 this.schema = caseNode;
580 validNames = new HashSet<>();
581 validQNames = new HashSet<>();
582 for (DataSchemaNode node : caseNode.getChildNodes()) {
583 QName qname = node.getQName();
584 validQNames.add(qname);
585 validNames.add(qname.getLocalName());
587 augmenting = caseNode.isAugmenting();
590 public ChoiceCaseCodecImpl() {
591 this.delegate = NOT_READY_CODEC;
594 public ChoiceCaseCodecImpl(ChoiceCaseNode caseNode) {
595 this.delegate = NOT_READY_CODEC;
600 public ValueWithQName<T> deserialize(Node<?> input) {
601 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
605 public CompositeNode serialize(ValueWithQName<T> input) {
606 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
609 public BindingCodec getDelegate() {
613 public void setDelegate(BindingCodec delegate) {
614 this.delegate = delegate;
617 public ChoiceCaseNode getSchema() {
622 public boolean isAcceptable(Node<?> input) {
623 if (input instanceof CompositeNode) {
625 return checkAugmenting((CompositeNode) input);
627 return checkLocal((CompositeNode) input);
633 private boolean checkLocal(CompositeNode input) {
634 QName parent = input.getNodeType();
635 for (Node<?> childNode : input.getChildren()) {
636 QName child = childNode.getNodeType();
637 if (!Objects.equals(parent.getNamespace(), child.getNamespace())
638 || !Objects.equals(parent.getRevision(), child.getRevision())) {
641 if (validNames.contains(child.getLocalName())) {
648 private boolean checkAugmenting(CompositeNode input) {
649 for (Node<?> child : input.getChildren()) {
650 if (validQNames.contains(child.getNodeType())) {
658 private static class ChoiceCodecImpl<T> implements ChoiceCodec<T> {
660 private final BindingCodec<Map<QName, Object>, Object> delegate;
662 @SuppressWarnings("rawtypes")
663 private final Map<Class, ChoiceCaseCodecImpl<?>> cases = new WeakHashMap<>();
665 private final CaseCompositeNodeMapFacade CompositeToCase;
667 public ChoiceCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
668 this.delegate = delegate;
669 this.CompositeToCase = new CaseCompositeNodeMapFacade(cases);
673 public ValueWithQName<T> deserialize(Node<?> input) {
674 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
678 public Node<?> serialize(ValueWithQName<T> input) {
679 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
682 public CaseCompositeNodeMapFacade getCompositeToCase() {
683 return CompositeToCase;
686 public Map<Class, ChoiceCaseCodecImpl<?>> getCases() {
690 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
696 @SuppressWarnings("rawtypes")
697 private class CaseClassMapFacade extends MapFacadeBase {
700 public Set<java.util.Map.Entry<Class, BindingCodec<Object, Object>>> entrySet() {
701 return Collections.emptySet();
705 public BindingCodec get(Object key) {
706 if (key instanceof Class) {
707 Class cls = (Class) key;
708 // bindingClassEncountered(cls);
709 ChoiceCaseCodecImpl caseCodec = getCaseCodecFor(cls);
710 return caseCodec.getDelegate();
716 @SuppressWarnings("rawtypes")
717 private static class CaseCompositeNodeMapFacade extends MapFacadeBase<CompositeNode> {
719 final Map<Class, ChoiceCaseCodecImpl<?>> choiceCases;
721 public CaseCompositeNodeMapFacade(Map<Class, ChoiceCaseCodecImpl<?>> choiceCases) {
722 this.choiceCases = choiceCases;
726 public BindingCodec get(Object key) {
727 if (!(key instanceof CompositeNode)) {
730 for (java.util.Map.Entry<Class, ChoiceCaseCodecImpl<?>> entry : choiceCases.entrySet()) {
731 ChoiceCaseCodecImpl<?> codec = entry.getValue();
732 if (codec.isAcceptable((CompositeNode) key)) {
733 return codec.getDelegate();
742 * This map is used as only facade for {@link BindingCodec} in different
743 * classloaders to retrieve codec dynamicly based on provided key.
748 @SuppressWarnings("rawtypes")
749 private static abstract class MapFacadeBase<T> implements Map<T, BindingCodec<?, ?>> {
752 public boolean containsKey(Object key) {
753 return get(key) != null;
757 public void clear() {
758 throw notModifiable();
762 public boolean equals(Object obj) {
763 return super.equals(obj);
767 public BindingCodec remove(Object key) {
777 public Collection<BindingCodec<?, ?>> values() {
778 return Collections.emptySet();
781 private UnsupportedOperationException notModifiable() {
782 return new UnsupportedOperationException("Not externally modifiable.");
786 public BindingCodec<Map<QName, Object>, Object> put(T key, BindingCodec<?, ?> value) {
787 throw notModifiable();
791 public void putAll(Map<? extends T, ? extends BindingCodec<?, ?>> m) {
792 throw notModifiable();
796 public int hashCode() {
797 return super.hashCode();
801 public boolean isEmpty() {
806 public Set<T> keySet() {
807 return Collections.emptySet();
811 public Set<java.util.Map.Entry<T, BindingCodec<?, ?>>> entrySet() {
812 return Collections.emptySet();
816 public boolean containsValue(Object value) {
821 @SuppressWarnings({ "rawtypes", "unchecked" })
822 private class AugmentableCompositeCodec implements BindingCodec {
824 private final Class augmentableType;
826 Map<Class, AugmentationCodec<?>> localAugmentationCodecs = new WeakHashMap<>();
828 public AugmentableCompositeCodec(Class type) {
829 checkArgument(Augmentable.class.isAssignableFrom(type));
830 augmentableType = type;
834 public Object serialize(Object input) {
835 if (input instanceof Augmentable<?>) {
837 Map<Class, Augmentation> augmentations = getAugmentations(input);
838 return serializeImpl(augmentations);
843 private Map<Class, Augmentation> getAugmentations(Object input) {
844 Field augmentationField;
846 augmentationField = input.getClass().getDeclaredField("augmentation");
847 augmentationField.setAccessible(true);
848 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
850 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
851 LOG.debug("Could not read augmentations for {}", input, e);
853 return Collections.emptyMap();
856 private List serializeImpl(Map<Class, Augmentation> input) {
857 List ret = new ArrayList<>();
858 for (Entry<Class, Augmentation> entry : input.entrySet()) {
859 AugmentationCodec codec = getCodecForAugmentation(entry.getKey());
860 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
861 ret.addAll(node.getChildren());
866 public synchronized <T extends Augmentation<?>> void addAugmentationCodec(Class<T> augmentationClass,
867 AugmentationCodec<T> value) {
868 localAugmentationCodecs.put(augmentationClass, value);
872 public Map<Class, Augmentation> deserialize(Object input) {
873 Map<Class, Augmentation> ret = new HashMap<>();
874 if (input instanceof CompositeNode) {
875 List<Entry<Class, AugmentationCodec<?>>> codecs = new ArrayList<>(localAugmentationCodecs.entrySet());
876 for (Entry<Class, AugmentationCodec<?>> codec : codecs) {
877 ValueWithQName<?> value = codec.getValue().deserialize((CompositeNode) input);
878 if (value != null && value.getValue() != null) {
879 ret.put(codec.getKey(), (Augmentation) value.getValue());
886 public Class getAugmentableType() {
887 return augmentableType;
891 @SuppressWarnings({ "rawtypes", "unchecked" })
892 private static class LateMixinCodec implements BindingCodec, Delegator<BindingCodec> {
894 private BindingCodec delegate;
897 public BindingCodec getDelegate() {
898 if (delegate == null) {
899 throw new IllegalStateException("Codec not initialized yet.");
905 public Object deserialize(Object input) {
906 return getDelegate().deserialize(input);
910 public Object serialize(Object input) {
911 return getDelegate().serialize(input);
915 private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
916 Delegator<BindingCodec> {
918 private BindingCodec delegate;
919 private QName augmentationQName;
921 public AugmentationCodecWrapper(BindingCodec<Map<QName, Object>, Object> rawCodec) {
922 this.delegate = rawCodec;
923 this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
927 public BindingCodec getDelegate() {
932 public CompositeNode serialize(ValueWithQName<T> input) {
933 @SuppressWarnings("unchecked")
934 List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
935 List<Node<?>> serialized = new ArrayList<>(rawValues.size());
936 for (Map<QName, Object> val : rawValues) {
937 serialized.add(toNode(val));
939 return new CompositeNodeTOImpl(input.getQname(), null, serialized);
943 @SuppressWarnings("unchecked")
944 public ValueWithQName<T> deserialize(Node<?> input) {
945 Object rawCodecValue = getDelegate().deserialize((Map<QName, Object>) input);
946 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
950 public QName getAugmentationQName() {
951 return augmentationQName;
955 private class IdentityCompositeCodec implements IdentitityCodec {
958 public Object deserialize(Object input) {
959 checkArgument(input instanceof QName);
960 return deserialize((QName) input);
964 public Class<?> deserialize(QName input) {
965 Type type = qnamesToIdentityMap.get(input);
969 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
970 WeakReference<Class> softref = typeToClass.get(typeref);
971 if (softref == null) {
974 return softref.get();
978 public QName serialize(Class input) {
979 checkArgument(BaseIdentity.class.isAssignableFrom(input));
980 bindingClassEncountered(input);
981 QName qname = identityQNames.get(input);
985 ConcreteType typeref = Types.typeForClass(input);
986 qname = typeToQname.get(typeref);
988 identityQNames.put(input, qname);
994 public Object serialize(Object input) {
995 checkArgument(input instanceof Class);
996 return serialize((Class) input);
1000 public boolean isCodecAvailable(Class<? extends DataContainer> cls) {
1001 if (containerCodecs.containsKey(cls)) {
1004 if (identifierCodecs.containsKey(cls)) {
1007 if (choiceCodecs.containsKey(cls)) {
1010 if (caseCodecs.containsKey(cls)) {
1013 if (augmentableCodecs.containsKey(cls)) {
1016 if (augmentationCodecs.containsKey(cls)) {