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