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