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