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