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