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