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