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