Fixed major sonar warnings in Binding Aware Broker
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / dom / serializer / impl / LazyGeneratedCodecRegistry.java
1 package org.opendaylight.controller.sal.binding.dom.serializer.impl;
2
3 import java.lang.ref.WeakReference;
4 import java.lang.reflect.Field;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.Collections;
8 import java.util.HashMap;
9 import java.util.HashSet;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.Map.Entry;
14 import java.util.Objects;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.concurrent.ConcurrentMap;
17 import java.util.Set;
18 import java.util.WeakHashMap;
19
20 import org.opendaylight.controller.sal.binding.dom.serializer.api.AugmentationCodec;
21 import org.opendaylight.controller.sal.binding.dom.serializer.api.ChoiceCaseCodec;
22 import org.opendaylight.controller.sal.binding.dom.serializer.api.ChoiceCodec;
23 import org.opendaylight.controller.sal.binding.dom.serializer.api.CodecRegistry;
24 import org.opendaylight.controller.sal.binding.dom.serializer.api.DataContainerCodec;
25 import org.opendaylight.controller.sal.binding.dom.serializer.api.DomCodec;
26 import org.opendaylight.controller.sal.binding.dom.serializer.api.IdentifierCodec;
27 import org.opendaylight.controller.sal.binding.dom.serializer.api.InstanceIdentifierCodec;
28 import org.opendaylight.controller.sal.binding.dom.serializer.api.ValueWithQName;
29 import org.opendaylight.controller.sal.core.api.model.SchemaServiceListener;
30 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
31 import org.opendaylight.yangtools.binding.generator.util.Types;
32 import org.opendaylight.yangtools.concepts.Delegator;
33 import org.opendaylight.yangtools.concepts.Identifiable;
34 import org.opendaylight.yangtools.yang.binding.Augmentable;
35 import org.opendaylight.yangtools.yang.binding.Augmentation;
36 import org.opendaylight.yangtools.yang.binding.BindingCodec;
37 import org.opendaylight.yangtools.yang.binding.DataContainer;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.binding.Identifier;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
42 import org.opendaylight.yangtools.yang.data.api.Node;
43 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
45 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 import static com.google.common.base.Preconditions.*;
55 import static org.opendaylight.controller.sal.binding.dom.serializer.impl.IntermediateMapping.*;
56
57 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
58 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
59 import org.opendaylight.yangtools.sal.binding.model.api.Type;
60 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
61 import org.opendaylight.yangtools.yang.model.api.Module;
62 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
63
64 public class LazyGeneratedCodecRegistry implements //
65         CodecRegistry, //
66         SchemaServiceListener, //
67         GeneratorListener {
68
69     private final static Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
70     private final static LateMixinCodec NOT_READY_CODEC = new LateMixinCodec();
71
72     private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
73
74     private TransformerGenerator generator;
75
76     // Concrete class to codecs
77     private Map<Class<?>, DataContainerCodec<?>> containerCodecs = new WeakHashMap<>();
78     private Map<Class<?>, IdentifierCodec<?>> identifierCodecs = new WeakHashMap<>();
79     private Map<Class<?>, ChoiceCodecImpl<?>> choiceCodecs = new WeakHashMap<>();
80     private Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = new WeakHashMap<>();
81     private Map<Class<?>, AugmentableCompositeCodec> augmentableCodecs = new WeakHashMap<>();
82
83     /** Binding type to encountered classes mapping **/
84     @SuppressWarnings("rawtypes")
85     Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
86
87     @SuppressWarnings("rawtypes")
88     private ConcurrentMap<Type, ChoiceCaseCodecImpl> typeToCaseNodes = new ConcurrentHashMap<>();
89
90     private CaseClassMapFacade classToCaseRawCodec = new CaseClassMapFacade();
91
92     Map<SchemaPath, GeneratedTypeBuilder> pathToType = new ConcurrentHashMap<>();
93
94     private SchemaContext currentSchema;
95
96     public TransformerGenerator getGenerator() {
97         return generator;
98     }
99
100     public void setGenerator(TransformerGenerator generator) {
101         this.generator = generator;
102     }
103
104     @Override
105     public InstanceIdentifierCodec getInstanceIdentifierCodec() {
106         return instanceIdentifierCodec;
107     }
108
109     @Override
110     public <T extends Augmentation<?>> AugmentationCodec<T> getCodecForAugmentation(Class<T> object) {
111         // TODO Auto-generated method stub
112         return null;
113     }
114
115     @Override
116     public Class<?> getClassForPath(List<QName> names) {
117         DataSchemaNode node = getSchemaNode(names);
118         SchemaPath path = node.getPath();
119         GeneratedTypeBuilder type = pathToType.get(path);
120         ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
121         @SuppressWarnings("rawtypes")
122         WeakReference<Class> weakRef = typeToClass.get(typeref);
123         if(weakRef == null) {
124             LOG.error("Could not find loaded class for path: {} and type: {}",path,typeref.getFullyQualifiedName());
125         }
126         return weakRef.get();
127     }
128
129     @Override
130     public IdentifierCodec<?> getKeyCodecForPath(List<QName> names) {
131         @SuppressWarnings("unchecked")
132         Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
133         return getIdentifierCodecForIdentifiable(cls);
134     }
135
136     @Override
137     public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(Class<T> type) {
138         @SuppressWarnings("unchecked")
139         DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
140         if (ret != null) {
141             return ret;
142         }
143         Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
144         BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
145         DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
146         containerCodecs.put(type, newWrapper);
147         return newWrapper;
148     }
149
150     @Override
151     @SuppressWarnings("rawtypes")
152     public void bindingClassEncountered(Class cls) {
153         
154         ConcreteType typeRef = Types.typeForClass(cls);
155         if(typeToClass.containsKey(typeRef)) {
156             return;
157         }
158         LOG.info("Binding Class {} encountered.",cls);
159         WeakReference<Class> weakRef = new WeakReference<>(cls);
160         typeToClass.put(typeRef, weakRef);
161         if(DataObject.class.isAssignableFrom(cls)) {
162             @SuppressWarnings({"unchecked","unused"})
163             Object cdc = getCodecForDataObject((Class<? extends DataObject>) cls);
164         }
165     }
166     
167     @Override
168     public void onClassProcessed(Class<?> cls) {
169         ConcreteType typeRef = Types.typeForClass(cls);
170         if(typeToClass.containsKey(typeRef)) {
171             return;
172         }
173         LOG.info("Binding Class {} encountered.",cls);
174         WeakReference<Class> weakRef = new WeakReference<>((Class) cls);
175         typeToClass.put(typeRef, weakRef);
176     }
177
178     private DataSchemaNode getSchemaNode(List<QName> path) {
179         QName firstNode = path.get(0);
180         DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
181                 firstNode.getRevision());
182         Iterator<QName> iterator = path.iterator();
183         while (iterator.hasNext()) {
184             QName arg = iterator.next();
185             DataSchemaNode currentNode = previous.getDataChildByName(arg);
186             if (currentNode == null && previous instanceof DataNodeContainer) {
187                 currentNode = searchInChoices(previous, arg);
188             }
189             if (currentNode instanceof DataNodeContainer) {
190                 previous = (DataNodeContainer) currentNode;
191             } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
192                 checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
193                 return currentNode;
194             }
195         }
196         return (DataSchemaNode) previous;
197     }
198
199     private DataSchemaNode searchInChoices(DataNodeContainer node, QName arg) {
200         Set<DataSchemaNode> children = node.getChildNodes();
201         for (DataSchemaNode child : children) {
202             if (child instanceof ChoiceNode) {
203                 ChoiceNode choiceNode = (ChoiceNode) child;
204                 DataSchemaNode potential = searchInCases(choiceNode, arg);
205                 if (potential != null) {
206                     return potential;
207                 }
208             }
209         }
210         return null;
211     }
212
213     private DataSchemaNode searchInCases(ChoiceNode choiceNode, QName arg) {
214         Set<ChoiceCaseNode> cases = choiceNode.getCases();
215         for (ChoiceCaseNode caseNode : cases) {
216             DataSchemaNode node = caseNode.getDataChildByName(arg);
217             if (node != null) {
218                 return node;
219             }
220         }
221         return null;
222     }
223
224     private <T> T newInstanceOf(Class<?> newType) {
225         try {
226             @SuppressWarnings("unchecked")
227             T ret = (T) newType.newInstance();
228             return ret;
229         } catch (InstantiationException e) {
230             throw new IllegalStateException(e);
231         } catch (IllegalAccessException e) {
232             throw new IllegalStateException(e);
233         }
234     }
235
236     @Override
237     public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(Class<T> type) {
238         IdentifierCodec<?> obj = identifierCodecs.get(type);
239         if (obj != null) {
240             return obj;
241         }
242         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
243                 .keyTransformerForIdentifiable(type);
244         BindingCodec<Map<QName, Object>, Object> newInstance;
245         newInstance = newInstanceOf(newCodec);
246         IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
247         identifierCodecs.put(type, newWrapper);
248         return newWrapper;
249     }
250
251     @Override
252     public void onCodecCreated(Class<?> cls) {
253         CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
254     }
255
256     @Override
257     public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(Class<T> object) {
258         @SuppressWarnings("unchecked")
259         IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
260         if (obj != null) {
261             return obj;
262         }
263         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
264                 .keyTransformerForIdentifier(object);
265         BindingCodec<Map<QName, Object>, Object> newInstance;
266         newInstance = newInstanceOf(newCodec);
267         IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
268         identifierCodecs.put(object, newWrapper);
269         return newWrapper;
270     }
271
272     @SuppressWarnings("rawtypes")
273     public ChoiceCaseCodecImpl getCaseCodecFor(Class caseClass) {
274         ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
275         if (potential != null) {
276             return potential;
277         }
278         ConcreteType typeref = Types.typeForClass(caseClass);
279         ChoiceCaseCodecImpl caseCodec = typeToCaseNodes.get(typeref);
280
281         @SuppressWarnings("unchecked")
282         Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseCodec.schema);
283         BindingCodec newInstance = newInstanceOf(newCodec);
284         caseCodec.setDelegate(newInstance);
285         caseCodecs.put(caseClass, caseCodec);
286
287         for (Entry<Class<?>, ChoiceCodecImpl<?>> choice : choiceCodecs.entrySet()) {
288             if (choice.getKey().isAssignableFrom(caseClass)) {
289                 choice.getValue().cases.put(caseClass, caseCodec);
290             }
291         }
292         return caseCodec;
293     }
294
295     public void onModuleContextAdded(SchemaContext schemaContext, Module module, ModuleContext context) {
296         pathToType.putAll(context.getChildNodes());
297
298         captureCases(context.getCases(), schemaContext);
299     }
300
301     private void captureCases(Map<SchemaPath, GeneratedTypeBuilder> cases, SchemaContext module) {
302         for (Entry<SchemaPath, GeneratedTypeBuilder> caseNode : cases.entrySet()) {
303             ReferencedTypeImpl typeref = new ReferencedTypeImpl(caseNode.getValue().getPackageName(), caseNode
304                     .getValue().getName());
305             ChoiceCaseNode node = (ChoiceCaseNode) SchemaContextUtil.findDataSchemaNode(module, caseNode.getKey());
306             if (node == null) {
307                 LOG.error("YANGTools Bug: SchemaNode for {}, with path {} was not found in context.",
308                         typeref.getFullyQualifiedName(), caseNode.getKey());
309                 continue;
310             }
311
312             @SuppressWarnings("rawtypes")
313             ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl(node);
314             typeToCaseNodes.putIfAbsent(typeref, value);
315         }
316     }
317
318     @Override
319     public void onGlobalContextUpdated(SchemaContext context) {
320         currentSchema = context;
321     }
322
323     @SuppressWarnings({ "unchecked", "rawtypes" })
324     @Override
325     public void onChoiceCodecCreated(Class<?> choiceClass,
326             Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
327         ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
328         checkState(oldCodec == null);
329         BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
330         ChoiceCodecImpl<?> newCodec = new ChoiceCodecImpl(delegate);
331         choiceCodecs.put(choiceClass, newCodec);
332         CodecMapping.setClassToCaseMap(choiceCodec, (Map<Class<?>, BindingCodec<?, ?>>) classToCaseRawCodec);
333         CodecMapping.setCompositeNodeToCaseMap(choiceCodec, newCodec.getCompositeToCase());
334
335     }
336
337     @Override
338     public void onValueCodecCreated(Class<?> valueClass, Class<?> valueCodec) {
339     }
340
341     @Override
342     public void onCaseCodecCreated(Class<?> choiceClass,
343             Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
344     }
345
346     @Override
347     public void onDataContainerCodecCreated(Class<?> dataClass,
348             Class<? extends BindingCodec<Map<QName, Object>, Object>> dataCodec) {
349         if (Augmentable.class.isAssignableFrom(dataClass)) {
350             AugmentableCompositeCodec augmentableCodec = getAugmentableCodec(dataClass);
351             CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
352         }
353
354     }
355
356     private AugmentableCompositeCodec getAugmentableCodec(Class<?> dataClass) {
357         AugmentableCompositeCodec ret = augmentableCodecs.get(dataClass);
358         if (ret != null) {
359             return ret;
360         }
361         ret = new AugmentableCompositeCodec(dataClass);
362         augmentableCodecs.put(dataClass, ret);
363         return ret;
364     }
365
366     private static abstract class IntermediateCodec<T> implements //
367             DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
368
369         private final BindingCodec<Map<QName, Object>, Object> delegate;
370
371         @Override
372         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
373             return delegate;
374         }
375
376         public IntermediateCodec(BindingCodec<Map<QName, Object>, Object> delegate) {
377             this.delegate = delegate;
378         }
379
380         @Override
381         public Node<?> serialize(ValueWithQName<T> input) {
382             Map<QName, Object> intermediateOutput = delegate.serialize(input);
383             return toNode(intermediateOutput);
384         }
385     }
386
387     private static class IdentifierCodecImpl<T extends Identifier<?>> //
388             extends IntermediateCodec<T> //
389             implements IdentifierCodec<T> {
390
391         public IdentifierCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
392             super(delegate);
393         }
394
395         @Override
396         public ValueWithQName<T> deserialize(Node<?> input) {
397             QName qname = input.getNodeType();
398             @SuppressWarnings("unchecked")
399             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
400             return new ValueWithQName<T>(qname, value);
401         }
402
403         @Override
404         public CompositeNode serialize(ValueWithQName<T> input) {
405             return (CompositeNode) super.serialize(input);
406         }
407     }
408
409     private static class DataContainerCodecImpl<T extends DataContainer> //
410             extends IntermediateCodec<T> //
411             implements DataContainerCodec<T> {
412
413         public DataContainerCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
414             super(delegate);
415         }
416
417         @Override
418         public ValueWithQName<T> deserialize(Node<?> input) {
419             if (input == null) {
420                 return null;
421             }
422             QName qname = input.getNodeType();
423             @SuppressWarnings("unchecked")
424             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
425             return new ValueWithQName<T>(qname, value);
426         }
427
428         @Override
429         public CompositeNode serialize(ValueWithQName<T> input) {
430             return (CompositeNode) super.serialize(input);
431         }
432     }
433
434     @SuppressWarnings("rawtypes")
435     private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
436             Delegator<BindingCodec> {
437         private final boolean augmenting;
438         private BindingCodec delegate;
439
440         private final Set<String> validNames;
441         private final Set<QName> validQNames;
442         private ChoiceCaseNode schema;
443
444         public ChoiceCaseCodecImpl(ChoiceCaseNode caseNode) {
445             this.delegate = NOT_READY_CODEC;
446             this.schema = caseNode;
447             validNames = new HashSet<>();
448             validQNames = new HashSet<>();
449             for (DataSchemaNode node : caseNode.getChildNodes()) {
450                 QName qname = node.getQName();
451                 validQNames.add(qname);
452                 validNames.add(qname.getLocalName());
453             }
454             augmenting = caseNode.isAugmenting();
455         }
456
457         @Override
458         public ValueWithQName<T> deserialize(Node<?> input) {
459             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
460         }
461
462         @Override
463         public CompositeNode serialize(ValueWithQName<T> input) {
464             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
465         }
466
467         public BindingCodec getDelegate() {
468             return delegate;
469         }
470
471         public void setDelegate(BindingCodec delegate) {
472             this.delegate = delegate;
473         }
474
475         public ChoiceCaseNode getSchema() {
476             return schema;
477         }
478
479         @Override
480         public boolean isAcceptable(Node<?> input) {
481             if (!(input instanceof CompositeNode)) {
482                 if (augmenting) {
483                     return checkAugmenting((CompositeNode) input);
484                 } else {
485                     return checkLocal((CompositeNode) input);
486                 }
487             }
488             return false;
489         }
490
491         private boolean checkLocal(CompositeNode input) {
492             QName parent = input.getNodeType();
493             for (Node<?> childNode : input.getChildren()) {
494                 QName child = childNode.getNodeType();
495                 if (!Objects.equals(parent.getNamespace(), child.getNamespace()) || Objects.equals(parent.getRevision(), child.getRevision())) {
496                     continue;
497                 }
498                 if (validNames.contains(child.getLocalName())) {
499                     return true;
500                 }
501             }
502             return false;
503         }
504
505         private boolean checkAugmenting(CompositeNode input) {
506             for (Node<?> child : input.getChildren()) {
507                 if (validQNames.contains(child.getNodeType())) {
508                     return true;
509                 }
510             }
511             return false;
512         }
513     }
514
515     private static class ChoiceCodecImpl<T> implements ChoiceCodec<T> {
516
517         private final BindingCodec<Map<QName, Object>, Object> delegate;
518
519         @SuppressWarnings("rawtypes")
520         private final Map<Class, ChoiceCaseCodecImpl<?>> cases = new WeakHashMap<>();
521
522         private final CaseCompositeNodeMapFacade CompositeToCase;
523
524         public ChoiceCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
525             this.delegate = delegate;
526             this.CompositeToCase = new CaseCompositeNodeMapFacade(cases);
527         }
528
529         @Override
530         public ValueWithQName<T> deserialize(Node<?> input) {
531             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
532         }
533
534         @Override
535         public Node<?> serialize(ValueWithQName<T> input) {
536             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
537         }
538
539         public CaseCompositeNodeMapFacade getCompositeToCase() {
540             return CompositeToCase;
541         }
542
543         public Map<Class, ChoiceCaseCodecImpl<?>> getCases() {
544             return cases;
545         }
546
547         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
548             return delegate;
549         }
550
551     }
552
553     @SuppressWarnings("rawtypes")
554     private class CaseClassMapFacade extends MapFacadeBase {
555
556         @Override
557         public Set<java.util.Map.Entry<Class, BindingCodec<Object, Object>>> entrySet() {
558             return Collections.emptySet();
559         }
560
561         @Override
562         public BindingCodec get(Object key) {
563             if (key instanceof Class) {
564                 Class cls = (Class) key;
565                 //bindingClassEncountered(cls);
566                 ChoiceCaseCodecImpl caseCodec = getCaseCodecFor(cls);
567                 return caseCodec.getDelegate();
568             }
569             return null;
570         }
571     }
572
573     @SuppressWarnings("rawtypes")
574     private static class CaseCompositeNodeMapFacade extends MapFacadeBase<CompositeNode> {
575
576         final Map<Class, ChoiceCaseCodecImpl<?>> choiceCases;
577
578         public CaseCompositeNodeMapFacade(Map<Class, ChoiceCaseCodecImpl<?>> choiceCases) {
579             this.choiceCases = choiceCases;
580         }
581
582         @Override
583         public BindingCodec get(Object key) {
584             if (!(key instanceof CompositeNode)) {
585                 return null;
586             }
587             for (java.util.Map.Entry<Class, ChoiceCaseCodecImpl<?>> entry : choiceCases.entrySet()) {
588                 ChoiceCaseCodecImpl<?> codec = entry.getValue();
589                 if (codec.isAcceptable((CompositeNode) key)) {
590                     return codec.getDelegate();
591                 }
592             }
593             return null;
594         }
595         
596         
597     }
598
599     /**
600      * This map is used as only facade for {@link BindingCodec} in different
601      * classloaders to retrieve codec dynamicly based on provided key.
602      * 
603      * @param <T>
604      *            Key type
605      */
606     @SuppressWarnings("rawtypes")
607     private static abstract class MapFacadeBase<T> implements Map<T, BindingCodec<?, ?>> {
608
609         @Override
610         public boolean containsKey(Object key) {
611             return get(key) != null;
612         }
613
614         @Override
615         public void clear() {
616             throw notModifiable();
617         }
618
619         @Override
620         public boolean equals(Object obj) {
621             return super.equals(obj);
622         }
623
624         @Override
625         public BindingCodec remove(Object key) {
626             return null;
627         }
628
629         @Override
630         public int size() {
631             return 0;
632         }
633
634         @Override
635         public Collection<BindingCodec<?, ?>> values() {
636             return Collections.emptySet();
637         }
638
639         private UnsupportedOperationException notModifiable() {
640             return new UnsupportedOperationException("Not externally modifiable.");
641         }
642
643         @Override
644         public BindingCodec<Map<QName, Object>, Object> put(T key, BindingCodec<?,?> value) {
645             throw notModifiable();
646         }
647
648         @Override
649         public void putAll(Map<? extends T, ? extends BindingCodec<?, ?>> m) {
650             throw notModifiable();
651         }
652
653         @Override
654         public int hashCode() {
655             return super.hashCode();
656         }
657
658         @Override
659         public boolean isEmpty() {
660             return true;
661         }
662
663         @Override
664         public Set<T> keySet() {
665             return Collections.emptySet();
666         }
667
668         @Override
669         public Set<java.util.Map.Entry<T, BindingCodec<?, ?>>> entrySet() {
670             return Collections.emptySet();
671         }
672
673         @Override
674         public boolean containsValue(Object value) {
675             return false;
676         }
677     }
678
679     @SuppressWarnings({ "rawtypes", "unchecked" })
680     private class AugmentableCompositeCodec implements BindingCodec {
681
682         private final Class augmentableType;
683
684         Map<Class, BindingCodec> rawAugmentationCodecs = new WeakHashMap<>();
685
686         public AugmentableCompositeCodec(Class type) {
687             checkArgument(Augmentable.class.isAssignableFrom(type));
688             augmentableType = type;
689         }
690
691         @Override
692         public Object serialize(Object input) {
693             if (input instanceof Augmentable<?>) {
694
695                 Map<Class, Augmentation> augmentations = getAugmentations(input);
696                 return serializeImpl(augmentations);
697             }
698             return null;
699         }
700
701         private Map<Class, Augmentation> getAugmentations(Object input) {
702             Field augmentationField;
703             try {
704                 augmentationField = input.getClass().getDeclaredField("augmentation");
705                 augmentationField.setAccessible(true);
706                 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
707                 return augMap;
708             } catch (IllegalArgumentException | IllegalAccessException |NoSuchFieldException | SecurityException e) {
709                 LOG.debug("Could not read augmentations for {}",input,e);
710             } 
711             return Collections.emptyMap();
712         }
713
714         private List serializeImpl(Map<Class, Augmentation> input) {
715             List ret = new ArrayList<>();
716             for (Entry<Class, Augmentation> entry : input.entrySet()) {
717                 BindingCodec codec = getRawCodecForAugmentation(entry.getKey());
718                 List output = (List) codec.serialize(new ValueWithQName(null, entry.getValue()));
719                 ret.addAll(output);
720             }
721             return ret;
722         }
723
724         private BindingCodec getRawCodecForAugmentation(Class key) {
725             BindingCodec ret = rawAugmentationCodecs.get(key);
726             if (ret != null) {
727                 return ret;
728             }
729             try {
730                 Class<? extends BindingCodec> retClass = generator.augmentationTransformerFor(key);
731                 ret = retClass.newInstance();
732                 rawAugmentationCodecs.put(key, ret);
733                 return ret;
734             } catch (InstantiationException e) {
735                 LOG.error("Can not instantiate raw augmentation codec {}",key.getSimpleName(),e);
736             } catch (IllegalAccessException e) {
737                 LOG.debug("BUG: Constructor for {} is not accessible.",key.getSimpleName(),e);
738             }
739             return null;
740         }
741
742         @Override
743         public Map<Class, Augmentation> deserialize(Object input) {
744             Map<Class, Augmentation> ret = new HashMap<>();
745             if (input instanceof CompositeNode) {
746                 for (Entry<Class, BindingCodec> codec : rawAugmentationCodecs.entrySet()) {
747                     Augmentation value = (Augmentation) codec.getValue().deserialize(input);
748                     if (value != null) {
749                         ret.put(codec.getKey(), value);
750                     }
751                 }
752             }
753             return ret;
754         }
755
756         public Map<Class, BindingCodec> getRawAugmentationCodecs() {
757             return rawAugmentationCodecs;
758         }
759
760         public void setRawAugmentationCodecs(Map<Class, BindingCodec> rawAugmentationCodecs) {
761             this.rawAugmentationCodecs = rawAugmentationCodecs;
762         }
763
764         public Class getAugmentableType() {
765             return augmentableType;
766         }
767     }
768
769     @SuppressWarnings({ "rawtypes", "unchecked" })
770     private static class LateMixinCodec implements BindingCodec, Delegator<BindingCodec> {
771
772         private BindingCodec delegate;
773
774         @Override
775         public BindingCodec getDelegate() {
776             if (delegate == null) {
777                 throw new IllegalStateException("Codec not initialized yet.");
778             }
779             return delegate;
780         }
781
782         @Override
783         public Object deserialize(Object input) {
784             return getDelegate().deserialize(input);
785         }
786
787         @Override
788         public Object serialize(Object input) {
789             return getDelegate().serialize(input);
790         }
791     }
792 }