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