Introduce Identifiables
[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.ArrayList;
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.HashMap;
16 import java.util.HashSet;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.Objects;
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.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
37 import org.opendaylight.yangtools.yang.binding.Augmentable;
38 import org.opendaylight.yangtools.yang.binding.Augmentation;
39 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
40 import org.opendaylight.yangtools.yang.binding.BindingCodec;
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.SchemaPath;
72 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75
76 import com.google.common.base.Optional;
77 import com.google.common.base.Preconditions;
78 import com.google.common.collect.BiMap;
79 import com.google.common.collect.HashBiMap;
80 import com.google.common.collect.HashMultimap;
81 import com.google.common.collect.Multimap;
82 import com.google.common.collect.Multimaps;
83
84 class LazyGeneratedCodecRegistry implements //
85         CodecRegistry, //
86         SchemaContextListener, //
87         GeneratorListener {
88
89     private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
90     private static final LateMixinCodec NOT_READY_CODEC = new LateMixinCodec();
91
92     // Concrete class to codecs
93     private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = Collections
94             .synchronizedMap(new WeakHashMap<Class<?>, DataContainerCodec<?>>());
95     private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = Collections
96             .synchronizedMap(new WeakHashMap<Class<?>, IdentifierCodec<?>>());
97     private static final Map<Class<?>, PublicChoiceCodecImpl<?>> choiceCodecs = Collections
98             .synchronizedMap(new WeakHashMap<Class<?>, PublicChoiceCodecImpl<?>>());
99     private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = Collections
100             .synchronizedMap(new WeakHashMap<Class<?>, ChoiceCaseCodecImpl<?>>());
101     private static final Map<Class<?>, AugmentableDispatchCodec> augmentableCodecs = Collections
102             .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
103     private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
104             .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
105     private static final Map<Class<?>, QName> identityQNames = Collections
106             .synchronizedMap(new WeakHashMap<Class<?>, QName>());
107     private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
108     /** Binding type to encountered classes mapping **/
109     @SuppressWarnings("rawtypes")
110     private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
111
112     @SuppressWarnings("rawtypes")
113     private static final ConcurrentMap<Type, ChoiceCaseCodecImpl> typeToCaseCodecs = new ConcurrentHashMap<>();
114
115     private static final Map<SchemaPath, Type> pathToType = new ConcurrentHashMap<>();
116     private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
117     private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
118     private static final BiMap<Type, AugmentationSchema> typeToAugment = HashBiMap
119             .create(new ConcurrentHashMap<Type, AugmentationSchema>());
120
121     private static final Multimap<Type, Type> augmentableToAugmentations = Multimaps.synchronizedMultimap(HashMultimap
122             .<Type, Type> create());
123     private static final Multimap<Type, Type> choiceToCases = Multimaps.synchronizedMultimap(HashMultimap
124             .<Type, Type> create());
125
126     private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
127     private final CaseClassMapFacade classToCaseRawCodec = new CaseClassMapFacade();
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             @SuppressWarnings({ "unchecked", "unused" })
259             Object cdc = getCodecForDataObject((Class<? extends DataObject>) cls);
260         }
261     }
262
263     @Override
264     public void onClassProcessed(final Class<?> cls) {
265         ConcreteType typeRef = Types.typeForClass(cls);
266         if (typeToClass.containsKey(typeRef)) {
267             return;
268         }
269         LOG.trace("Binding Class {} encountered.", cls);
270         @SuppressWarnings("rawtypes")
271         WeakReference<Class> weakRef = new WeakReference<Class>(cls);
272         typeToClass.put(typeRef, weakRef);
273     }
274
275     private DataSchemaNode getSchemaNode(final List<QName> path) {
276         QName firstNode = path.get(0);
277         DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
278                 firstNode.getRevision());
279         Preconditions.checkArgument(previous != null, "Failed to find module %s for path %s", firstNode, path);
280
281         Iterator<QName> iterator = path.iterator();
282         while (iterator.hasNext()) {
283             QName arg = iterator.next();
284             DataSchemaNode currentNode = previous.getDataChildByName(arg);
285             if (currentNode == null && previous instanceof DataNodeContainer) {
286                 currentNode = searchInChoices(previous, arg);
287             }
288             if (currentNode instanceof DataNodeContainer) {
289                 previous = (DataNodeContainer) currentNode;
290             } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
291                 Preconditions.checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
292                 return currentNode;
293             }
294         }
295         return (DataSchemaNode) previous;
296     }
297
298     private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
299         Set<DataSchemaNode> children = node.getChildNodes();
300         for (DataSchemaNode child : children) {
301             if (child instanceof ChoiceNode) {
302                 ChoiceNode choiceNode = (ChoiceNode) child;
303                 DataSchemaNode potential = searchInCases(choiceNode, arg);
304                 if (potential != null) {
305                     return potential;
306                 }
307             }
308         }
309         return null;
310     }
311
312     private DataSchemaNode searchInCases(final ChoiceNode choiceNode, final QName arg) {
313         Set<ChoiceCaseNode> cases = choiceNode.getCases();
314         for (ChoiceCaseNode caseNode : cases) {
315             DataSchemaNode node = caseNode.getDataChildByName(arg);
316             if (node != null) {
317                 return node;
318             }
319         }
320         return null;
321     }
322
323     private static <T> T newInstanceOf(final Class<?> cls) {
324         try {
325             @SuppressWarnings("unchecked")
326             T ret = (T) cls.newInstance();
327             return ret;
328         } catch (InstantiationException e) {
329             LOG.error("Failed to instantiate codec {}", cls.getSimpleName(), e);
330             throw new IllegalStateException(String.format("Failed to instantiate codec %s", cls), e);
331         } catch (IllegalAccessException e) {
332             LOG.debug(
333                     "Run-time consistency issue: constructor for {} is not available. This indicates either a code generation bug or a misconfiguration of JVM.",
334                     cls.getSimpleName(), e);
335             throw new IllegalStateException(String.format("Cannot access contructor of %s", cls), e);
336         }
337     }
338
339     @Override
340     public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class<T> type) {
341         IdentifierCodec<?> obj = identifierCodecs.get(type);
342         if (obj != null) {
343             return obj;
344         }
345         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
346                 .keyTransformerForIdentifiable(type);
347         BindingCodec<Map<QName, Object>, Object> newInstance;
348         newInstance = newInstanceOf(newCodec);
349         IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
350         identifierCodecs.put(type, newWrapper);
351         return newWrapper;
352     }
353
354     @Override
355     public IdentityCodec<?> getIdentityCodec() {
356         return identityRefCodec;
357     }
358
359     @SuppressWarnings("unchecked")
360     @Override
361     public <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(final Class<T> codec) {
362         bindingClassEncountered(codec);
363         return identityRefCodec;
364     }
365
366     @Override
367     public void onCodecCreated(final Class<?> cls) {
368         CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
369         CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
370     }
371
372     @Override
373     public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> object) {
374         @SuppressWarnings("unchecked")
375         IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
376         if (obj != null) {
377             return obj;
378         }
379         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
380                 .keyTransformerForIdentifier(object);
381         BindingCodec<Map<QName, Object>, Object> newInstance;
382         newInstance = newInstanceOf(newCodec);
383         IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
384         identifierCodecs.put(object, newWrapper);
385         return newWrapper;
386     }
387
388     @SuppressWarnings("rawtypes")
389     public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
390         ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
391         if (potential != null) {
392             return potential;
393         }
394         ConcreteType typeref = Types.typeForClass(caseClass);
395         ChoiceCaseCodecImpl caseCodec = typeToCaseCodecs.get(typeref);
396
397         Preconditions.checkState(caseCodec != null, "Case Codec was not created proactivelly for %s",
398                 caseClass.getName());
399         Preconditions.checkState(caseCodec.getSchema() != null, "Case schema is not available for %s",
400                 caseClass.getName());
401         Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseCodec.getSchema());
402         BindingCodec newInstance = newInstanceOf(newCodec);
403         caseCodec.setDelegate(newInstance);
404         caseCodecs.put(caseClass, caseCodec);
405
406         for (Entry<Class<?>, PublicChoiceCodecImpl<?>> choice : choiceCodecs.entrySet()) {
407             if (choice.getKey().isAssignableFrom(caseClass)) {
408                 choice.getValue().cases.put(caseClass, caseCodec);
409             }
410         }
411         return caseCodec;
412     }
413
414     public void onModuleContextAdded(final SchemaContext schemaContext, final Module module, final ModuleContext context) {
415         pathToType.putAll(context.getChildNodes());
416
417         BiMap<Type, AugmentationSchema> bimap = context.getTypeToAugmentation();
418         for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
419             Type key = entry.getKey();
420             AugmentationSchema value = entry.getValue();
421             Set<DataSchemaNode> augmentedNodes = value.getChildNodes();
422             if (augmentedNodes != null && !(augmentedNodes.isEmpty())) {
423                 typeToAugment.put(key, value);
424             }
425         }
426
427         qnamesToIdentityMap.putAll(context.getIdentities());
428         for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
429             typeToQname.put(
430                     new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
431                     identity.getKey());
432         }
433
434         synchronized (augmentableToAugmentations) {
435             augmentableToAugmentations.putAll(context.getAugmentableToAugmentations());
436         }
437         synchronized (choiceToCases) {
438             choiceToCases.putAll(context.getChoiceToCases());
439         }
440         captureCases(context.getCases(), schemaContext);
441     }
442
443     private void captureCases(final Map<SchemaPath, GeneratedTypeBuilder> cases, final SchemaContext module) {
444         for (Entry<SchemaPath, GeneratedTypeBuilder> caseNode : cases.entrySet()) {
445             ReferencedTypeImpl typeref = new ReferencedTypeImpl(caseNode.getValue().getPackageName(), caseNode
446                     .getValue().getName());
447
448             pathToType.put(caseNode.getKey(), caseNode.getValue());
449
450             ChoiceCaseNode node = (ChoiceCaseNode) SchemaContextUtil.findDataSchemaNode(module, caseNode.getKey());
451
452             if (node == null) {
453                 LOG.warn("Failed to find YANG SchemaNode for {}, with path {} was not found in context.",
454                         typeref.getFullyQualifiedName(), caseNode.getKey());
455                 @SuppressWarnings("rawtypes")
456                 ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl();
457                 typeToCaseCodecs.putIfAbsent(typeref, value);
458                 continue;
459             }
460             @SuppressWarnings("rawtypes")
461             ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl(node);
462             typeToCaseCodecs.putIfAbsent(typeref, value);
463         }
464     }
465
466     @Override
467     public void onGlobalContextUpdated(final SchemaContext context) {
468         currentSchema = context;
469     }
470
471     @SuppressWarnings({ "unchecked", "rawtypes" })
472     @Override
473     public void onChoiceCodecCreated(final Class<?> choiceClass,
474             final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, final ChoiceNode schema) {
475         ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
476         Preconditions.checkState(oldCodec == null);
477         BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
478         PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
479         choiceCodecs.put(choiceClass, newCodec);
480         CodecMapping.setClassToCaseMap(choiceCodec, classToCaseRawCodec);
481         CodecMapping.setCompositeNodeToCaseMap(choiceCodec, newCodec.getCompositeToCase());
482
483         tryToCreateCasesCodecs(schema);
484
485     }
486
487     @Deprecated
488     private void tryToCreateCasesCodecs(final ChoiceNode schema) {
489         for (ChoiceCaseNode choiceCase : schema.getCases()) {
490             ChoiceCaseNode caseNode = choiceCase;
491             if (caseNode.isAddedByUses()) {
492                 DataSchemaNode origCaseNode = SchemaContextUtil.findOriginal(caseNode, currentSchema);
493                 if (origCaseNode instanceof ChoiceCaseNode) {
494                     caseNode = (ChoiceCaseNode) origCaseNode;
495                 }
496             }
497             SchemaPath path = caseNode.getPath();
498
499             Type type;
500             if (path != null && (type = pathToType.get(path)) != null) {
501                 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
502                 @SuppressWarnings("rawtypes")
503                 ChoiceCaseCodecImpl partialCodec = typeToCaseCodecs.get(typeref);
504                 if (partialCodec.getSchema() == null) {
505                     partialCodec.setSchema(caseNode);
506                 }
507                 try {
508                     Class<?> caseClass = classLoadingStrategy.loadClass(type.getFullyQualifiedName());
509                     getCaseCodecFor(caseClass);
510                 } catch (ClassNotFoundException e) {
511                     LOG.trace("Could not proactivelly create case codec for {}", type, e);
512                 }
513             }
514         }
515
516     }
517
518     @Override
519     public void onValueCodecCreated(final Class<?> valueClass, final Class<?> valueCodec) {
520     }
521
522     @Override
523     public void onCaseCodecCreated(final Class<?> choiceClass,
524             final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
525     }
526
527     @Override
528     public void onDataContainerCodecCreated(final Class<?> dataClass,
529             final Class<? extends BindingCodec<?, ?>> dataCodec) {
530         if (Augmentable.class.isAssignableFrom(dataClass)) {
531             AugmentableDispatchCodec augmentableCodec = getAugmentableCodec(dataClass);
532             CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
533         }
534     }
535
536     public synchronized AugmentableDispatchCodec getAugmentableCodec(final Class<?> dataClass) {
537         AugmentableDispatchCodec ret = augmentableCodecs.get(dataClass);
538         if (ret != null) {
539             return ret;
540         }
541         ret = new AugmentableDispatchCodec(dataClass);
542         augmentableCodecs.put(dataClass, ret);
543         ret.tryToLoadImplementations();
544         return ret;
545     }
546
547     private static abstract class IntermediateCodec<T> implements //
548             DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
549
550         private final BindingCodec<Map<QName, Object>, Object> delegate;
551
552         @Override
553         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
554             return delegate;
555         }
556
557         public IntermediateCodec(final BindingCodec<Map<QName, Object>, Object> delegate) {
558             this.delegate = delegate;
559         }
560
561         @Override
562         public Node<?> serialize(final ValueWithQName<T> input) {
563             Map<QName, Object> intermediateOutput = delegate.serialize(input);
564             return IntermediateMapping.toNode(intermediateOutput);
565         }
566
567     }
568
569     private static class IdentifierCodecImpl<T extends Identifier<?>> //
570             extends IntermediateCodec<T> //
571             implements IdentifierCodec<T> {
572
573         public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
574             super(delegate);
575         }
576
577         @Override
578         public ValueWithQName<T> deserialize(final Node<?> input) {
579             QName qname = input.getNodeType();
580             @SuppressWarnings("unchecked")
581             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
582             return new ValueWithQName<T>(qname, value);
583         }
584
585         @Override
586         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
587             QName qname = input.getNodeType();
588             @SuppressWarnings("unchecked")
589             T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
590             return new ValueWithQName<T>(qname, value);
591         }
592
593         @Override
594         public CompositeNode serialize(final ValueWithQName<T> input) {
595             return (CompositeNode) super.serialize(input);
596         }
597     }
598
599     private static class DataContainerCodecImpl<T extends DataContainer> //
600             extends IntermediateCodec<T> //
601             implements DataContainerCodec<T> {
602
603         public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
604             super(delegate);
605         }
606
607         @Override
608         public ValueWithQName<T> deserialize(final Node<?> input) {
609             if (input == null) {
610                 return null;
611             }
612             QName qname = input.getNodeType();
613             @SuppressWarnings("unchecked")
614             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
615             return new ValueWithQName<T>(qname, value);
616         }
617
618         @Override
619         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
620             if (input == null) {
621                 return null;
622             }
623             QName qname = input.getNodeType();
624             @SuppressWarnings("unchecked")
625             T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
626             return new ValueWithQName<T>(qname, value);
627         }
628
629         @Override
630         public CompositeNode serialize(final ValueWithQName<T> input) {
631             return (CompositeNode) super.serialize(input);
632         }
633     }
634
635     private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
636
637         boolean isApplicable(InstanceIdentifier<?> location);
638
639         public Class<?> getDataType();
640
641     }
642
643     @SuppressWarnings("rawtypes")
644     private abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements BindingCodec {
645
646         private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
647         private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
648
649         protected Map<Class, T> getImplementations() {
650             return implementations;
651         }
652
653         protected void addImplementation(final T implementation) {
654             implementations.put(implementation.getDataType(), implementation);
655         }
656
657         @Override
658         public final Object deserialize(final Object input) {
659             throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
660         }
661
662         @Override
663         public Object serialize(final Object input) {
664             Preconditions.checkArgument(input instanceof DataContainer);
665             Class<? extends DataContainer> inputType = ((DataContainer) input).getImplementedInterface();
666             T implementation = implementations.get(inputType);
667             if (implementation == null) {
668                 implementation = tryToLoadImplementationImpl(inputType);
669             }
670
671             return null;
672         }
673
674         private T tryToLoadImplementationImpl(final Class<? extends DataContainer> inputType) {
675             T implementation = tryToLoadImplementation(inputType);
676             Preconditions.checkArgument(implementation != null, "Data type %s is not supported.", inputType);
677             addImplementation(implementation);
678             return implementation;
679         }
680
681         protected final synchronized void adaptForPath(final InstanceIdentifier<?> path) {
682             if (adaptedForPaths.contains(path)) {
683                 return;
684             }
685             /**
686              * We search in schema context if the use of this location aware
687              * codec (augmentable codec, case codec) makes sense on provided
688              * location (path)
689              *
690              */
691             Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(currentSchema,
692                     path);
693             /**
694              * If context node is present, this codec makes sense on provided
695              * location.
696              *
697              */
698             if (contextNode.isPresent()) {
699                 synchronized (this) {
700                     /**
701                      *
702                      * We adapt (turn on / off) possible implementations of
703                      * child codecs (augmentations, cases) based on this
704                      * location.
705                      *
706                      *
707                      */
708
709                     adaptForPathImpl(path, contextNode.get());
710                     try {
711                         /**
712                          * We trigger serialization of instance identifier, to
713                          * make sure instance identifier codec is aware of
714                          * combination of this path / augmentation / case
715                          */
716                         instanceIdentifierCodec.serialize(path);
717                     } catch (Exception e) {
718                         LOG.warn("Exception during preparation of instance identifier codec for  path {}.", path, e);
719                     }
720                     adaptedForPaths.add(path);
721                 }
722             } else {
723                 LOG.debug("Context node (parent node) not found for {}", path);
724             }
725         }
726
727         protected abstract T tryToLoadImplementation(Class<? extends DataContainer> inputType);
728
729         protected abstract void tryToLoadImplementations();
730
731         protected abstract void adaptForPathImpl(InstanceIdentifier<?> path, DataNodeContainer ctx);
732     }
733
734     @SuppressWarnings("rawtypes")
735     private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
736             Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
737         private boolean augmenting;
738         private boolean uses;
739         private BindingCodec delegate;
740
741         private Set<String> validNames;
742         private Set<QName> validQNames;
743         private ChoiceCaseNode schema;
744         private Set<InstanceIdentifier<?>> applicableLocations;
745
746         @Override
747         public boolean isApplicable(final InstanceIdentifier location) {
748             return applicableLocations.contains(location);
749         }
750
751         public void setSchema(final ChoiceCaseNode caseNode) {
752             this.schema = caseNode;
753             validNames = new HashSet<>();
754             validQNames = new HashSet<>();
755             for (DataSchemaNode node : caseNode.getChildNodes()) {
756                 QName qname = node.getQName();
757                 validQNames.add(qname);
758                 validNames.add(qname.getLocalName());
759             }
760             augmenting = caseNode.isAugmenting();
761             uses = caseNode.isAddedByUses();
762             applicableLocations = new HashSet<>();
763         }
764
765         public ChoiceCaseCodecImpl() {
766             this.delegate = NOT_READY_CODEC;
767         }
768
769         public ChoiceCaseCodecImpl(final ChoiceCaseNode caseNode) {
770             this.delegate = NOT_READY_CODEC;
771             setSchema(caseNode);
772         }
773
774         @Override
775         public ValueWithQName<T> deserialize(final Node<?> input) {
776             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
777         }
778
779         @Override
780         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
781             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
782         }
783
784         @Override
785         public CompositeNode serialize(final ValueWithQName<T> input) {
786             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
787         }
788
789         @Override
790         public BindingCodec getDelegate() {
791             return delegate;
792         }
793
794         public void setDelegate(final BindingCodec delegate) {
795             this.delegate = delegate;
796         }
797
798         public ChoiceCaseNode getSchema() {
799             return schema;
800         }
801
802         @Override
803         public boolean isAcceptable(final Node<?> input) {
804             if (input instanceof CompositeNode) {
805                 if (augmenting && !uses) {
806                     return checkAugmenting((CompositeNode) input);
807                 } else {
808                     return checkLocal((CompositeNode) input);
809                 }
810             }
811             return false;
812         }
813
814         @SuppressWarnings("deprecation")
815         private boolean checkLocal(final CompositeNode input) {
816             QName parent = input.getNodeType();
817             for (Node<?> childNode : input.getChildren()) {
818                 QName child = childNode.getNodeType();
819                 if (!Objects.equals(parent.getNamespace(), child.getNamespace())
820                         || !Objects.equals(parent.getRevision(), child.getRevision())) {
821                     continue;
822                 }
823                 if (validNames.contains(child.getLocalName())) {
824                     return true;
825                 }
826             }
827             return false;
828         }
829
830         @SuppressWarnings("deprecation")
831         private boolean checkAugmenting(final CompositeNode input) {
832             for (Node<?> child : input.getChildren()) {
833                 if (validQNames.contains(child.getNodeType())) {
834                     return true;
835                 }
836             }
837             return false;
838         }
839
840         @Override
841         public Class<?> getDataType() {
842             // TODO Auto-generated method stub
843             throw new UnsupportedOperationException("Not implemented Yet.");
844         }
845     }
846
847     private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>,
848             Delegator<BindingCodec<Map<QName, Object>, Object>> {
849
850         private final BindingCodec<Map<QName, Object>, Object> delegate;
851
852         @SuppressWarnings("rawtypes")
853         private final Map<Class, ChoiceCaseCodecImpl<?>> cases = Collections
854                 .synchronizedMap(new WeakHashMap<Class, ChoiceCaseCodecImpl<?>>());
855
856         private final CaseCompositeNodeMapFacade CompositeToCase;
857
858         public PublicChoiceCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
859             this.delegate = delegate;
860             this.CompositeToCase = new CaseCompositeNodeMapFacade(cases);
861         }
862
863         @Override
864         public ValueWithQName<T> deserialize(final Node<?> input) {
865             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
866         }
867
868         @Override
869         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
870             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
871         }
872
873         @Override
874         public Node<?> serialize(final ValueWithQName<T> input) {
875             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
876         }
877
878         public CaseCompositeNodeMapFacade getCompositeToCase() {
879             return CompositeToCase;
880         }
881
882         @Override
883         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
884             return delegate;
885         }
886
887     }
888
889     @SuppressWarnings("unused")
890     private class DispatchChoiceCodecImpl extends LocationAwareDispatchCodec<ChoiceCaseCodecImpl<?>> {
891
892         @Override
893         public Object deserialize(final Object input,
894                 @SuppressWarnings("rawtypes") final InstanceIdentifier bindingIdentifier) {
895             // TODO Auto-generated method stub
896             return null;
897         }
898
899         @Override
900         public Object serialize(final Object input) {
901             // TODO Auto-generated method stub
902             return null;
903         }
904
905         @Override
906         protected ChoiceCaseCodecImpl<?> tryToLoadImplementation(final Class<? extends DataContainer> inputType) {
907             return getCaseCodecFor(inputType);
908         }
909
910         @Override
911         protected void tryToLoadImplementations() {
912             // TODO Auto-generated method stub
913
914         }
915
916         @Override
917         protected void adaptForPathImpl(final InstanceIdentifier<?> path, final DataNodeContainer ctx) {
918             // TODO Auto-generated method stub
919
920         }
921     }
922
923     @SuppressWarnings("rawtypes")
924     private class CaseClassMapFacade extends MapFacadeBase {
925
926         @Override
927         public Set<Entry<Class, BindingCodec<Object, Object>>> entrySet() {
928             return Collections.emptySet();
929         }
930
931         @Override
932         public BindingCodec get(final Object key) {
933             if (key instanceof Class) {
934                 Class cls = (Class) key;
935                 // bindingClassEncountered(cls);
936                 ChoiceCaseCodecImpl caseCodec = getCaseCodecFor(cls);
937                 return caseCodec.getDelegate();
938             }
939             return null;
940         }
941     }
942
943     @SuppressWarnings("rawtypes")
944     private static class CaseCompositeNodeMapFacade extends MapFacadeBase<CompositeNode> {
945
946         final Map<Class, ChoiceCaseCodecImpl<?>> choiceCases;
947
948         public CaseCompositeNodeMapFacade(final Map<Class, ChoiceCaseCodecImpl<?>> choiceCases) {
949             this.choiceCases = choiceCases;
950         }
951
952         @Override
953         public BindingCodec get(final Object key) {
954             if (!(key instanceof CompositeNode)) {
955                 return null;
956             }
957             for (Entry<Class, ChoiceCaseCodecImpl<?>> entry : choiceCases.entrySet()) {
958                 ChoiceCaseCodecImpl<?> codec = entry.getValue();
959                 if (codec.isAcceptable((CompositeNode) key)) {
960                     return codec.getDelegate();
961                 }
962             }
963             return null;
964         }
965
966     }
967
968     /**
969      * This map is used as only facade for
970      * {@link org.opendaylight.yangtools.yang.binding.BindingCodec} in different
971      * classloaders to retrieve codec dynamicly based on provided key.
972      *
973      * @param <T>
974      *            Key type
975      */
976     @SuppressWarnings("rawtypes")
977     private abstract static class MapFacadeBase<T> implements Map<T, BindingCodec<?, ?>> {
978
979         @Override
980         public boolean containsKey(final Object key) {
981             return get(key) != null;
982         }
983
984         @Override
985         public void clear() {
986             throw notModifiable();
987         }
988
989         @Override
990         public boolean equals(final Object obj) {
991             return super.equals(obj);
992         }
993
994         @Override
995         public BindingCodec remove(final Object key) {
996             return null;
997         }
998
999         @Override
1000         public int size() {
1001             return 0;
1002         }
1003
1004         @Override
1005         public Collection<BindingCodec<?, ?>> values() {
1006             return Collections.emptySet();
1007         }
1008
1009         private UnsupportedOperationException notModifiable() {
1010             return new UnsupportedOperationException("Not externally modifiable.");
1011         }
1012
1013         @Override
1014         public BindingCodec<Map<QName, Object>, Object> put(final T key, final BindingCodec<?, ?> value) {
1015             throw notModifiable();
1016         }
1017
1018         @Override
1019         public void putAll(final Map<? extends T, ? extends BindingCodec<?, ?>> m) {
1020             throw notModifiable();
1021         }
1022
1023         @Override
1024         public int hashCode() {
1025             return super.hashCode();
1026         }
1027
1028         @Override
1029         public boolean isEmpty() {
1030             return true;
1031         }
1032
1033         @Override
1034         public Set<T> keySet() {
1035             return Collections.emptySet();
1036         }
1037
1038         @Override
1039         public Set<Entry<T, BindingCodec<?, ?>>> entrySet() {
1040             return Collections.emptySet();
1041         }
1042
1043         @Override
1044         public boolean containsValue(final Object value) {
1045             return false;
1046         }
1047     }
1048
1049     @SuppressWarnings({ "rawtypes", "unchecked" })
1050     class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
1051
1052         private final Class augmentableType;
1053
1054         public AugmentableDispatchCodec(final Class type) {
1055             Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
1056             augmentableType = type;
1057         }
1058
1059         @Override
1060         // TODO deprecate use without iid
1061         public Object serialize(final Object input) {
1062             if (input instanceof Augmentable<?>) {
1063                 Map<Class, Augmentation> augmentations = getAugmentations(input);
1064                 return serializeImpl(augmentations);
1065             }
1066             return null;
1067         }
1068
1069         private Map<Class, Augmentation> getAugmentations(final Object input) {
1070             Field augmentationField;
1071             try {
1072                 augmentationField = input.getClass().getDeclaredField("augmentation");
1073                 augmentationField.setAccessible(true);
1074                 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
1075                 return augMap;
1076             } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
1077                 LOG.debug("Could not read augmentations for {}", input, e);
1078             }
1079             return Collections.emptyMap();
1080         }
1081
1082         @SuppressWarnings("deprecation")
1083         private List serializeImpl(final Map<Class, Augmentation> input) {
1084             List ret = new ArrayList<>();
1085             for (Entry<Class, Augmentation> entry : input.entrySet()) {
1086                 AugmentationCodec codec = getCodecForAugmentation(entry.getKey());
1087                 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
1088                 ret.addAll(node.getChildren());
1089             }
1090             return ret;
1091         }
1092
1093         @Override
1094         public Map<Class, Augmentation> deserialize(final Object input, final InstanceIdentifier path) {
1095             adaptForPath(path);
1096             Map<Class, Augmentation> ret = new HashMap<>();
1097
1098             if (input instanceof CompositeNode) {
1099                 List<Entry<Class, AugmentationCodecWrapper>> codecs = new ArrayList<>(getImplementations().entrySet());
1100                 for (Entry<Class, AugmentationCodecWrapper> codec : codecs) {
1101                     AugmentationCodec<?> ac = codec.getValue();
1102                     if (ac.isAcceptable(path)) {
1103                         // We add Augmentation Identifier to path, in order to
1104                         // correctly identify children.
1105                         InstanceIdentifier augmentPath = path.builder().augmentation(codec.getKey()).build();
1106                         ValueWithQName<?> value = codec.getValue().deserialize((CompositeNode) input, augmentPath);
1107                         if (value != null && value.getValue() != null) {
1108                             ret.put(codec.getKey(), (Augmentation) value.getValue());
1109                         }
1110                     }
1111                 }
1112             }
1113             return ret;
1114         }
1115
1116         protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
1117             try {
1118                 Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) classLoadingStrategy
1119                         .loadClass(potential);
1120                 return Optional.of(tryToLoadImplementation(clazz));
1121             } catch (ClassNotFoundException e) {
1122                 LOG.warn("Failed to find class for augmentation of {}", potential, e);
1123             }
1124             return Optional.absent();
1125         }
1126
1127         @Override
1128         protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
1129             AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getCodecForAugmentation(inputType);
1130             addImplementation(potentialImpl);
1131             return potentialImpl;
1132         }
1133
1134         @Override
1135         protected void tryToLoadImplementations() {
1136             Type type = referencedType(augmentableType);
1137             Collection<Type> potentialAugmentations;
1138             synchronized (augmentableToAugmentations) {
1139                 potentialAugmentations = new ArrayList(augmentableToAugmentations.get(type));
1140             }
1141             for (Type potential : potentialAugmentations) {
1142                 try {
1143                     tryToLoadImplementation(potential);
1144                 } catch (CodeGenerationException e) {
1145                     LOG.warn("Failed to proactively generate augment code for {}", type, e);
1146                 }
1147             }
1148         }
1149
1150         @Override
1151         protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1152             if (ctxNode instanceof AugmentationTarget) {
1153                 Set<AugmentationSchema> availableAugmentations = ((AugmentationTarget) ctxNode)
1154                         .getAvailableAugmentations();
1155                 if (!availableAugmentations.isEmpty()) {
1156                     updateAugmentationMapping(augTarget, availableAugmentations);
1157                 }
1158             }
1159         }
1160
1161         /**
1162          *
1163          * Adapts augmentation codec for specific provider location (target)
1164          *
1165          * Since augmentation are not forward-referencing and may be discovered
1166          * during runtime, we need to adapt {@link AugmentableDispatchCodec},
1167          * {@link AugmentationCodecWrapper} and {@link InstanceIdentifierCodec}
1168          * for this newly discovered location where augmentation may be used.
1169          *
1170          * Adaptation consists of:
1171          * <ol>
1172          * <li> scan of available (valid) augmentations for
1173          * current location
1174          * <li>lookup for Java classes derived from this augmentations
1175          * <li>generation of missing codecs
1176          * <li>updating Augmentation codecs to work with new location
1177          * <li>updating Instance Identifier to work with new location
1178          *
1179          */
1180         private void updateAugmentationMapping(final InstanceIdentifier<?> augTarget,
1181                 final Set<AugmentationSchema> availableAugmentations) {
1182             for (AugmentationSchema aug : availableAugmentations) {
1183
1184                 Type potentialType = getTypeForAugmentation(aug);
1185                 if (potentialType != null) {
1186                     Optional<AugmentationCodecWrapper> potentialImpl = tryToLoadImplementation(potentialType);
1187                     if (potentialImpl.isPresent()) {
1188                         potentialImpl.get().addApplicableFor(augTarget, aug);
1189                         Class augType = potentialImpl.get().getDataType();
1190                         InstanceIdentifier augPath = augTarget.augmentation(augType);
1191                         try {
1192
1193                             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = getInstanceIdentifierCodec().serialize(augPath);
1194                             if(domPath == null) {
1195                                 LOG.error("Unable to serialize instance identifier for {}",augPath);
1196                             }
1197                         } catch (Exception e) {
1198                             LOG.error("Unable to serialize instance identifiers for {}",augPath,e);
1199                         }
1200
1201                     }
1202                 } else {
1203                     // Omits warning for empty augmentations since they are not represented in data
1204                     if(!aug.getChildNodes().isEmpty()) {
1205                         LOG.warn("Could not find generated type for augmentation {} with children {}", aug,
1206                             aug.getChildNodes());
1207                     }
1208                 }
1209             }
1210         }
1211
1212
1213
1214         private Type getTypeForAugmentation(final AugmentationSchema aug) {
1215             Optional<AugmentationSchema> currentAug = Optional.of(aug);
1216             while (currentAug.isPresent()) {
1217                 Type potentialType = typeToAugment.inverse().get(currentAug.get());
1218                 if (potentialType != null) {
1219                     return potentialType;
1220                 }
1221                 currentAug = currentAug.get().getOriginalDefinition();
1222             }
1223             return null;
1224         }
1225     }
1226
1227     @SuppressWarnings({ "rawtypes", "unchecked" })
1228     private static class LateMixinCodec implements BindingCodec, Delegator<BindingCodec> {
1229
1230         private BindingCodec delegate;
1231
1232         @Override
1233         public BindingCodec getDelegate() {
1234             if (delegate == null) {
1235                 throw new IllegalStateException("Codec not initialized yet.");
1236             }
1237             return delegate;
1238         }
1239
1240         @Override
1241         public Object deserialize(final Object input) {
1242             return getDelegate().deserialize(input);
1243         }
1244
1245         @Override
1246         public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
1247             return getDelegate().deserialize(input, bindingIdentifier);
1248         }
1249
1250         @Override
1251         public Object serialize(final Object input) {
1252             return getDelegate().serialize(input);
1253         }
1254
1255     }
1256
1257     @SuppressWarnings("rawtypes")
1258     private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
1259             Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
1260
1261         private final BindingCodec delegate;
1262         private final QName augmentationQName;
1263         private final Multimap<InstanceIdentifier<?>, QName> validAugmentationTargets;
1264         private final Class<?> augmentationType;
1265
1266         public AugmentationCodecWrapper(final BindingCodec<Map<QName, Object>, Object> rawCodec, final Class<?> dataType) {
1267             this.delegate = rawCodec;
1268             this.augmentationType = dataType;
1269             this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
1270             this.validAugmentationTargets = Multimaps.synchronizedSetMultimap(HashMultimap
1271                     .<InstanceIdentifier<?>, QName> create());
1272         }
1273
1274         public void addApplicableFor(final InstanceIdentifier<?> path, final AugmentationSchema aug) {
1275             for (DataSchemaNode child : aug.getChildNodes()) {
1276                 validAugmentationTargets.put(path, child.getQName());
1277             }
1278         }
1279
1280         @Override
1281         public BindingCodec getDelegate() {
1282             return delegate;
1283         }
1284
1285         @Override
1286         public CompositeNode serialize(final ValueWithQName<T> input) {
1287             @SuppressWarnings("unchecked")
1288             List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
1289             List<Node<?>> serialized = new ArrayList<>(rawValues.size());
1290             for (Map<QName, Object> val : rawValues) {
1291                 serialized.add(IntermediateMapping.toNode(val));
1292             }
1293             return new CompositeNodeTOImpl(input.getQname(), null, serialized);
1294         }
1295
1296         @Override
1297         @SuppressWarnings("unchecked")
1298         public ValueWithQName<T> deserialize(final Node<?> input) {
1299             Object rawCodecValue = getDelegate().deserialize(input);
1300             return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1301         }
1302
1303         @Override
1304         @SuppressWarnings("unchecked")
1305         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
1306             // if (!isAcceptable(bindingIdentifier)) {
1307             // return null;
1308             // }
1309             Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
1310             return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1311         }
1312
1313         @Override
1314         public QName getAugmentationQName() {
1315             return augmentationQName;
1316         }
1317
1318         @Override
1319         public boolean isAcceptable(final InstanceIdentifier<?> path) {
1320             if (path == null) {
1321                 return false;
1322             }
1323             return validAugmentationTargets.containsKey(path);
1324         }
1325
1326         @Override
1327         public boolean isApplicable(final InstanceIdentifier location) {
1328             return isAcceptable(location);
1329         }
1330
1331         @Override
1332         public Class<?> getDataType() {
1333             return augmentationType;
1334         }
1335     }
1336
1337     @SuppressWarnings("rawtypes")
1338     private class IdentityCompositeCodec implements IdentityCodec {
1339
1340         @Override
1341         public Object deserialize(final Object input) {
1342             Preconditions.checkArgument(input instanceof QName);
1343             return deserialize((QName) input);
1344         }
1345
1346         @Override
1347         public Class<?> deserialize(final QName input) {
1348             Type type = qnamesToIdentityMap.get(input);
1349             if (type == null) {
1350                 return null;
1351             }
1352             ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1353             WeakReference<Class> softref = typeToClass.get(typeref);
1354             if (softref == null) {
1355
1356                 try {
1357                     Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1358                     if (cls != null) {
1359                         serialize(cls);
1360                         return cls;
1361                     }
1362                 } catch (Exception e) {
1363                     LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1364                             typeref.getFullyQualifiedName());
1365                 }
1366                 return null;
1367             }
1368             return softref.get();
1369         }
1370
1371         @Override
1372         public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
1373             Type type = qnamesToIdentityMap.get(input);
1374             if (type == null) {
1375                 return null;
1376             }
1377             ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1378             WeakReference<Class> softref = typeToClass.get(typeref);
1379             if (softref == null) {
1380
1381                 try {
1382                     Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1383                     if (cls != null) {
1384                         serialize(cls);
1385                         return cls;
1386                     }
1387                 } catch (Exception e) {
1388                     LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1389                             typeref.getFullyQualifiedName());
1390                 }
1391                 return null;
1392             }
1393             return softref.get();
1394         }
1395
1396         @Override
1397         public QName serialize(final Class input) {
1398             Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
1399             bindingClassEncountered(input);
1400             QName qname = identityQNames.get(input);
1401             if (qname != null) {
1402                 return qname;
1403             }
1404             ConcreteType typeref = Types.typeForClass(input);
1405             qname = typeToQname.get(typeref);
1406             if (qname != null) {
1407                 identityQNames.put(input, qname);
1408             }
1409             return qname;
1410         }
1411
1412         @Override
1413         public Object serialize(final Object input) {
1414             Preconditions.checkArgument(input instanceof Class);
1415             return serialize((Class) input);
1416         }
1417
1418     }
1419
1420     private static final Type referencedType(final Class<?> augmentableType) {
1421         return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());
1422     }
1423 }