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