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