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