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