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