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