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