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