Fixed bug in Data store where multiple readers could overwrite
[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 (false == (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 (false == Objects.equals(parent.getNamespace(), child.getNamespace())) {
496                     continue;
497                 }
498                 if (false == Objects.equals(parent.getRevision(), child.getRevision())) {
499                     continue;
500                 }
501                 if (validNames.contains(child.getLocalName())) {
502                     return true;
503                 }
504             }
505             return false;
506         }
507
508         private boolean checkAugmenting(CompositeNode input) {
509             for (Node<?> child : input.getChildren()) {
510                 if (validQNames.contains(child.getNodeType())) {
511                     return true;
512                 }
513             }
514             return false;
515         }
516     }
517
518     private static class ChoiceCodecImpl<T> implements ChoiceCodec<T> {
519
520         private final BindingCodec<Map<QName, Object>, Object> delegate;
521
522         @SuppressWarnings("rawtypes")
523         private final Map<Class, ChoiceCaseCodecImpl<?>> cases = new WeakHashMap<>();
524
525         private final CaseCompositeNodeMapFacade CompositeToCase;
526
527         public ChoiceCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
528             this.delegate = delegate;
529             this.CompositeToCase = new CaseCompositeNodeMapFacade(cases);
530         }
531
532         @Override
533         public ValueWithQName<T> deserialize(Node<?> input) {
534             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
535         }
536
537         @Override
538         public Node<?> serialize(ValueWithQName<T> input) {
539             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
540         }
541
542         public CaseCompositeNodeMapFacade getCompositeToCase() {
543             return CompositeToCase;
544         }
545
546         public Map<Class, ChoiceCaseCodecImpl<?>> getCases() {
547             return cases;
548         }
549
550         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
551             return delegate;
552         }
553
554     }
555
556     @SuppressWarnings("rawtypes")
557     private class CaseClassMapFacade extends MapFacadeBase {
558
559         @Override
560         public Set<java.util.Map.Entry<Class, BindingCodec<Object, Object>>> entrySet() {
561             return null;
562         }
563
564         @Override
565         public BindingCodec get(Object key) {
566             if (key instanceof Class) {
567                 Class cls = (Class) key;
568                 //bindingClassEncountered(cls);
569                 ChoiceCaseCodecImpl caseCodec = getCaseCodecFor(cls);
570                 return caseCodec.getDelegate();
571             }
572             return null;
573         }
574     }
575
576     @SuppressWarnings("rawtypes")
577     private static class CaseCompositeNodeMapFacade extends MapFacadeBase<CompositeNode> {
578
579         final Map<Class, ChoiceCaseCodecImpl<?>> choiceCases;
580
581         public CaseCompositeNodeMapFacade(Map<Class, ChoiceCaseCodecImpl<?>> choiceCases) {
582             this.choiceCases = choiceCases;
583         }
584
585         @Override
586         public BindingCodec get(Object key) {
587             if (false == (key instanceof CompositeNode)) {
588                 return null;
589             }
590             for (java.util.Map.Entry<Class, ChoiceCaseCodecImpl<?>> entry : choiceCases.entrySet()) {
591                 ChoiceCaseCodecImpl<?> codec = entry.getValue();
592                 if (codec.isAcceptable((CompositeNode) key)) {
593                     return codec.getDelegate();
594                 }
595             }
596             return null;
597         }
598         
599         
600     }
601
602     /**
603      * This map is used as only facade for {@link BindingCodec} in different
604      * classloaders to retrieve codec dynamicly based on provided key.
605      * 
606      * @param <T>
607      *            Key type
608      */
609     @SuppressWarnings("rawtypes")
610     private static abstract class MapFacadeBase<T> implements Map<T, BindingCodec<?, ?>> {
611
612         @Override
613         public boolean containsKey(Object key) {
614             return get(key) != null;
615         }
616
617         @Override
618         public void clear() {
619             throw notModifiable();
620         }
621
622         @Override
623         public boolean equals(Object obj) {
624             return super.equals(obj);
625         }
626
627         @Override
628         public BindingCodec remove(Object key) {
629             return null;
630         }
631
632         @Override
633         public int size() {
634             return 0;
635         }
636
637         @Override
638         public Collection<BindingCodec<?, ?>> values() {
639             return null;
640         }
641
642         private UnsupportedOperationException notModifiable() {
643             return new UnsupportedOperationException("Not externally modifiable.");
644         }
645
646         @Override
647         public BindingCodec<Map<QName, Object>, Object> put(T key, BindingCodec<?,?> value) {
648             throw notModifiable();
649         }
650
651         @Override
652         public void putAll(Map<? extends T, ? extends BindingCodec<?, ?>> m) {
653             throw notModifiable();
654         }
655
656         @Override
657         public int hashCode() {
658             return super.hashCode();
659         }
660
661         @Override
662         public boolean isEmpty() {
663             return false;
664         }
665
666         @Override
667         public Set<T> keySet() {
668             return null;
669         }
670
671         @Override
672         public Set<java.util.Map.Entry<T, BindingCodec<?, ?>>> entrySet() {
673             // TODO Auto-generated method stub
674             return null;
675         }
676
677         @Override
678         public boolean containsValue(Object value) {
679             return false;
680         }
681     }
682
683     @SuppressWarnings({ "rawtypes", "unchecked" })
684     private class AugmentableCompositeCodec implements BindingCodec {
685
686         private final Class augmentableType;
687
688         Map<Class, BindingCodec> rawAugmentationCodecs = new WeakHashMap<>();
689
690         public AugmentableCompositeCodec(Class type) {
691             checkArgument(Augmentable.class.isAssignableFrom(type));
692             augmentableType = type;
693         }
694
695         @Override
696         public Object serialize(Object input) {
697             if (input instanceof Augmentable<?>) {
698
699                 Map<Class, Augmentation> augmentations = getAugmentations(input);
700                 return serializeImpl(augmentations);
701             }
702             return null;
703         }
704
705         private Map<Class, Augmentation> getAugmentations(Object input) {
706             Field augmentationField;
707             try {
708                 augmentationField = input.getClass().getDeclaredField("augmentation");
709                 augmentationField.setAccessible(true);
710                 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
711                 return augMap;
712             } catch (NoSuchFieldException e) {
713
714             } catch (SecurityException e) {
715
716             } catch (IllegalArgumentException e) {
717
718             } catch (IllegalAccessException e) {
719
720             }
721             return Collections.emptyMap();
722         }
723
724         private List serializeImpl(Map<Class, Augmentation> input) {
725             List ret = new ArrayList<>();
726             for (Entry<Class, Augmentation> entry : input.entrySet()) {
727                 BindingCodec codec = getRawCodecForAugmentation(entry.getKey());
728                 List output = (List) codec.serialize(new ValueWithQName(null, entry.getValue()));
729                 ret.addAll(output);
730             }
731             return ret;
732         }
733
734         private BindingCodec getRawCodecForAugmentation(Class key) {
735             BindingCodec ret = rawAugmentationCodecs.get(key);
736             if (ret != null) {
737                 return ret;
738             }
739             try {
740                 Class<? extends BindingCodec> retClass = generator.augmentationTransformerFor(key);
741                 ret = retClass.newInstance();
742                 rawAugmentationCodecs.put(key, ret);
743                 return ret;
744             } catch (InstantiationException e) {
745
746             } catch (IllegalAccessException e) {
747
748             }
749             return null;
750         }
751
752         @Override
753         public Map<Class, Augmentation> deserialize(Object input) {
754             Map<Class, Augmentation> ret = new HashMap<>();
755             if (input instanceof CompositeNode) {
756                 for (Entry<Class, BindingCodec> codec : rawAugmentationCodecs.entrySet()) {
757                     Augmentation value = (Augmentation) codec.getValue().deserialize(input);
758                     if (value != null) {
759                         ret.put(codec.getKey(), value);
760                     }
761                 }
762             }
763             return ret;
764         }
765
766         public Map<Class, BindingCodec> getRawAugmentationCodecs() {
767             return rawAugmentationCodecs;
768         }
769
770         public void setRawAugmentationCodecs(Map<Class, BindingCodec> rawAugmentationCodecs) {
771             this.rawAugmentationCodecs = rawAugmentationCodecs;
772         }
773
774         public Class getAugmentableType() {
775             return augmentableType;
776         }
777     }
778
779     @SuppressWarnings({ "rawtypes", "unchecked" })
780     private static class LateMixinCodec implements BindingCodec, Delegator<BindingCodec> {
781
782         private BindingCodec delegate;
783
784         @Override
785         public BindingCodec getDelegate() {
786             if (delegate == null) {
787                 throw new IllegalStateException("Codec not initialized yet.");
788             }
789             return delegate;
790         }
791
792         @Override
793         public Object deserialize(Object input) {
794             return getDelegate().deserialize(input);
795         }
796
797         @Override
798         public Object serialize(Object input) {
799             return getDelegate().serialize(input);
800         }
801     }
802 }