Rename LeafNodeCodecContext to ValueNodeCodecContext
[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, ValueNodeCodecContext> 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 ValueNodeCodecContext 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     @Override
333     public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
334         final NodeContextSupplier childSupplier;
335         if (arg instanceof NodeIdentifierWithPredicates) {
336             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
337         } else if (arg instanceof AugmentationIdentifier) {
338             childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
339         } else {
340             childSupplier = byYang.get(arg);
341         }
342
343         return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
344     }
345
346     protected final ValueNodeCodecContext getLeafChild(final String name) {
347         final ValueNodeCodecContext value = leafChild.get(name);
348         return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
349     }
350
351     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
352         final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
353         // Direct instantiation or use in same module in which grouping
354         // was defined.
355         DataSchemaNode sameName;
356         try {
357             sameName = getSchema().getDataChildByName(origDef.getQName());
358         } catch (final IllegalArgumentException e) {
359             sameName = null;
360         }
361         final DataSchemaNode childSchema;
362         if (sameName != null) {
363             // Exactly same schema node
364             if (origDef.equals(sameName)) {
365                 childSchema = sameName;
366                 // We check if instantiated node was added via uses
367                 // statement and is instantiation of same grouping
368             } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
369                 childSchema = sameName;
370             } else {
371                 // Node has same name, but clearly is different
372                 childSchema = null;
373             }
374         } else {
375             // We are looking for instantiation via uses in other module
376             final QName instantiedName = origDef.getQName().withModule(namespace());
377             final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
378             // We check if it is really instantiated from same
379             // definition as class was derived
380             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
381                 childSchema = potential;
382             } else {
383                 childSchema = null;
384             }
385         }
386         final DataSchemaNode nonNullChild =
387                 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
388         return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
389     }
390
391     @SuppressWarnings("unchecked")
392     Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
393         return Item.of((Class<? extends DataObject>) childClass);
394     }
395
396     private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
397         final DataContainerCodecPrototype<?> firstTry = augmentations.byYang.get(arg);
398         if (firstTry != null) {
399             return firstTry;
400         }
401         if (possibleAugmentations.containsKey(arg)) {
402             // Try to load augmentations, which will potentially update knownAugmentations, hence we re-load that field
403             // again.
404             reloadAllAugmentations();
405             return augmentations.byYang.get(arg);
406         }
407         return null;
408     }
409
410     private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
411         DataContainerCodecPrototype<?> lookup = augmentationByClassOrEquivalentClass(childClass);
412         if (lookup != null || !isPotentialAugmentation(childClass)) {
413             return lookup;
414         }
415
416         // Attempt to reload all augmentations using TCCL and lookup again
417         reloadAllAugmentations();
418         lookup = augmentationByClassOrEquivalentClass(childClass);
419         if (lookup != null) {
420             return lookup;
421         }
422
423         // Still no result, this can be caused by TCCL not being set up properly -- try the class's ClassLoader
424         // if it is present;
425         final ClassLoader loader = childClass.getClassLoader();
426         if (loader == null) {
427             return null;
428         }
429
430         LOG.debug("Class {} not loaded via TCCL, attempting to recover", childClass);
431         ClassLoaderUtils.runWithClassLoader(loader, this::reloadAllAugmentations);
432         return augmentationByClassOrEquivalentClass(childClass);
433     }
434
435     private boolean isPotentialAugmentation(final Class<?> childClass) {
436         final JavaTypeName name = JavaTypeName.create(childClass);
437         for (Type type : possibleAugmentations.values()) {
438             if (name.equals(type.getIdentifier())) {
439                 return true;
440             }
441         }
442         return false;
443     }
444
445     private @Nullable DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(
446             final @NonNull Class<?> childClass) {
447         // Perform a single load, so we can reuse it if we end up going to the reflection-based slow path
448         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local = augmentations.byStream;
449         final DataContainerCodecPrototype<?> childProto = local.get(childClass);
450         if (childProto != null) {
451             return childProto;
452         }
453
454         /*
455          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
456          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
457          * we'll cache it so we do not need to perform reflection operations again.
458          */
459         final DataContainerCodecPrototype<?> mismatched = mismatchedAugmented.get(childClass);
460         if (mismatched != null) {
461             return mismatched;
462         }
463
464         @SuppressWarnings("rawtypes")
465         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
466         if (getBindingClass().equals(augTarget)) {
467             for (final DataContainerCodecPrototype<?> realChild : local.values()) {
468                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
469                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
470                     return cacheMismatched(childClass, realChild);
471                 }
472             }
473         }
474         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
475         return null;
476     }
477
478     private synchronized DataContainerCodecPrototype<?> cacheMismatched(final Class<?> childClass,
479             final DataContainerCodecPrototype<?> prototype) {
480         // Original access was unsynchronized, we need to perform additional checking
481         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local = mismatchedAugmented;
482         final DataContainerCodecPrototype<?> existing = local.get(childClass);
483         if (existing != null) {
484             return existing;
485         }
486
487         final Builder<Class<?>, DataContainerCodecPrototype<?>> builder = ImmutableMap.builderWithExpectedSize(
488             local.size() + 1);
489         builder.putAll(local);
490         builder.put(childClass, prototype);
491
492         mismatchedAugmented = builder.build();
493         LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
494         return prototype;
495     }
496
497     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
498         final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
499         @SuppressWarnings("rawtypes")
500         final Class augClass;
501         try {
502             augClass = loader.loadClass(value);
503         } catch (final ClassNotFoundException e) {
504             LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
505             return null;
506         }
507
508         @SuppressWarnings("unchecked")
509         final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
510                 .getResolvedAugmentationSchema(getSchema(), augClass);
511         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
512     }
513
514     // Unlike BindingMapping.getGetterMethodForNonnull() this returns an interned String
515     @NonNull String getterNameForNonnullName(final String nonnullMethod) {
516         return verifyNotNull(nonnullToGetter.get(nonnullMethod), "Failed to look up getter method for %s",
517             nonnullMethod);
518     }
519
520     @SuppressWarnings("rawtypes")
521     @Nullable Object getBindingChildValue(final String method, final NormalizedNodeContainer domData) {
522         final NodeCodecContext childContext = verifyNotNull(byMethod.get(method),
523             "Cannot find data handler for method %s", method).get();
524
525         @SuppressWarnings("unchecked")
526         final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
527
528         // We do not want to use Optional.map() here because we do not want to invoke defaultObject() when we have
529         // normal value because defaultObject() may end up throwing an exception intentionally.
530         return domChild.isPresent() ? childContext.deserializeObject(domChild.get()) : childContext.defaultObject();
531     }
532
533     @SuppressWarnings("checkstyle:illegalCatch")
534     protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
535         try {
536             return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
537         } catch (final Throwable e) {
538             Throwables.throwIfUnchecked(e);
539             throw new IllegalStateException(e);
540         }
541     }
542
543     @SuppressWarnings("unchecked")
544     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
545             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
546
547         @SuppressWarnings("rawtypes")
548         final Map map = new HashMap<>();
549
550         for (final NormalizedNode<?, ?> childValue : data.getValue()) {
551             if (childValue instanceof AugmentationNode) {
552                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
553                 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
554                 if (codecProto != null) {
555                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
556                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
557                 }
558             }
559         }
560         for (final DataContainerCodecPrototype<?> value : augmentations.byStream.values()) {
561             final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
562             if (augData.isPresent()) {
563                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
564             }
565         }
566         return map;
567     }
568
569     final Method[] propertyMethods() {
570         return propertyMethods;
571     }
572
573     @Override
574     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
575         checkArgument(getDomPathArgument().equals(arg));
576         return bindingArg();
577     }
578
579     @Override
580     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
581         checkArgument(bindingArg().equals(arg));
582         return getDomPathArgument();
583     }
584 }