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