c5941d5cd57348b13e3b2bb2df43165f27e27269
[mdsal.git] / binding2 / mdsal-binding2-dom-codec / src / main / java / org / opendaylight / mdsal / binding / javav2 / dom / codec / impl / context / base / TreeNodeCodecContext.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies s.r.o. 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
9 package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base;
10
11 import com.google.common.annotations.Beta;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Throwables;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSortedMap;
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 javax.annotation.Nonnull;
34 import javax.annotation.Nullable;
35 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ChoiceNodeCodecContext;
36 import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy;
37 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
38 import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections;
39 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument;
40 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
41 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
42 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
43 import org.opendaylight.mdsal.binding.javav2.spec.structural.AugmentationHolder;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
50 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
53 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 @Beta
61 public abstract class TreeNodeCodecContext<D extends TreeNode, T extends DataNodeContainer>
62         extends DataContainerCodecContext<D, T> {
63
64     private static final Logger LOG = LoggerFactory.getLogger(TreeNodeCodecContext.class);
65     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
66     private static final MethodType TREENODE_TYPE = MethodType.methodType(TreeNode.class, InvocationHandler.class);
67     private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
68
69     private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
70     private final ImmutableMap<String, AnyxmlNodeCodecContext<?>> anyxmlChild;
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<PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
79             new ConcurrentHashMap<>();
80     private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
81
82
83     protected TreeNodeCodecContext(final DataContainerCodecPrototype<T> prototype) {
84         super(prototype);
85
86         this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
87         this.anyxmlChild = factory().getAnyxmlNodes(getBindingClass(), getSchema());
88
89         final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
90
91         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
92         final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
93         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
94         final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
95
96         // Adds leaves to mapping
97         for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
98             byMethodBuilder.put(leaf.getGetter(), leaf);
99             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
100         }
101
102         for (final AnyxmlNodeCodecContext<?> anyxml : anyxmlChild.values()) {
103             byMethodBuilder.put(anyxml.getGetter(), anyxml);
104             byYangBuilder.put(anyxml.getDomPathArgument(), anyxml);
105         }
106
107         for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
108             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
109             byMethodBuilder.put(childDataObj.getValue(), childProto);
110             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
111             byYangBuilder.put(childProto.getYangArg(), childProto);
112
113             if (childProto.isChoice()) {
114                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
115                 choice.getClassCaseChildren().entrySet().forEach(entry ->
116                     byBindingArgClassBuilder.put(entry.getKey(), childProto));
117
118                 choice.getYangCaseChildren().entrySet().forEach(entry ->
119                     byYangBuilder.put(entry.getKey(), childProto));
120             }
121         }
122
123         this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
124         this.byYang = ImmutableMap.copyOf(byYangBuilder);
125         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
126         byBindingArgClassBuilder.putAll(byStreamClass);
127         this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
128
129
130         if (Augmentable.class.isAssignableFrom(getBindingClass())) {
131             this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
132         } else {
133             this.possibleAugmentations = ImmutableMap.of();
134         }
135         reloadAllAugmentations();
136
137         final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(),
138             new Class[] { getBindingClass(), AugmentationHolder.class });
139         try {
140             proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
141                     .asType(TREENODE_TYPE);
142         } catch (NoSuchMethodException | IllegalAccessException e) {
143             throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
144         }
145     }
146
147     private void reloadAllAugmentations() {
148         for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
149             final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
150             if (augProto != null) {
151                 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
152                 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
153             }
154         }
155     }
156
157     @Nonnull
158     @SuppressWarnings("unchecked")
159     @Override
160     public <C extends TreeNode> DataContainerCodecContext<C, ?> streamChild(@Nonnull final Class<C> childClass) {
161         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
162         return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
163                 childClass).get();
164     }
165
166     private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
167         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
168         if (childProto != null) {
169             return childProto;
170         }
171         if (Augmentation.class.isAssignableFrom(childClass)) {
172             return augmentationByClass(childClass);
173         }
174         return null;
175     }
176
177     @SuppressWarnings("unchecked")
178     @Override
179     public <C extends TreeNode> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
180             @Nonnull final Class<C> childClass) {
181         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
182         if (childProto != null) {
183             return Optional.of((DataContainerCodecContext<C,?>) childProto.get());
184         }
185         return Optional.empty();
186     }
187
188     @Nonnull
189     @Override
190     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final TreeArgument<?> arg,
191             final List<PathArgument> builder) {
192
193         final Class<? extends TreeNode> argType = (Class<? extends TreeNode>) arg.getType();
194         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
195         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
196             ctxProto = augmentationByClass(argType);
197         }
198         final DataContainerCodecContext<?, ?> context =
199                 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
200
201         if (context instanceof ChoiceNodeCodecContext) {
202             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
203             final DataContainerCodecContext<?, ?> caze = choice.getCaseByChildClass(argType);
204             // FIXME: Instance identifier should not reference choice or case as they're
205             // not data tree nodes.
206             return caze.bindingPathArgumentChild(arg, builder);
207         }
208
209         context.addYangPathArgument(arg, builder);
210         return context;
211     }
212
213     @Nonnull
214     @SuppressWarnings("unchecked")
215     @Override
216     public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
217         final NodeContextSupplier childSupplier;
218         if (arg instanceof NodeIdentifierWithPredicates) {
219             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
220         } else if (arg instanceof AugmentationIdentifier) {
221             childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
222         } else {
223             childSupplier = byYang.get(arg);
224         }
225
226         // FIXME: Since instance identifier does not reference choice or case,
227         // we should search in data children of choice/case
228         if (childSupplier instanceof DataContainerCodecPrototype) {
229             final DataContainerCodecContext<?,T> context = ((DataContainerCodecPrototype) childSupplier).get();
230             if (context instanceof ChoiceNodeCodecContext) {
231                 return (NodeCodecContext<D>) childNonNull(((ChoiceNodeCodecContext) context).yangPathArgumentChild(arg),
232                     arg, "Argument %s is not valid child of %s", arg, getSchema());
233             }
234         }
235
236         return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
237                 "Argument %s is not valid child of %s", arg, getSchema()).get();
238     }
239
240     public final LeafNodeCodecContext<?> getLeafChild(final String name) {
241         final LeafNodeCodecContext<?> value = leafChild.get(name);
242         return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
243     }
244
245     public final AnyxmlNodeCodecContext<?> getAnyxmlChild(final String name) {
246         final AnyxmlNodeCodecContext<?> value = anyxmlChild.get(name);
247         return IncorrectNestingException.checkNonNull(value, "Anyxml %s is not valid for %s", name, getBindingClass());
248     }
249
250     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
251         final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
252         // Direct instantiation or use in same module in which grouping
253         // was defined.
254         DataSchemaNode sameName;
255         try {
256             sameName = getSchema().getDataChildByName(origDef.getQName());
257         } catch (final IllegalArgumentException e) {
258             sameName = null;
259         }
260         final DataSchemaNode childSchema;
261         if (sameName != null) {
262             // Exactly same schema node
263             if (origDef.equals(sameName)) {
264                 childSchema = sameName;
265                 // We check if instantiated node was added via uses
266                 // statement and is instantiation of same grouping
267             } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
268                 childSchema = sameName;
269             } else {
270                 // Node has same name, but clearly is different
271                 childSchema = null;
272             }
273         } else {
274             // We are looking for instantiation via uses in other module
275             final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
276             final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
277             // We check if it is really instantiated from same
278             // definition as class was derived
279             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
280                 childSchema = potential;
281             } else {
282                 childSchema = null;
283             }
284         }
285         final DataSchemaNode nonNullChild =
286                 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
287         return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
288     }
289
290     private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
291         final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
292         if (firstTry != null) {
293             return firstTry;
294         }
295         if (possibleAugmentations.containsKey(arg)) {
296             reloadAllAugmentations();
297             return byYangAugmented.get(arg);
298         }
299         return null;
300     }
301
302     @Nullable
303     private DataContainerCodecPrototype<?> augmentationByClass(@Nonnull final Class<?> childClass) {
304         final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
305         if (firstTry != null) {
306             return firstTry;
307         }
308         reloadAllAugmentations();
309         return augmentationByClassOrEquivalentClass(childClass);
310     }
311
312     @Nullable
313     private DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
314         final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
315         if (childProto != null) {
316             return childProto;
317         }
318
319         /*
320          * It is potentially mismatched valid augmentation - we look up equivalent augmentation
321          * using reflection and walk all stream child and compare augmenations classes if they are
322          * equivalent.
323          *
324          * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
325          */
326         @SuppressWarnings("rawtypes")
327         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
328         if (getBindingClass().equals(augTarget)) {
329             for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
330                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
331                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
332                     return realChild;
333                 }
334             }
335         }
336         return null;
337     }
338
339     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
340         final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
341         @SuppressWarnings("rawtypes")
342         final Class augClass;
343         try {
344             augClass = loader.loadClass(value);
345         } catch (final ClassNotFoundException e) {
346             LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
347             return null;
348         }
349
350         @SuppressWarnings("unchecked")
351         final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
352                 .getResolvedAugmentationSchema(getSchema(), augClass);
353         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
354     }
355
356     @SuppressWarnings("rawtypes")
357     public Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
358         final NodeCodecContext<?> childContext = byMethod.get(method).get();
359         @SuppressWarnings("unchecked")
360         final java.util.Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
361         if (domChild.isPresent()) {
362             return childContext.deserializeObject(domChild.get());
363         } else if (childContext instanceof LeafNodeCodecContext) {
364             return ((LeafNodeCodecContext)childContext).defaultObject();
365         } else {
366             return null;
367         }
368     }
369
370     @SuppressWarnings("checkstyle:illegalCatch")
371     protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
372         try {
373             return (D) proxyConstructor.invokeExact((InvocationHandler) new LazyTreeNode<>(this, node));
374         } catch (final Throwable e) {
375             throw Throwables.propagate(e);
376         }
377     }
378
379     @SuppressWarnings("unchecked")
380     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
381             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
382
383         @SuppressWarnings("rawtypes")
384         final Map map = new HashMap<>();
385
386         for (final NormalizedNode<?, ?> childValue : data.getValue()) {
387             if (childValue instanceof AugmentationNode) {
388                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
389                 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
390                 if (codecProto != null) {
391                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
392                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
393                 }
394             }
395         }
396         for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
397             final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
398             if (augData.isPresent()) {
399                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
400             }
401         }
402         return map;
403     }
404
405     public Collection<Method> getHashCodeAndEqualsMethods() {
406         return byMethod.keySet();
407     }
408
409     @Override
410     public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
411         Preconditions.checkArgument(getDomPathArgument().equals(arg));
412         return bindingArg();
413     }
414
415     @Override
416     public YangInstanceIdentifier.PathArgument serializePathArgument(final TreeArgument arg) {
417         Preconditions.checkArgument(bindingArg().equals(arg));
418         return getDomPathArgument();
419     }
420
421 }