ad0bbaa36bb682ae18a3f2d5c8d11cc345af3220
[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
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableSortedMap;
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.lang.invoke.MethodHandle;
20 import java.lang.invoke.MethodHandles;
21 import java.lang.invoke.MethodType;
22 import java.lang.reflect.InvocationHandler;
23 import java.lang.reflect.Method;
24 import java.lang.reflect.Proxy;
25 import java.util.Collection;
26 import java.util.Comparator;
27 import java.util.HashMap;
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.SortedMap;
33 import java.util.TreeMap;
34 import java.util.concurrent.ConcurrentHashMap;
35 import java.util.concurrent.ConcurrentMap;
36 import java.util.function.Function;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.Nullable;
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.util.ClassLoaderUtils;
44 import org.opendaylight.yangtools.yang.binding.Augmentable;
45 import org.opendaylight.yangtools.yang.binding.Augmentation;
46 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
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.common.QName;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
56 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
61 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
63 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
68         extends DataContainerCodecContext<D, T> {
69     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
70     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
71     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
72     private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
73
74     private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
75     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
76     private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
77     private final ImmutableMap<Method, NodeContextSupplier> nonnullMethods;
78     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
79     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
80     private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
81     private final MethodHandle proxyConstructor;
82
83     private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
84             new ConcurrentHashMap<>();
85     private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
86
87     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
88         super(prototype);
89
90         final Class<D> bindingClass = getBindingClass();
91         this.leafChild = factory().getLeafNodes(bindingClass, getSchema());
92
93         final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
94
95         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
96         final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
97         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
98         final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
99
100         // Adds leaves to mapping
101         for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
102             byMethodBuilder.put(leaf.getGetter(), leaf);
103             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
104         }
105
106         for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
107             final Method method = childDataObj.getValue();
108             verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
109             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
110             byMethodBuilder.put(method, childProto);
111             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
112             byYangBuilder.put(childProto.getYangArg(), childProto);
113             if (childProto.isChoice()) {
114                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
115                 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
116                     byBindingArgClassBuilder.put(cazeChild, childProto);
117                 }
118             }
119         }
120         this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
121         this.byYang = ImmutableMap.copyOf(byYangBuilder);
122         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
123         byBindingArgClassBuilder.putAll(byStreamClass);
124         this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
125
126         final Map<Class<?>, Method> clsToNonnull = BindingReflections.getChildrenClassToNonnullMethod(bindingClass);
127         final Map<Method, NodeContextSupplier> nonnullMethodsBuilder = new HashMap<>();
128         for (final Entry<Class<?>, Method> entry : clsToNonnull.entrySet()) {
129             final Method method = entry.getValue();
130             if (!method.isDefault()) {
131                 LOG.warn("Ignoring non-default method {} in {}", method, bindingClass);
132                 continue;
133             }
134             final DataContainerCodecPrototype<?> supplier = byStreamClass.get(entry.getKey());
135             if (supplier != null) {
136                 nonnullMethodsBuilder.put(method, supplier);
137             } else {
138                 LOG.warn("Failed to look up data handler for method {}", method);
139             }
140         }
141
142         nonnullMethods = ImmutableMap.copyOf(nonnullMethodsBuilder);
143
144         if (Augmentable.class.isAssignableFrom(bindingClass)) {
145             this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
146         } else {
147             this.possibleAugmentations = ImmutableMap.of();
148         }
149         reloadAllAugmentations();
150
151         final Class<?> proxyClass = Proxy.getProxyClass(bindingClass.getClassLoader(), bindingClass,
152             AugmentationHolder.class);
153         try {
154             proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
155                     .asType(DATAOBJECT_TYPE);
156         } catch (NoSuchMethodException | IllegalAccessException e) {
157             throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
158         }
159     }
160
161     @SuppressFBWarnings("RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED")
162     private void reloadAllAugmentations() {
163         for (final Type augment : possibleAugmentations.values()) {
164             final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
165             if (augProto != null) {
166                 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
167                 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
168             }
169         }
170     }
171
172     @SuppressWarnings("unchecked")
173     @Override
174     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
175         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
176         return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
177                 childClass).get();
178     }
179
180     private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
181         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
182         if (childProto != null) {
183             return childProto;
184         }
185         if (Augmentation.class.isAssignableFrom(childClass)) {
186             return augmentationByClass(childClass);
187         }
188         return null;
189     }
190
191     @SuppressWarnings("unchecked")
192     @Override
193     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
194             final Class<C> childClass) {
195         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
196         if (childProto != null) {
197             return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
198         }
199         return Optional.empty();
200     }
201
202     @Override
203     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
204             final List<YangInstanceIdentifier.PathArgument> builder) {
205
206         final Class<? extends DataObject> argType = arg.getType();
207         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
208         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
209             ctxProto = augmentationByClass(argType);
210         }
211         final DataContainerCodecContext<?, ?> context =
212                 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
213         if (context instanceof ChoiceNodeCodecContext) {
214             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
215             choice.addYangPathArgument(arg, builder);
216
217             final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
218             final Class<? extends DataObject> type = arg.getType();
219             final DataContainerCodecContext<?, ?> caze;
220             if (caseType.isPresent()) {
221                 // Non-ambiguous addressing this should not pose any problems
222                 caze = choice.streamChild(caseType.get());
223             } else {
224                 caze = choice.getCaseByChildClass(type);
225             }
226
227             caze.addYangPathArgument(arg, builder);
228             return caze.bindingPathArgumentChild(arg, builder);
229         }
230         context.addYangPathArgument(arg, builder);
231         return context;
232     }
233
234     @SuppressWarnings("unchecked")
235     @Override
236     public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
237         final NodeContextSupplier childSupplier;
238         if (arg instanceof NodeIdentifierWithPredicates) {
239             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
240         } else if (arg instanceof AugmentationIdentifier) {
241             childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
242         } else {
243             childSupplier = byYang.get(arg);
244         }
245
246         return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
247             "Argument %s is not valid child of %s", arg, getSchema()).get();
248     }
249
250     protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
251         final LeafNodeCodecContext<?> value = leafChild.get(name);
252         return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
253     }
254
255     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
256         final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
257         // Direct instantiation or use in same module in which grouping
258         // was defined.
259         DataSchemaNode sameName;
260         try {
261             sameName = getSchema().getDataChildByName(origDef.getQName());
262         } catch (final IllegalArgumentException e) {
263             sameName = null;
264         }
265         final DataSchemaNode childSchema;
266         if (sameName != null) {
267             // Exactly same schema node
268             if (origDef.equals(sameName)) {
269                 childSchema = sameName;
270                 // We check if instantiated node was added via uses
271                 // statement and is instantiation of same grouping
272             } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
273                 childSchema = sameName;
274             } else {
275                 // Node has same name, but clearly is different
276                 childSchema = null;
277             }
278         } else {
279             // We are looking for instantiation via uses in other module
280             final QName instantiedName = origDef.getQName().withModule(namespace());
281             final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
282             // We check if it is really instantiated from same
283             // definition as class was derived
284             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
285                 childSchema = potential;
286             } else {
287                 childSchema = null;
288             }
289         }
290         final DataSchemaNode nonNullChild =
291                 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
292         return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
293     }
294
295     @SuppressWarnings("unchecked")
296     Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
297         return Item.of((Class<? extends DataObject>) childClass);
298     }
299
300     private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
301         final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
302         if (firstTry != null) {
303             return firstTry;
304         }
305         if (possibleAugmentations.containsKey(arg)) {
306             reloadAllAugmentations();
307             return byYangAugmented.get(arg);
308         }
309         return null;
310     }
311
312     private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
313         DataContainerCodecPrototype<?> lookup = augmentationByClassOrEquivalentClass(childClass);
314         if (lookup != null || !isPotentialAugmentation(childClass)) {
315             return lookup;
316         }
317
318         // Attempt to reload all augmentations using TCCL and lookup again
319         reloadAllAugmentations();
320         lookup = augmentationByClassOrEquivalentClass(childClass);
321         if (lookup != null) {
322             return lookup;
323         }
324
325         // Still no result, this can be caused by TCCL not being set up properly -- try the class's ClassLoader
326         // if it is present;
327         final ClassLoader loader = childClass.getClassLoader();
328         if (loader == null) {
329             return null;
330         }
331
332         LOG.debug("Class {} not loaded via TCCL, attempting to recover", childClass);
333         ClassLoaderUtils.runWithClassLoader(loader, this::reloadAllAugmentations);
334         return augmentationByClassOrEquivalentClass(childClass);
335     }
336
337     private boolean isPotentialAugmentation(final Class<?> childClass) {
338         final JavaTypeName name = JavaTypeName.create(childClass);
339         for (Type type : possibleAugmentations.values()) {
340             if (name.equals(type.getIdentifier())) {
341                 return true;
342             }
343         }
344         return false;
345     }
346
347     private @Nullable DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(
348             final @NonNull Class<?> childClass) {
349         final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
350         if (childProto != null) {
351             return childProto;
352         }
353
354         /*
355          * It is potentially mismatched valid augmentation - we look up equivalent augmentation
356          * using reflection and walk all stream child and compare augmenations classes if they are
357          * equivalent.
358          *
359          * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
360          */
361         @SuppressWarnings("rawtypes")
362         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
363         if (getBindingClass().equals(augTarget)) {
364             for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
365                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
366                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
367                     return realChild;
368                 }
369             }
370         }
371         return null;
372     }
373
374     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
375         final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
376         @SuppressWarnings("rawtypes")
377         final Class augClass;
378         try {
379             augClass = loader.loadClass(value);
380         } catch (final ClassNotFoundException e) {
381             LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
382             return null;
383         }
384
385         @SuppressWarnings("unchecked")
386         final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
387                 .getResolvedAugmentationSchema(getSchema(), augClass);
388         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
389     }
390
391     Object getBindingChildValue(final Method method, final NormalizedNodeContainer<?, ?, ?> domData) {
392         return method.isDefault() ? getBindingChildValue(nonnullMethods, method, domData, dummy -> ImmutableList.of())
393                 : getBindingChildValue(byMethod, method, domData, NodeCodecContext::defaultObject);
394     }
395
396     @SuppressWarnings("rawtypes")
397     private static Object getBindingChildValue(final ImmutableMap<Method, NodeContextSupplier> map, final Method method,
398             final NormalizedNodeContainer domData, final Function<NodeCodecContext<?>, Object> getDefaultObject) {
399         final NodeCodecContext<?> childContext = verifyNotNull(map.get(method),
400             "Cannot find data handler for method %s", method).get();
401
402         @SuppressWarnings("unchecked")
403         final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
404
405         // We do not want to use Optional.map() here because we do not want to invoke defaultObject() when we have
406         // normal value because defaultObject() may end up throwing an exception intentionally.
407         return domChild.isPresent() ? childContext.deserializeObject(domChild.get())
408                 : getDefaultObject.apply(childContext);
409     }
410
411     @SuppressWarnings("checkstyle:illegalCatch")
412     protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
413         try {
414             return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
415         } catch (final Throwable e) {
416             Throwables.throwIfUnchecked(e);
417             throw new RuntimeException(e);
418         }
419     }
420
421     @SuppressWarnings("unchecked")
422     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
423             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
424
425         @SuppressWarnings("rawtypes")
426         final Map map = new HashMap<>();
427
428         for (final NormalizedNode<?, ?> childValue : data.getValue()) {
429             if (childValue instanceof AugmentationNode) {
430                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
431                 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
432                 if (codecProto != null) {
433                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
434                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
435                 }
436             }
437         }
438         for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
439             final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
440             if (augData.isPresent()) {
441                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
442             }
443         }
444         return map;
445     }
446
447     Collection<Method> getHashCodeAndEqualsMethods() {
448         return byMethod.keySet();
449     }
450
451     @Override
452     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
453         checkArgument(getDomPathArgument().equals(arg));
454         return bindingArg();
455     }
456
457     @Override
458     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
459         checkArgument(bindingArg().equals(arg));
460         return getDomPathArgument();
461     }
462 }