Merge "Move XmlDocumentUtils.writeValueByType()"
[yangtools.git] / code-generator / binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / binding / generator / impl / LazyGeneratedCodecRegistry.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.sal.binding.generator.impl;
9
10 import java.lang.ref.WeakReference;
11 import java.lang.reflect.Field;
12 import java.util.AbstractMap.SimpleEntry;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Set;
23 import java.util.WeakHashMap;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26
27 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
28 import org.opendaylight.yangtools.binding.generator.util.Types;
29 import org.opendaylight.yangtools.concepts.Delegator;
30 import org.opendaylight.yangtools.concepts.Identifiable;
31 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
32 import org.opendaylight.yangtools.sal.binding.generator.util.CodeGenerationException;
33 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
34 import org.opendaylight.yangtools.sal.binding.model.api.Type;
35 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
36 import org.opendaylight.yangtools.yang.binding.Augmentable;
37 import org.opendaylight.yangtools.yang.binding.Augmentation;
38 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
39 import org.opendaylight.yangtools.yang.binding.BindingCodec;
40 import org.opendaylight.yangtools.yang.binding.BindingMapping;
41 import org.opendaylight.yangtools.yang.binding.DataContainer;
42 import org.opendaylight.yangtools.yang.binding.DataObject;
43 import org.opendaylight.yangtools.yang.binding.Identifier;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
48 import org.opendaylight.yangtools.yang.data.api.Node;
49 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
50 import org.opendaylight.yangtools.yang.data.impl.codec.AugmentationCodec;
51 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCaseCodec;
52 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCodec;
53 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
54 import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
55 import org.opendaylight.yangtools.yang.data.impl.codec.DomCodec;
56 import org.opendaylight.yangtools.yang.data.impl.codec.IdentifierCodec;
57 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
58 import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
59 import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
60 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
61 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
62 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
63 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
64 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
65 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.Module;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
71 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
73 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76
77 import com.google.common.base.Optional;
78 import com.google.common.base.Preconditions;
79 import com.google.common.collect.BiMap;
80 import com.google.common.collect.HashBiMap;
81 import com.google.common.collect.HashMultimap;
82 import com.google.common.collect.Iterables;
83 import com.google.common.collect.Multimap;
84 import com.google.common.collect.Multimaps;
85
86 class LazyGeneratedCodecRegistry implements //
87         CodecRegistry, //
88         SchemaContextListener, //
89         GeneratorListener {
90
91     private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
92
93     // Concrete class to codecs
94     private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = Collections
95             .synchronizedMap(new WeakHashMap<Class<?>, DataContainerCodec<?>>());
96     private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = Collections
97             .synchronizedMap(new WeakHashMap<Class<?>, IdentifierCodec<?>>());
98     private static final Map<Class<?>, PublicChoiceCodecImpl<?>> choiceCodecs = Collections
99             .synchronizedMap(new WeakHashMap<Class<?>, PublicChoiceCodecImpl<?>>());
100     private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = Collections
101             .synchronizedMap(new WeakHashMap<Class<?>, ChoiceCaseCodecImpl<?>>());
102     private static final Map<Class<?>, AugmentableDispatchCodec> augmentableCodecs = Collections
103             .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
104     private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
105             .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
106
107     private static final Map<Class<?>, LocationAwareDispatchCodec<?>> dispatchCodecs = Collections
108             .synchronizedMap(new WeakHashMap<Class<?>, LocationAwareDispatchCodec<?>>());
109
110     private static final Map<Class<?>, QName> identityQNames = Collections
111             .synchronizedMap(new WeakHashMap<Class<?>, QName>());
112     private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
113     /** Binding type to encountered classes mapping **/
114     @SuppressWarnings("rawtypes")
115     private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
116
117     private static final ConcurrentMap<Type, ChoiceCaseNode> caseTypeToCaseSchema = new ConcurrentHashMap<>();
118
119     private static final Map<SchemaPath, Type> pathToType = new ConcurrentHashMap<>();
120     private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
121     private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
122     private static final BiMap<Type, AugmentationSchema> typeToAugment = HashBiMap
123             .create(new ConcurrentHashMap<Type, AugmentationSchema>());
124
125     private static final Multimap<Type, Type> augmentableToAugmentations = Multimaps.synchronizedMultimap(HashMultimap
126             .<Type, Type> create());
127     private static final Multimap<Type, Type> choiceToCases = Multimaps.synchronizedMultimap(HashMultimap
128             .<Type, Type> create());
129
130     private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
131     private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
132     private final ClassLoadingStrategy classLoadingStrategy;
133     private final AbstractTransformerGenerator generator;
134     private final SchemaLock lock;
135
136     // FIXME: how is this protected?
137     private SchemaContext currentSchema;
138
139     LazyGeneratedCodecRegistry(final SchemaLock lock, final AbstractTransformerGenerator generator,
140             final ClassLoadingStrategy classLoadingStrategy) {
141         this.lock = Preconditions.checkNotNull(lock);
142         this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy);
143         this.generator = Preconditions.checkNotNull(generator);
144     }
145
146     public SchemaLock getLock() {
147         return lock;
148     }
149
150     @Override
151     public InstanceIdentifierCodec getInstanceIdentifierCodec() {
152         return instanceIdentifierCodec;
153     }
154
155     @SuppressWarnings("unchecked")
156     @Override
157     public <T extends Augmentation<?>> AugmentationCodecWrapper<T> getCodecForAugmentation(final Class<T> augClass) {
158         AugmentationCodecWrapper<T> codec = null;
159         @SuppressWarnings("rawtypes")
160         AugmentationCodecWrapper potentialCodec = augmentationCodecs.get(augClass);
161         if (potentialCodec != null) {
162             codec = potentialCodec;
163         } else {
164             lock.waitForSchema(augClass);
165             Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
166                     .augmentationTransformerFor(augClass);
167
168             BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(augmentRawCodec);
169             codec = new AugmentationCodecWrapper<T>(rawCodec, augClass);
170             augmentationCodecs.put(augClass, codec);
171         }
172
173         final Class<? extends Augmentable<?>> objectSupertype;
174         try {
175             objectSupertype = BindingReflections.findAugmentationTarget(augClass);
176         } catch (Exception e) {
177             LOG.warn("Failed to find target for augmentation {}, ignoring it", augClass, e);
178             return codec;
179         }
180
181         if (objectSupertype == null) {
182             LOG.warn("Augmentation target for {} not found, ignoring it", augClass);
183             return codec;
184         }
185
186         getAugmentableCodec(objectSupertype).addImplementation(codec);
187         return codec;
188     }
189
190     @SuppressWarnings("unchecked")
191     @Override
192     public QName getQNameForAugmentation(final Class<?> cls) {
193         Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
194         return getCodecForAugmentation((Class<? extends Augmentation<?>>) cls).getAugmentationQName();
195     }
196
197     @Override
198     public Class<?> getClassForPath(final List<QName> names) {
199         DataSchemaNode node = getSchemaNode(names);
200         Preconditions.checkArgument(node != null, "Path %s points to invalid schema location",names);
201         SchemaNode originalDefinition = SchemaNodeUtils.getRootOriginalIfPossible(node);
202         if(originalDefinition instanceof DataSchemaNode) {
203             node =(DataSchemaNode) originalDefinition;
204         }
205         final SchemaPath path = node.getPath();
206         final Type t = pathToType.get(path);
207
208         final Type type;
209         if (t != null) {
210             type = new ReferencedTypeImpl(t.getPackageName(), t.getName());
211         } else {
212             type = pathToInstantiatedType.get(names);
213             Preconditions.checkState(type != null, "Failed to lookup instantiated type for path %s", path);
214         }
215
216         @SuppressWarnings("rawtypes")
217         final WeakReference<Class> weakRef = typeToClass.get(type);
218         if(weakRef != null) {
219             return weakRef.get();
220         }
221         try {
222             return classLoadingStrategy.loadClass(type);
223         } catch (ClassNotFoundException e) {
224             throw new IllegalStateException(String.format("Could not find loaded class for path: %s and type: %s", path,type.getFullyQualifiedName()));
225         }
226     }
227
228     @Override
229     public void putPathToClass(final List<QName> names, final Class<?> cls) {
230         final Type reference = Types.typeForClass(cls);
231         pathToInstantiatedType.put(names, reference);
232         LOG.trace("Path {} attached to class {} reference {}", names, cls, reference);
233         bindingClassEncountered(cls);
234     }
235
236     @Override
237     public IdentifierCodec<?> getKeyCodecForPath(final List<QName> names) {
238         @SuppressWarnings("unchecked")
239         Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
240         return getIdentifierCodecForIdentifiable(cls);
241     }
242
243     @Override
244     public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(final Class<T> type) {
245         @SuppressWarnings("unchecked")
246         DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
247         if (ret != null) {
248             return ret;
249         }
250         Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
251         BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
252         DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
253         containerCodecs.put(type, newWrapper);
254         return newWrapper;
255     }
256
257     @Override
258     @SuppressWarnings("rawtypes")
259     public void bindingClassEncountered(final Class cls) {
260
261         ConcreteType typeRef = Types.typeForClass(cls);
262         if (typeToClass.containsKey(typeRef)) {
263             return;
264         }
265         LOG.trace("Binding Class {} encountered.", cls);
266         WeakReference<Class> weakRef = new WeakReference<>(cls);
267         typeToClass.put(typeRef, weakRef);
268         if (Augmentation.class.isAssignableFrom(cls)) {
269             // Intentionally NOOP
270         } else if (DataObject.class.isAssignableFrom(cls)) {
271             getCodecForDataObject((Class<? extends DataObject>) cls);
272         }
273     }
274
275     @Override
276     public void onClassProcessed(final Class<?> cls) {
277         ConcreteType typeRef = Types.typeForClass(cls);
278         if (typeToClass.containsKey(typeRef)) {
279             return;
280         }
281         LOG.trace("Binding Class {} encountered.", cls);
282         @SuppressWarnings("rawtypes")
283         WeakReference<Class> weakRef = new WeakReference<Class>(cls);
284         typeToClass.put(typeRef, weakRef);
285     }
286
287     private DataSchemaNode getSchemaNode(final List<QName> path) {
288         QName firstNode = path.get(0);
289         DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
290                 firstNode.getRevision());
291         Preconditions.checkArgument(previous != null, "Failed to find module %s for path %s", firstNode, path);
292
293         Iterator<QName> iterator = path.iterator();
294         while (iterator.hasNext()) {
295             QName arg = iterator.next();
296             DataSchemaNode currentNode = previous.getDataChildByName(arg);
297             if (currentNode == null && previous instanceof DataNodeContainer) {
298                 currentNode = searchInChoices(previous, arg);
299             }
300             if (currentNode instanceof DataNodeContainer) {
301                 previous = (DataNodeContainer) currentNode;
302             } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
303                 Preconditions.checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
304                 return currentNode;
305             }
306         }
307         return (DataSchemaNode) previous;
308     }
309
310     private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
311         Set<DataSchemaNode> children = node.getChildNodes();
312         for (DataSchemaNode child : children) {
313             if (child instanceof ChoiceNode) {
314                 ChoiceNode choiceNode = (ChoiceNode) child;
315                 DataSchemaNode potential = searchInCases(choiceNode, arg);
316                 if (potential != null) {
317                     return potential;
318                 }
319             }
320         }
321         return null;
322     }
323
324     private DataSchemaNode searchInCases(final ChoiceNode choiceNode, final QName arg) {
325         Set<ChoiceCaseNode> cases = choiceNode.getCases();
326         for (ChoiceCaseNode caseNode : cases) {
327             DataSchemaNode node = caseNode.getDataChildByName(arg);
328             if (node != null) {
329                 return node;
330             }
331         }
332         return null;
333     }
334
335     private static <T> T newInstanceOf(final Class<?> cls) {
336         try {
337             @SuppressWarnings("unchecked")
338             T ret = (T) cls.newInstance();
339             return ret;
340         } catch (InstantiationException e) {
341             LOG.error("Failed to instantiate codec {}", cls.getSimpleName(), e);
342             throw new IllegalStateException(String.format("Failed to instantiate codec %s", cls), e);
343         } catch (IllegalAccessException e) {
344             LOG.debug(
345                     "Run-time consistency issue: constructor for {} is not available. This indicates either a code generation bug or a misconfiguration of JVM.",
346                     cls.getSimpleName(), e);
347             throw new IllegalStateException(String.format("Cannot access contructor of %s", cls), e);
348         }
349     }
350
351     @Override
352     public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class<T> type) {
353         IdentifierCodec<?> obj = identifierCodecs.get(type);
354         if (obj != null) {
355             return obj;
356         }
357         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
358                 .keyTransformerForIdentifiable(type);
359         BindingCodec<Map<QName, Object>, Object> newInstance;
360         newInstance = newInstanceOf(newCodec);
361         IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
362         identifierCodecs.put(type, newWrapper);
363         return newWrapper;
364     }
365
366     @Override
367     public IdentityCodec<?> getIdentityCodec() {
368         return identityRefCodec;
369     }
370
371     @SuppressWarnings("unchecked")
372     @Override
373     public <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(final Class<T> codec) {
374         bindingClassEncountered(codec);
375         return identityRefCodec;
376     }
377
378     @Override
379     public void onCodecCreated(final Class<?> cls) {
380         CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
381         CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
382     }
383
384     @Override
385     public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> object) {
386         @SuppressWarnings("unchecked")
387         IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
388         if (obj != null) {
389             return obj;
390         }
391         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
392                 .keyTransformerForIdentifier(object);
393         BindingCodec<Map<QName, Object>, Object> newInstance;
394         newInstance = newInstanceOf(newCodec);
395         IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
396         identifierCodecs.put(object, newWrapper);
397         return newWrapper;
398     }
399
400     @SuppressWarnings("rawtypes")
401     public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
402         ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
403         if (potential != null) {
404             return potential;
405         }
406         ConcreteType typeref = Types.typeForClass(caseClass);
407         ChoiceCaseNode caseSchema = caseTypeToCaseSchema.get(typeref);
408
409         Preconditions.checkState(caseSchema != null, "Case schema is not available for %s", caseClass.getName());
410         Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseSchema);
411         BindingCodec newInstance = newInstanceOf(newCodec);
412         @SuppressWarnings("unchecked")
413         ChoiceCaseCodecImpl caseCodec = new ChoiceCaseCodecImpl(caseClass, caseSchema, newInstance);
414         caseCodecs.put(caseClass, caseCodec);
415         return caseCodec;
416     }
417
418     public void onModuleContextAdded(final SchemaContext schemaContext, final Module module, final ModuleContext context) {
419         pathToType.putAll(context.getChildNodes());
420
421         BiMap<Type, AugmentationSchema> bimap = context.getTypeToAugmentation();
422         for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
423             Type key = entry.getKey();
424             AugmentationSchema value = entry.getValue();
425             Set<DataSchemaNode> augmentedNodes = value.getChildNodes();
426             if (augmentedNodes != null && !(augmentedNodes.isEmpty())) {
427                 typeToAugment.put(key, value);
428             }
429         }
430
431         qnamesToIdentityMap.putAll(context.getIdentities());
432         for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
433             typeToQname.put(
434                     new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
435                     identity.getKey());
436         }
437
438         synchronized (augmentableToAugmentations) {
439             augmentableToAugmentations.putAll(context.getAugmentableToAugmentations());
440         }
441         synchronized (choiceToCases) {
442             choiceToCases.putAll(context.getChoiceToCases());
443         }
444         synchronized (caseTypeToCaseSchema) {
445             caseTypeToCaseSchema.putAll(context.getCaseTypeToSchemas());
446         }
447     }
448
449     @Override
450     public void onGlobalContextUpdated(final SchemaContext context) {
451         currentSchema = context;
452         resetDispatchCodecsAdaptation();
453
454     }
455
456     /**
457      * Resets / clears adaptation for all schema context sensitive codecs in
458      * order for them to adapt to new schema context and maybe newly discovered
459      * augmentations This ensure correct behaviour for augmentations and
460      * augmented cases for preexisting codecs, which augmentations were
461      * introduced at later point in time.
462      *
463      * This also makes removed augmentations unavailable.
464      */
465     private void resetDispatchCodecsAdaptation() {
466         synchronized (dispatchCodecs) {
467             for (LocationAwareDispatchCodec<?> codec : dispatchCodecs.values()) {
468                 codec.resetCodec(this);
469             }
470         }
471     }
472
473     @SuppressWarnings({ "unchecked", "rawtypes" })
474     @Override
475     public void onChoiceCodecCreated(final Class<?> choiceClass,
476             final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, final ChoiceNode schema) {
477         ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
478         Preconditions.checkState(oldCodec == null);
479         BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
480         PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
481         DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass,this);
482         choiceCodecs.put(choiceClass, newCodec);
483         synchronized (dispatchCodecs) {
484             dispatchCodecs.put(choiceClass, dispatchCodec);
485         }
486         CodecMapping.setDispatchCodec(choiceCodec, dispatchCodec);
487     }
488
489     @Override
490     public void onValueCodecCreated(final Class<?> valueClass, final Class<?> valueCodec) {
491     }
492
493     @Override
494     public void onCaseCodecCreated(final Class<?> choiceClass,
495             final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
496     }
497
498     @Override
499     public void onDataContainerCodecCreated(final Class<?> dataClass,
500             final Class<? extends BindingCodec<?, ?>> dataCodec) {
501         if (Augmentable.class.isAssignableFrom(dataClass)) {
502             AugmentableDispatchCodec augmentableCodec = getAugmentableCodec(dataClass);
503             CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
504         }
505     }
506
507     public synchronized AugmentableDispatchCodec getAugmentableCodec(final Class<?> dataClass) {
508         AugmentableDispatchCodec ret = augmentableCodecs.get(dataClass);
509         if (ret != null) {
510             return ret;
511         }
512         ret = new AugmentableDispatchCodec(dataClass,this);
513         augmentableCodecs.put(dataClass, ret);
514         synchronized (dispatchCodecs) {
515             dispatchCodecs.put(dataClass, ret);
516         }
517         ret.tryToLoadImplementations();
518         return ret;
519     }
520
521     private static abstract class IntermediateCodec<T> implements //
522             DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
523
524         private final BindingCodec<Map<QName, Object>, Object> delegate;
525
526         @Override
527         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
528             return delegate;
529         }
530
531         public IntermediateCodec(final BindingCodec<Map<QName, Object>, Object> delegate) {
532             this.delegate = delegate;
533         }
534
535         @Override
536         public Node<?> serialize(final ValueWithQName<T> input) {
537             Map<QName, Object> intermediateOutput = delegate.serialize(input);
538             return IntermediateMapping.toNode(intermediateOutput);
539         }
540
541     }
542
543     private static class IdentifierCodecImpl<T extends Identifier<?>> //
544             extends IntermediateCodec<T> //
545             implements IdentifierCodec<T> {
546
547         public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
548             super(delegate);
549         }
550
551         @Override
552         public ValueWithQName<T> deserialize(final Node<?> input) {
553             QName qname = input.getNodeType();
554             @SuppressWarnings("unchecked")
555             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
556             return new ValueWithQName<T>(qname, value);
557         }
558
559         @Override
560         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
561             QName qname = input.getNodeType();
562             @SuppressWarnings("unchecked")
563             T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
564             return new ValueWithQName<T>(qname, value);
565         }
566
567         @Override
568         public CompositeNode serialize(final ValueWithQName<T> input) {
569             return (CompositeNode) super.serialize(input);
570         }
571     }
572
573     private static class DataContainerCodecImpl<T extends DataContainer> //
574             extends IntermediateCodec<T> //
575             implements DataContainerCodec<T> {
576
577         public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
578             super(delegate);
579         }
580
581         @Override
582         public ValueWithQName<T> deserialize(final Node<?> input) {
583             if (input == null) {
584                 return null;
585             }
586             QName qname = input.getNodeType();
587             @SuppressWarnings("unchecked")
588             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
589             return new ValueWithQName<T>(qname, value);
590         }
591
592         @Override
593         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
594             if (input == null) {
595                 return null;
596             }
597             QName qname = input.getNodeType();
598             @SuppressWarnings("unchecked")
599             T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
600             return new ValueWithQName<T>(qname, value);
601         }
602
603         @Override
604         public CompositeNode serialize(final ValueWithQName<T> input) {
605             return (CompositeNode) super.serialize(input);
606         }
607     }
608
609     private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
610
611         boolean isApplicable(InstanceIdentifier<?> parentPath, CompositeNode data);
612
613         public Class<?> getDataType();
614
615     }
616
617     @SuppressWarnings("rawtypes")
618     private static abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements BindingCodec {
619
620         private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
621         private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
622         private LazyGeneratedCodecRegistry registry;
623
624
625         protected LocationAwareDispatchCodec(final LazyGeneratedCodecRegistry registry) {
626             this.registry = registry;
627         }
628
629         protected Map<Class, T> getImplementations() {
630             return implementations;
631         }
632
633         /**
634          * Resets codec adaptation based on location and schema context.
635          *
636          * This is required if new cases / augmentations were introduced or
637          * removed and first use of codec is triggered by invocation from DOM to
638          * Java, so the implementations may change and this may require loading
639          * of new codecs and/or removal of existing ones.
640          *
641          */
642         public synchronized void resetCodec(final LazyGeneratedCodecRegistry currentRegistry) {
643             registry = currentRegistry;
644             adaptedForPaths.clear();
645             resetAdaptationImpl();
646         }
647
648         protected void resetAdaptationImpl() {
649             // Intentionally NOOP, subclasses may specify their custom
650             // behaviour.
651         }
652
653         protected final LazyGeneratedCodecRegistry getRegistry() {
654             return registry;
655         }
656         protected void addImplementation(final T implementation) {
657             implementations.put(implementation.getDataType(), implementation);
658         }
659
660         @Override
661         public final Object deserialize(final Object input) {
662             throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
663         }
664
665         @Override
666         public final Object deserialize(final Object parent, final InstanceIdentifier parentPath) {
667             adaptForPath(parentPath);
668             Preconditions.checkArgument(parent instanceof CompositeNode, "node must be of CompositeNode type.");
669             CompositeNode parentData = (CompositeNode) parent;
670             ArrayList<T> applicable = new ArrayList<>(implementations.size());
671
672             /*
673              * Codecs are filtered to only ones, which
674              * are applicable in supplied parent context.
675              *
676              */
677             for (T impl : getImplementations().values()) {
678                 @SuppressWarnings("unchecked")
679                 boolean codecApplicable = impl.isApplicable(parentPath, parentData);
680                 if (codecApplicable) {
681                     applicable.add(impl);
682                 }
683             }
684             LOG.trace("{}: Deserializing mixins from {}, Schema Location {}, Applicable Codecs: {}, All Codecs: {}",this,parent,parentPath,applicable,getImplementations().values());
685
686             /* In case of none is applicable, we return
687              * null. Since there is no mixin which
688              * is applicable in this location.
689             */
690             if(applicable.isEmpty()) {
691                 return null;
692             }
693             return deserializeImpl(parentData, parentPath, applicable);
694         }
695
696         protected abstract Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> parentPath,
697                 Iterable<T> applicableCodecs);
698
699         @Override
700         public Object serialize(final Object input) {
701             Preconditions.checkArgument(input instanceof DataContainer);
702             Class<? extends DataContainer> inputType = ((DataContainer) input).getImplementedInterface();
703             T implementation = implementations.get(inputType);
704             if (implementation == null) {
705                 implementation = tryToLoadImplementationImpl(inputType);
706             }
707
708             return null;
709         }
710
711         private T tryToLoadImplementationImpl(final Class<? extends DataContainer> inputType) {
712             T implementation = tryToLoadImplementation(inputType);
713             Preconditions.checkArgument(implementation != null, "Data type %s is not supported.", inputType);
714             addImplementation(implementation);
715             return implementation;
716         }
717
718         protected final synchronized void adaptForPath(final InstanceIdentifier<?> path) {
719             if (adaptedForPaths.contains(path)) {
720                 return;
721             }
722             LOG.debug("Adapting mixin codec {} for path {}",this,path);
723             /**
724              * We search in schema context if the use of this location aware
725              * codec (augmentable codec, case codec) makes sense on provided
726              * location (path)
727              *
728              */
729             Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(getRegistry().currentSchema,
730                     path);
731             /**
732              * If context node is present, this codec makes sense on provided
733              * location.
734              *
735              */
736             if (contextNode.isPresent()) {
737                 synchronized (this) {
738                     /**
739                      *
740                      * We adapt (turn on / off) possible implementations of
741                      * child codecs (augmentations, cases) based on this
742                      * location.
743                      *
744                      *
745                      */
746
747                     adaptForPathImpl(path, contextNode.get());
748                     try {
749                         /**
750                          * We trigger serialization of instance identifier, to
751                          * make sure instance identifier codec is aware of
752                          * combination of this path / augmentation / case
753                          */
754                         getRegistry().getInstanceIdentifierCodec().serialize(path);
755                     } catch (Exception e) {
756                         LOG.warn("Exception during preparation of instance identifier codec for  path {}.", path, e);
757                     }
758                     adaptedForPaths.add(path);
759                 }
760             } else {
761                 LOG.debug("Context node (parent node) not found for {}", path);
762             }
763         }
764
765         protected abstract T tryToLoadImplementation(Class<? extends DataContainer> inputType);
766
767         protected abstract void tryToLoadImplementations();
768
769         protected abstract void adaptForPathImpl(InstanceIdentifier<?> path, DataNodeContainer ctx);
770     }
771
772     @SuppressWarnings("rawtypes")
773     private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
774             Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
775         private final BindingCodec delegate;
776         private final ChoiceCaseNode schema;
777         private final Map<InstanceIdentifier<?>, ChoiceCaseNode> instantiatedLocations;
778         private final Class<?> dataType;
779
780         public ChoiceCaseCodecImpl(final Class<?> caseClass, final ChoiceCaseNode caseNode,
781                 final BindingCodec newInstance) {
782             this.delegate = newInstance;
783             this.dataType = caseClass;
784             this.schema = caseNode;
785             instantiatedLocations = new HashMap<>();
786         }
787
788         @Override
789         public ValueWithQName<T> deserialize(final Node<?> input) {
790             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
791         }
792
793         @Override
794         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
795             if (input == null) {
796                 return null;
797             }
798             QName qname = input.getNodeType();
799             synchronized (instantiatedLocations) {
800                 ChoiceCaseNode instantiation = instantiatedLocations.get(bindingIdentifier);
801                 if (instantiation != null) {
802                     qname = instantiatedLocations.get(bindingIdentifier).getQName();
803                 }
804             }
805             @SuppressWarnings("unchecked")
806             T value = (T) getDelegate().deserialize(new SimpleEntry(qname, input), bindingIdentifier);
807             return new ValueWithQName<T>(qname, value);
808         }
809
810         @Override
811         public CompositeNode serialize(final ValueWithQName<T> input) {
812             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
813         }
814
815         @Override
816         public BindingCodec getDelegate() {
817             return delegate;
818         }
819
820         public ChoiceCaseNode getSchema() {
821             return schema;
822         }
823
824         @Override
825         @Deprecated
826         public boolean isAcceptable(final Node<?> input) {
827             return checkAgainstSchema(schema, input);
828         }
829
830         private static boolean checkAgainstSchema(final ChoiceCaseNode schema, final Node<?> node) {
831             if (node instanceof CompositeNode) {
832                 CompositeNode input = (CompositeNode) node;
833                 for (Node<?> childNode : input.getValue()) {
834                     QName child = childNode.getNodeType();
835                     if (schema.getDataChildByName(child) != null) {
836                         return true;
837                     }
838                 }
839             }
840             return false;
841         }
842
843         @Override
844         public Class<?> getDataType() {
845             return dataType;
846         }
847
848         public void adaptForPath(final InstanceIdentifier<?> augTarget, final ChoiceCaseNode choiceCaseNode) {
849             synchronized (instantiatedLocations) {
850                 instantiatedLocations.put(augTarget, choiceCaseNode);
851             }
852         }
853
854         @Override
855         public boolean isApplicable(final InstanceIdentifier path, final CompositeNode input) {
856             ChoiceCaseNode instantiatedSchema = null;
857             synchronized (instantiatedLocations) {
858                 instantiatedSchema = instantiatedLocations.get(path);
859             }
860             if (instantiatedSchema == null) {
861                 return false;
862             }
863             return checkAgainstSchema(instantiatedSchema, input);
864         }
865
866         protected boolean isAugmenting(final QName choiceName, final QName proposedQName) {
867             if (schema.isAugmenting()) {
868                 return true;
869             }
870             // Choice QName
871             QName parentQName = Iterables.get(schema.getPath().getPathTowardsRoot(), 1);
872             if (!parentQName.getNamespace().equals(schema.getQName().getNamespace())) {
873                 return true;
874             }
875             if (!parentQName.equals(choiceName)) {
876                 // This item is instantiation of choice via uses in other YANG
877                 // module
878                 if (choiceName.getNamespace().equals(schema.getQName())) {
879                     // Original definition of grouping is in same namespace
880                     // as original definition of case
881                     // so for sure case is introduced via instantiation of
882                     // grouping
883                     return false;
884                 }
885                 // Since we are still here, that means case has same namespace
886                 // as its parent, which is instantiation of grouping
887                 // but case namespace is different from parent node
888                 // so it is augmentation.
889                 return true;
890             }
891             return false;
892         }
893
894         @Override
895         public String toString() {
896             return "ChoiceCaseCodec [case=" + dataType
897                     + ", knownLocations=" + instantiatedLocations.keySet() + "]";
898         }
899     }
900
901     private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>,
902             Delegator<BindingCodec<Map<QName, Object>, Object>> {
903
904         private final BindingCodec<Map<QName, Object>, Object> delegate;
905
906         public PublicChoiceCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
907             this.delegate = delegate;
908         }
909
910         @Override
911         public ValueWithQName<T> deserialize(final Node<?> input) {
912             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
913         }
914
915         @Override
916         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
917             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
918         }
919
920         @Override
921         public Node<?> serialize(final ValueWithQName<T> input) {
922             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
923         }
924
925         @Override
926         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
927             return delegate;
928         }
929
930     }
931
932     class DispatchChoiceCodecImpl extends LocationAwareDispatchCodec<ChoiceCaseCodecImpl<?>> {
933         private final Class<?> choiceType;
934         private final QName choiceName;
935
936         private DispatchChoiceCodecImpl(final Class<?> type, final LazyGeneratedCodecRegistry registry) {
937             super(registry);
938             choiceType = type;
939             choiceName = BindingReflections.findQName(type);
940         }
941
942         @Override
943         public Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
944                 final Iterable<ChoiceCaseCodecImpl<?>> codecs) {
945             ChoiceCaseCodecImpl<?> caseCodec = Iterables.getOnlyElement(codecs);
946             ValueWithQName<?> value = caseCodec.deserialize(input, path);
947             if (value != null) {
948                 return value.getValue();
949             }
950             return null;
951         }
952
953         @SuppressWarnings("unchecked")
954         @Override
955         public Object serialize(final Object input) {
956             Preconditions.checkArgument(input instanceof Map.Entry<?, ?>, "Input must be QName, Value");
957             @SuppressWarnings("rawtypes")
958             QName derivedQName = (QName) ((Map.Entry) input).getKey();
959             @SuppressWarnings("rawtypes")
960             Object inputValue = ((Map.Entry) input).getValue();
961             Preconditions.checkArgument(inputValue instanceof DataObject);
962             Class<? extends DataContainer> inputType = ((DataObject) inputValue).getImplementedInterface();
963             ChoiceCaseCodecImpl<?> codec = tryToLoadImplementation(inputType);
964             Preconditions.checkState(codec != null, "Unable to get codec for %s", inputType);
965             if (codec.isAugmenting(choiceName, derivedQName)) {
966                 // If choice is augmenting we use QName which defined this
967                 // augmentation
968                 return codec.getDelegate().serialize(new ValueWithQName<>(codec.getSchema().getQName(), inputValue));
969             }
970             return codec.getDelegate().serialize(input);
971         }
972
973         @SuppressWarnings("rawtypes")
974         protected Optional<ChoiceCaseCodecImpl> tryToLoadImplementation(final Type potential) {
975             try {
976                 @SuppressWarnings("unchecked")
977                 Class<? extends DataContainer> clazz = (Class<? extends DataContainer>) classLoadingStrategy
978                         .loadClass(potential);
979                 ChoiceCaseCodecImpl codec = tryToLoadImplementation(clazz);
980                 addImplementation(codec);
981                 return Optional.of(codec);
982             } catch (ClassNotFoundException e) {
983                 LOG.warn("Failed to find class for choice {}", potential, e);
984             }
985             return Optional.absent();
986         }
987
988         @Override
989         protected ChoiceCaseCodecImpl<?> tryToLoadImplementation(final Class<? extends DataContainer> inputType) {
990             ChoiceCaseCodecImpl<?> codec = getCaseCodecFor(inputType);
991             addImplementation(codec);
992             return codec;
993         }
994
995         @Override
996         protected void tryToLoadImplementations() {
997             Type type = referencedType(choiceType);
998             Collection<Type> potentialCases;
999             synchronized (choiceToCases) {
1000                 potentialCases = choiceToCases.get(type);
1001             }
1002             for (Type potential : potentialCases) {
1003                 try {
1004                     tryToLoadImplementation(potential);
1005                 } catch (CodeGenerationException e) {
1006                     LOG.warn("Failed to proactively generate choice code for {}", type, e);
1007                 }
1008             }
1009         }
1010
1011         @Override
1012         protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1013             Optional<ChoiceNode> newChoice = BindingSchemaContextUtils.findInstantiatedChoice(ctxNode, choiceType);
1014             tryToLoadImplementations();
1015             Preconditions.checkState(newChoice.isPresent(), "BUG: Unable to find instantiated choice node in schema.");
1016             for (@SuppressWarnings("rawtypes")
1017             Entry<Class, ChoiceCaseCodecImpl<?>> codec : getImplementations().entrySet()) {
1018                 ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
1019                 Optional<ChoiceCaseNode> instantiatedSchema = BindingSchemaContextUtils.findInstantiatedCase(newChoice.get(),
1020                         caseCodec.getSchema());
1021                 if (instantiatedSchema.isPresent()) {
1022                     caseCodec.adaptForPath(augTarget, instantiatedSchema.get());
1023                 }
1024             }
1025         }
1026
1027
1028
1029         @Override
1030         public String toString() {
1031             return "DispatchChoiceCodecImpl [choiceType=" + choiceType + "]";
1032         }
1033     }
1034
1035     @SuppressWarnings({ "rawtypes", "unchecked" })
1036     static class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
1037
1038         private final Class augmentableType;
1039
1040         public AugmentableDispatchCodec(final Class type, final LazyGeneratedCodecRegistry registry) {
1041             super(registry);
1042             Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
1043             augmentableType = type;
1044         }
1045
1046         @Override
1047         // TODO deprecate use without iid
1048         public Object serialize(final Object input) {
1049             if (input instanceof Augmentable<?>) {
1050                 Map<Class, Augmentation> augmentations = getAugmentations(input);
1051                 return serializeImpl(augmentations);
1052             }
1053             return null;
1054         }
1055
1056         private Map<Class, Augmentation> getAugmentations(final Object input) {
1057             Field augmentationField;
1058             try {
1059                 augmentationField = input.getClass().getDeclaredField("augmentation");
1060                 augmentationField.setAccessible(true);
1061                 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
1062                 return augMap;
1063             } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
1064                 LOG.debug("Could not read augmentations for {}", input, e);
1065             }
1066             return Collections.emptyMap();
1067         }
1068
1069         @SuppressWarnings("deprecation")
1070         private List serializeImpl(final Map<Class, Augmentation> input) {
1071             List ret = new ArrayList<>();
1072             for (Entry<Class, Augmentation> entry : input.entrySet()) {
1073                 AugmentationCodec codec = getRegistry().getCodecForAugmentation(entry.getKey());
1074                 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
1075                 ret.addAll(node.getChildren());
1076             }
1077             return ret;
1078         }
1079
1080         @Override
1081         public Map<Class, Augmentation> deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
1082                 final Iterable<AugmentationCodecWrapper> codecs) {
1083             LOG.trace("{}: Going to deserialize augmentations from {} in location {}. Available codecs {}",this,input,path,codecs);
1084             Map<Class, Augmentation> ret = new HashMap<>();
1085             for (AugmentationCodecWrapper codec : codecs) {
1086                     // We add Augmentation Identifier to path, in order to
1087                     // correctly identify children.
1088                     Class type = codec.getDataType();
1089                     final InstanceIdentifier augmentPath = path.augmentation(type);
1090                     ValueWithQName<?> value = codec.deserialize(input, augmentPath);
1091                     if (value != null && value.getValue() != null) {
1092                         ret.put(type, (Augmentation) value.getValue());
1093                     }
1094             }
1095             return ret;
1096         }
1097
1098         protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
1099             try {
1100                 Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) getRegistry().classLoadingStrategy
1101                         .loadClass(potential);
1102                 return Optional.of(tryToLoadImplementation(clazz));
1103             } catch (ClassNotFoundException e) {
1104                 LOG.warn("Failed to find class for augmentation of {}", potential, e);
1105             }
1106             return Optional.absent();
1107         }
1108
1109         @Override
1110         protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
1111             AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getRegistry().getCodecForAugmentation(inputType);
1112             addImplementation(potentialImpl);
1113             return potentialImpl;
1114         }
1115
1116         @Override
1117         protected void tryToLoadImplementations() {
1118             Type type = referencedType(augmentableType);
1119             Collection<Type> potentialAugmentations;
1120             synchronized (augmentableToAugmentations) {
1121                 potentialAugmentations = new ArrayList(augmentableToAugmentations.get(type));
1122             }
1123             for (Type potential : potentialAugmentations) {
1124                 try {
1125                     tryToLoadImplementation(potential);
1126                 } catch (CodeGenerationException e) {
1127                     LOG.warn("Failed to proactively generate augment code for {}", type, e);
1128                 }
1129             }
1130         }
1131
1132         @Override
1133         protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1134             if (ctxNode instanceof AugmentationTarget) {
1135                 Set<AugmentationSchema> availableAugmentations = ((AugmentationTarget) ctxNode)
1136                         .getAvailableAugmentations();
1137                 if (!availableAugmentations.isEmpty()) {
1138                     updateAugmentationMapping(augTarget, availableAugmentations);
1139                 }
1140             }
1141         }
1142
1143         /**
1144          *
1145          * Adapts augmentation codec for specific provider location (target)
1146          *
1147          * Since augmentation are not forward-referencing and may be discovered
1148          * during runtime, we need to adapt {@link AugmentableDispatchCodec},
1149          * {@link AugmentationCodecWrapper} and {@link InstanceIdentifierCodec}
1150          * for this newly discovered location where augmentation may be used.
1151          *
1152          * Adaptation consists of:
1153          * <ol>
1154          * <li>scan of available (valid) augmentations for current location
1155          * <li>lookup for Java classes derived from this augmentations
1156          * <li>generation of missing codecs
1157          * <li>updating Augmentation codecs to work with new location
1158          * <li>updating Instance Identifier to work with new location
1159          *
1160          */
1161         private void updateAugmentationMapping(final InstanceIdentifier<?> augTarget,
1162                 final Set<AugmentationSchema> availableAugmentations) {
1163             for (AugmentationSchema aug : availableAugmentations) {
1164
1165                 Type potentialType = getTypeForAugmentation(aug);
1166                 if (potentialType != null) {
1167                     Optional<AugmentationCodecWrapper> potentialImpl = tryToLoadImplementation(potentialType);
1168                     if (potentialImpl.isPresent()) {
1169                         potentialImpl.get().addApplicableFor(augTarget, aug);
1170                         Class augType = potentialImpl.get().getDataType();
1171                         InstanceIdentifier augPath = augTarget.augmentation(augType);
1172                         try {
1173
1174                             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = getRegistry().getInstanceIdentifierCodec()
1175                                     .serialize(augPath);
1176                             if (domPath == null) {
1177                                 LOG.error("Unable to serialize instance identifier for {}", augPath);
1178                             }
1179                         } catch (Exception e) {
1180                             LOG.error("Unable to serialize instance identifiers for {}", augPath, e);
1181                         }
1182
1183                     }
1184                 } else {
1185                     // Omits warning for empty augmentations since they are not
1186                     // represented in data
1187                     if (!aug.getChildNodes().isEmpty()) {
1188                         LOG.warn("Could not find generated type for augmentation {} with children {}", aug,
1189                                 aug.getChildNodes());
1190                     }
1191                 }
1192             }
1193         }
1194
1195         private Type getTypeForAugmentation(final AugmentationSchema aug) {
1196             Optional<AugmentationSchema> currentAug = Optional.of(aug);
1197             while (currentAug.isPresent()) {
1198                 Type potentialType = typeToAugment.inverse().get(currentAug.get());
1199                 if (potentialType != null) {
1200                     return potentialType;
1201                 }
1202                 currentAug = currentAug.get().getOriginalDefinition();
1203             }
1204             return null;
1205         }
1206
1207         @Override
1208         public String toString() {
1209             return "AugmentableDispatchCodec [augmentable=" + augmentableType + "]";
1210         }
1211
1212     }
1213
1214     @SuppressWarnings("rawtypes")
1215     private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
1216             Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
1217
1218         private final BindingCodec delegate;
1219         private final QName augmentationQName;
1220         private final Multimap<InstanceIdentifier<?>, QName> validAugmentationTargets;
1221         private final Class<?> augmentationType;
1222
1223         public AugmentationCodecWrapper(final BindingCodec<Map<QName, Object>, Object> rawCodec, final Class<?> dataType) {
1224             this.delegate = rawCodec;
1225             this.augmentationType = dataType;
1226             this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
1227             this.validAugmentationTargets = Multimaps.synchronizedSetMultimap(HashMultimap
1228                     .<InstanceIdentifier<?>, QName> create());
1229         }
1230
1231         public void addApplicableFor(final InstanceIdentifier<?> path, final AugmentationSchema aug) {
1232             for (DataSchemaNode child : aug.getChildNodes()) {
1233                 validAugmentationTargets.put(path, child.getQName());
1234             }
1235         }
1236
1237         @Override
1238         public BindingCodec getDelegate() {
1239             return delegate;
1240         }
1241
1242         @Override
1243         public CompositeNode serialize(final ValueWithQName<T> input) {
1244             @SuppressWarnings("unchecked")
1245             List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
1246             List<Node<?>> serialized = new ArrayList<>(rawValues.size());
1247             for (Map<QName, Object> val : rawValues) {
1248                 serialized.add(IntermediateMapping.toNode(val));
1249             }
1250             return new CompositeNodeTOImpl(input.getQname(), null, serialized);
1251         }
1252
1253         @Override
1254         @SuppressWarnings("unchecked")
1255         public ValueWithQName<T> deserialize(final Node<?> input) {
1256             Object rawCodecValue = getDelegate().deserialize(input);
1257             return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1258         }
1259
1260         @Override
1261         @SuppressWarnings("unchecked")
1262         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
1263             Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
1264             return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1265         }
1266
1267         @Override
1268         public QName getAugmentationQName() {
1269             return augmentationQName;
1270         }
1271
1272         @Override
1273         public boolean isAcceptable(final InstanceIdentifier<?> path) {
1274             if (path == null) {
1275                 return false;
1276             }
1277             return validAugmentationTargets.containsKey(path);
1278         }
1279
1280         @Override
1281         public boolean isApplicable(final InstanceIdentifier parentPath,final CompositeNode parentData) {
1282             return isAcceptable(parentPath);
1283         }
1284
1285         @Override
1286         public Class<?> getDataType() {
1287             return augmentationType;
1288         }
1289
1290         @Override
1291         public String toString() {
1292             return "AugmentationCodecWrapper [augmentation=" + augmentationType
1293                     + ", knownLocations=" + validAugmentationTargets.keySet() + "]";
1294         }
1295     }
1296
1297     @SuppressWarnings("rawtypes")
1298     private class IdentityCompositeCodec implements IdentityCodec {
1299
1300         @Override
1301         public Object deserialize(final Object input) {
1302             Preconditions.checkArgument(input instanceof QName);
1303             return deserialize((QName) input);
1304         }
1305
1306         @Override
1307         public Class<?> deserialize(final QName input) {
1308             if(input == null) {
1309                 return null;
1310             }
1311             Type type = qnamesToIdentityMap.get(input);
1312             if (type == null) {
1313                 String packageName = BindingMapping.getRootPackageName(input);
1314                 String className = BindingMapping.getClassName(input);
1315                 type = new ReferencedTypeImpl(packageName, className);
1316             }
1317             ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1318             WeakReference<Class> softref = typeToClass.get(typeref);
1319             if (softref == null) {
1320
1321                 try {
1322                     Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1323                     if (cls != null) {
1324                         serialize(cls);
1325                         return cls;
1326                     }
1327                 } catch (Exception e) {
1328                     LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1329                             typeref.getFullyQualifiedName());
1330                 }
1331                 return null;
1332             }
1333             return softref.get();
1334         }
1335
1336         @Override
1337         public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
1338             Type type = qnamesToIdentityMap.get(input);
1339             if (type == null) {
1340                 throw new IllegalArgumentException( "Invalid for \"" + input + "\"." );
1341             }
1342             ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1343             WeakReference<Class> softref = typeToClass.get(typeref);
1344             if (softref == null) {
1345
1346                 try {
1347                     Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1348                     if (cls != null) {
1349                         serialize(cls);
1350                         return cls;
1351                     }
1352                 } catch (Exception e) {
1353                     LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1354                             typeref.getFullyQualifiedName());
1355                 }
1356                 return null;
1357             }
1358             return softref.get();
1359         }
1360
1361         @Override
1362         public QName serialize(final Class input) {
1363             Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
1364             bindingClassEncountered(input);
1365             QName qname = identityQNames.get(input);
1366             if (qname != null) {
1367                 return qname;
1368             }
1369             qname = BindingReflections.findQName(input);
1370             if (qname != null) {
1371                 identityQNames.put(input, qname);
1372             }
1373             return qname;
1374         }
1375
1376         @Override
1377         public Object serialize(final Object input) {
1378             Preconditions.checkArgument(input instanceof Class);
1379             return serialize((Class) input);
1380         }
1381
1382     }
1383
1384     private static final Type referencedType(final Class<?> augmentableType) {
1385         return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());
1386     }
1387 }