Cache NodeContextSuppliers in CodecDataObject
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / DataObjectCodecContext.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.mdsal.binding.dom.codec.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.base.Throwables;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableMap.Builder;
18 import java.io.IOException;
19 import java.lang.invoke.MethodHandle;
20 import java.lang.invoke.MethodHandles;
21 import java.lang.invoke.MethodType;
22 import java.lang.reflect.Method;
23 import java.util.Arrays;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
32 import javassist.CannotCompileException;
33 import javassist.CtClass;
34 import javassist.NotFoundException;
35 import org.eclipse.jdt.annotation.NonNull;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.opendaylight.mdsal.binding.dom.codec.loader.StaticClassPool;
38 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
39 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
40 import org.opendaylight.mdsal.binding.model.api.Type;
41 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
42 import org.opendaylight.yangtools.concepts.Immutable;
43 import org.opendaylight.yangtools.util.ClassLoaderUtils;
44 import org.opendaylight.yangtools.yang.binding.Augmentable;
45 import org.opendaylight.yangtools.yang.binding.Augmentation;
46 import org.opendaylight.yangtools.yang.binding.DataObject;
47 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
48 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
49 import org.opendaylight.yangtools.yang.binding.OpaqueObject;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
56 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
61 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
63 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
68         extends DataContainerCodecContext<D, T> {
69     private static final class Augmentations implements Immutable {
70         final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYang;
71         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStream;
72
73         Augmentations(final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYang,
74             final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStream) {
75             this.byYang = requireNonNull(byYang);
76             this.byStream = requireNonNull(byStream);
77         }
78     }
79
80     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
81     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, NormalizedNodeContainer.class);
82     private static final MethodType AUGMENTABLE_CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
83         DataObjectCodecContext.class, NormalizedNodeContainer.class);
84     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
85         NormalizedNodeContainer.class);
86     private static final MethodType AUGMENTABLE_DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
87         DataObjectCodecContext.class, NormalizedNodeContainer.class);
88     private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
89     private static final Augmentations EMPTY_AUGMENTATIONS = new Augmentations(ImmutableMap.of(), ImmutableMap.of());
90     private static final CtClass SUPERCLASS = StaticClassPool.findClass(CodecDataObject.class);
91     private static final CtClass AUGMENTABLE_SUPERCLASS = StaticClassPool.findClass(
92         AugmentableCodecDataObject.class);
93
94     private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
95     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
96     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
97     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
98     private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
99     private final MethodHandle proxyConstructor;
100
101     @SuppressWarnings("rawtypes")
102     private static final AtomicReferenceFieldUpdater<DataObjectCodecContext, Augmentations>
103         AUGMENTATIONS_UPDATER = AtomicReferenceFieldUpdater.newUpdater(DataObjectCodecContext.class,
104             Augmentations.class, "augmentations");
105     private volatile Augmentations augmentations = EMPTY_AUGMENTATIONS;
106
107     private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
108
109     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
110         this(prototype, null);
111     }
112
113     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype,
114             final Entry<Method, IdentifiableItemCodec> keyMethod) {
115         super(prototype);
116
117         final Class<D> bindingClass = getBindingClass();
118         this.leafChild = factory().getLeafNodes(bindingClass, getSchema());
119
120         final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
121
122         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
123         final Map<Method, NodeContextSupplier> tmpMethodToSupplier = new HashMap<>();
124         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
125         final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
126
127         // Adds leaves to mapping
128         for (final ValueNodeCodecContext leaf : leafChild.values()) {
129             tmpMethodToSupplier.put(leaf.getGetter(), leaf);
130             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
131         }
132
133         for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
134             final Method method = childDataObj.getValue();
135             verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
136
137             final Class<?> retClass = childDataObj.getKey();
138             if (OpaqueObject.class.isAssignableFrom(retClass)) {
139                 // Filter OpaqueObjects, they are not containers
140                 continue;
141             }
142
143             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(retClass);
144             tmpMethodToSupplier.put(method, childProto);
145             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
146             byYangBuilder.put(childProto.getYangArg(), childProto);
147             if (childProto.isChoice()) {
148                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
149                 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
150                     byBindingArgClassBuilder.put(cazeChild, childProto);
151                 }
152             }
153         }
154
155         // Make sure properties are alpha-sorted
156         final Method[] properties = tmpMethodToSupplier.keySet().toArray(new Method[0]);
157         Arrays.sort(properties, METHOD_BY_ALPHABET);
158         final Builder<Method, NodeContextSupplier> propBuilder = ImmutableMap.builderWithExpectedSize(
159             properties.length);
160         for (Method prop : properties) {
161             propBuilder.put(prop, verifyNotNull(tmpMethodToSupplier.get(prop)));
162         }
163
164         this.byYang = ImmutableMap.copyOf(byYangBuilder);
165         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
166         byBindingArgClassBuilder.putAll(byStreamClass);
167         this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
168
169         final CtClass superClass;
170         final MethodType ctorType;
171         if (Augmentable.class.isAssignableFrom(bindingClass)) {
172             this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
173             superClass = AUGMENTABLE_SUPERCLASS;
174             ctorType = AUGMENTABLE_CONSTRUCTOR_TYPE;
175         } else {
176             this.possibleAugmentations = ImmutableMap.of();
177             superClass = SUPERCLASS;
178             ctorType = CONSTRUCTOR_TYPE;
179         }
180         reloadAllAugmentations();
181
182         final Class<?> generatedClass;
183         try {
184             generatedClass = prototype.getFactory().getLoader().generateSubclass(superClass, bindingClass, "codecImpl",
185                 new CodecDataObjectCustomizer(propBuilder.build(), keyMethod));
186         } catch (CannotCompileException | IOException | NotFoundException e) {
187             throw new LinkageError("Failed to generated class for " + bindingClass, e);
188         }
189
190         final MethodHandle ctor;
191         try {
192             ctor = MethodHandles.publicLookup().findConstructor(generatedClass, ctorType);
193         } catch (NoSuchMethodException | IllegalAccessException e) {
194             throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
195         }
196
197         if (Augmentable.class.isAssignableFrom(bindingClass)) {
198             proxyConstructor = ctor.asType(AUGMENTABLE_DATAOBJECT_TYPE).bindTo(this);
199         } else {
200             proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
201         }
202     }
203
204     // This method could be synchronized, but that would mean that concurrent attempts to load an invalid augmentation
205     // would end up being unnecessarily contended -- blocking real progress and not being able to run concurrently
206     // while producing no effect. We therefore use optimistic read + CAS.
207     private void reloadAllAugmentations() {
208         // Load current values
209         Augmentations oldAugmentations = augmentations;
210
211         // FIXME: can we detect when we have both maps fully populated and skip all of this?
212
213         // Scratch space for additions
214         final Map<PathArgument, DataContainerCodecPrototype<?>> addByYang = new HashMap<>();
215         final Map<Class<?>, DataContainerCodecPrototype<?>> addByStream = new HashMap<>();
216
217         // Iterate over all possibilities, checking for modifications.
218         for (final Type augment : possibleAugmentations.values()) {
219             final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
220             if (augProto != null) {
221                 final PathArgument yangArg = augProto.getYangArg();
222                 final Class<?> bindingClass = augProto.getBindingClass();
223                 if (!oldAugmentations.byYang.containsKey(yangArg)) {
224                     if (addByYang.putIfAbsent(yangArg, augProto) == null) {
225                         LOG.trace("Discovered new YANG mapping {} -> {} in {}", yangArg, augProto, this);
226                     }
227                 }
228                 if (!oldAugmentations.byStream.containsKey(bindingClass)) {
229                     if (addByStream.putIfAbsent(bindingClass, augProto) == null) {
230                         LOG.trace("Discovered new class mapping {} -> {} in {}", bindingClass, augProto, this);
231                     }
232                 }
233             }
234         }
235
236         while (true) {
237             if (addByYang.isEmpty() && addByStream.isEmpty()) {
238                 LOG.trace("No new augmentations discovered in {}", this);
239                 return;
240             }
241
242             // We have some additions, propagate them out
243             final Augmentations newAugmentations = new Augmentations(concatMaps(oldAugmentations.byYang, addByYang),
244                 concatMaps(oldAugmentations.byStream, addByStream));
245             if (AUGMENTATIONS_UPDATER.compareAndSet(this, oldAugmentations, newAugmentations)) {
246                 // Success, we are done
247                 return;
248             }
249
250             // We have raced installing new augmentations, read them again, remove everything present in the installed
251             // once and try again. This may mean that we end up not doing anything, but that's fine.
252             oldAugmentations = augmentations;
253
254             // We could use Map.removeAll(oldAugmentations.byYang.keySet()), but that forces the augmentation's keyset
255             // to be materialized, which we otherwise do not need. Hence we do this the other way around, instantiating
256             // our temporary maps' keySets and iterating over them. That's fine as we'll be throwing those maps away.
257             removeMapKeys(addByYang, oldAugmentations.byYang);
258             removeMapKeys(addByStream, oldAugmentations.byStream);
259         }
260     }
261
262     private static <K, V> ImmutableMap<K, V> concatMaps(final ImmutableMap<K, V> old, final Map<K, V> add) {
263         if (add.isEmpty()) {
264             return old;
265         }
266
267         final Builder<K, V> builder = ImmutableMap.builderWithExpectedSize(old.size() + add.size());
268         builder.putAll(old);
269         builder.putAll(add);
270         return builder.build();
271     }
272
273     private static <K, V> void removeMapKeys(final Map<K, V> removeFrom, final ImmutableMap<K, V> map) {
274         final Iterator<K> it = removeFrom.keySet().iterator();
275         while (it.hasNext()) {
276             if (map.containsKey(it.next())) {
277                 it.remove();
278             }
279         }
280     }
281
282     @SuppressWarnings("unchecked")
283     @Override
284     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
285         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
286         return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
287                 childClass).get();
288     }
289
290     private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
291         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
292         if (childProto != null) {
293             return childProto;
294         }
295         if (Augmentation.class.isAssignableFrom(childClass)) {
296             return augmentationByClass(childClass);
297         }
298         return null;
299     }
300
301     @SuppressWarnings("unchecked")
302     @Override
303     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
304             final Class<C> childClass) {
305         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
306         if (childProto != null) {
307             return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
308         }
309         return Optional.empty();
310     }
311
312     @Override
313     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
314             final List<YangInstanceIdentifier.PathArgument> builder) {
315
316         final Class<? extends DataObject> argType = arg.getType();
317         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
318         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
319             ctxProto = augmentationByClass(argType);
320         }
321         final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
322             "Class %s is not valid child of %s", argType, getBindingClass()).get();
323         if (context instanceof ChoiceNodeCodecContext) {
324             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
325             choice.addYangPathArgument(arg, builder);
326
327             final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
328             final Class<? extends DataObject> type = arg.getType();
329             final DataContainerCodecContext<?, ?> caze;
330             if (caseType.isPresent()) {
331                 // Non-ambiguous addressing this should not pose any problems
332                 caze = choice.streamChild(caseType.get());
333             } else {
334                 caze = choice.getCaseByChildClass(type);
335             }
336
337             caze.addYangPathArgument(arg, builder);
338             return caze.bindingPathArgumentChild(arg, builder);
339         }
340         context.addYangPathArgument(arg, builder);
341         return context;
342     }
343
344     @Override
345     public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
346         final NodeContextSupplier childSupplier;
347         if (arg instanceof NodeIdentifierWithPredicates) {
348             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
349         } else if (arg instanceof AugmentationIdentifier) {
350             childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
351         } else {
352             childSupplier = byYang.get(arg);
353         }
354
355         return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
356     }
357
358     protected final ValueNodeCodecContext getLeafChild(final String name) {
359         final ValueNodeCodecContext value = leafChild.get(name);
360         return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
361     }
362
363     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
364         final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
365         // Direct instantiation or use in same module in which grouping
366         // was defined.
367         DataSchemaNode sameName;
368         try {
369             sameName = getSchema().getDataChildByName(origDef.getQName());
370         } catch (final IllegalArgumentException e) {
371             sameName = null;
372         }
373         final DataSchemaNode childSchema;
374         if (sameName != null) {
375             // Exactly same schema node
376             if (origDef.equals(sameName)) {
377                 childSchema = sameName;
378                 // We check if instantiated node was added via uses
379                 // statement and is instantiation of same grouping
380             } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
381                 childSchema = sameName;
382             } else {
383                 // Node has same name, but clearly is different
384                 childSchema = null;
385             }
386         } else {
387             // We are looking for instantiation via uses in other module
388             final QName instantiedName = origDef.getQName().withModule(namespace());
389             final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
390             // We check if it is really instantiated from same
391             // definition as class was derived
392             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
393                 childSchema = potential;
394             } else {
395                 childSchema = null;
396             }
397         }
398         final DataSchemaNode nonNullChild =
399                 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
400         return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
401     }
402
403     @SuppressWarnings("unchecked")
404     Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
405         return Item.of((Class<? extends DataObject>) childClass);
406     }
407
408     private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
409         final DataContainerCodecPrototype<?> firstTry = augmentations.byYang.get(arg);
410         if (firstTry != null) {
411             return firstTry;
412         }
413         if (possibleAugmentations.containsKey(arg)) {
414             // Try to load augmentations, which will potentially update knownAugmentations, hence we re-load that field
415             // again.
416             reloadAllAugmentations();
417             return augmentations.byYang.get(arg);
418         }
419         return null;
420     }
421
422     private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
423         DataContainerCodecPrototype<?> lookup = augmentationByClassOrEquivalentClass(childClass);
424         if (lookup != null || !isPotentialAugmentation(childClass)) {
425             return lookup;
426         }
427
428         // Attempt to reload all augmentations using TCCL and lookup again
429         reloadAllAugmentations();
430         lookup = augmentationByClassOrEquivalentClass(childClass);
431         if (lookup != null) {
432             return lookup;
433         }
434
435         // Still no result, this can be caused by TCCL not being set up properly -- try the class's ClassLoader
436         // if it is present;
437         final ClassLoader loader = childClass.getClassLoader();
438         if (loader == null) {
439             return null;
440         }
441
442         LOG.debug("Class {} not loaded via TCCL, attempting to recover", childClass);
443         ClassLoaderUtils.runWithClassLoader(loader, this::reloadAllAugmentations);
444         return augmentationByClassOrEquivalentClass(childClass);
445     }
446
447     private boolean isPotentialAugmentation(final Class<?> childClass) {
448         final JavaTypeName name = JavaTypeName.create(childClass);
449         for (Type type : possibleAugmentations.values()) {
450             if (name.equals(type.getIdentifier())) {
451                 return true;
452             }
453         }
454         return false;
455     }
456
457     private @Nullable DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(
458             final @NonNull Class<?> childClass) {
459         // Perform a single load, so we can reuse it if we end up going to the reflection-based slow path
460         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local = augmentations.byStream;
461         final DataContainerCodecPrototype<?> childProto = local.get(childClass);
462         if (childProto != null) {
463             return childProto;
464         }
465
466         /*
467          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
468          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
469          * we'll cache it so we do not need to perform reflection operations again.
470          */
471         final DataContainerCodecPrototype<?> mismatched = mismatchedAugmented.get(childClass);
472         if (mismatched != null) {
473             return mismatched;
474         }
475
476         @SuppressWarnings("rawtypes")
477         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
478         if (getBindingClass().equals(augTarget)) {
479             for (final DataContainerCodecPrototype<?> realChild : local.values()) {
480                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
481                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
482                     return cacheMismatched(childClass, realChild);
483                 }
484             }
485         }
486         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
487         return null;
488     }
489
490     private synchronized DataContainerCodecPrototype<?> cacheMismatched(final Class<?> childClass,
491             final DataContainerCodecPrototype<?> prototype) {
492         // Original access was unsynchronized, we need to perform additional checking
493         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local = mismatchedAugmented;
494         final DataContainerCodecPrototype<?> existing = local.get(childClass);
495         if (existing != null) {
496             return existing;
497         }
498
499         final Builder<Class<?>, DataContainerCodecPrototype<?>> builder = ImmutableMap.builderWithExpectedSize(
500             local.size() + 1);
501         builder.putAll(local);
502         builder.put(childClass, prototype);
503
504         mismatchedAugmented = builder.build();
505         LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
506         return prototype;
507     }
508
509     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
510         final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
511         @SuppressWarnings("rawtypes")
512         final Class augClass;
513         try {
514             augClass = loader.loadClass(value);
515         } catch (final ClassNotFoundException e) {
516             LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
517             return null;
518         }
519
520         @SuppressWarnings("unchecked")
521         final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
522                 .getResolvedAugmentationSchema(getSchema(), augClass);
523         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
524     }
525
526     @SuppressWarnings("checkstyle:illegalCatch")
527     protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
528         try {
529             return (D) proxyConstructor.invokeExact(node);
530         } catch (final Throwable e) {
531             Throwables.throwIfUnchecked(e);
532             throw new IllegalStateException(e);
533         }
534     }
535
536     @SuppressWarnings("unchecked")
537     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
538             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
539
540         @SuppressWarnings("rawtypes")
541         final Map map = new HashMap<>();
542
543         for (final NormalizedNode<?, ?> childValue : data.getValue()) {
544             if (childValue instanceof AugmentationNode) {
545                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
546                 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
547                 if (codecProto != null) {
548                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
549                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
550                 }
551             }
552         }
553         for (final DataContainerCodecPrototype<?> value : augmentations.byStream.values()) {
554             final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
555             if (augData.isPresent()) {
556                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
557             }
558         }
559         return map;
560     }
561
562     @Override
563     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
564         checkArgument(getDomPathArgument().equals(arg));
565         return bindingArg();
566     }
567
568     @Override
569     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
570         checkArgument(bindingArg().equals(arg));
571         return getDomPathArgument();
572     }
573 }