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