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