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