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