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