Cache mismatched augmentations
[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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableMap.Builder;
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.SortedMap;
29 import java.util.TreeMap;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.ConcurrentMap;
32 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
35 import org.opendaylight.mdsal.binding.model.api.Type;
36 import org.opendaylight.yangtools.yang.binding.Augmentable;
37 import org.opendaylight.yangtools.yang.binding.Augmentation;
38 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
39 import org.opendaylight.yangtools.yang.binding.DataObject;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
41 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
48 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
51 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
53 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
55 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
60         extends DataContainerCodecContext<D, T> {
61     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
62     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
63     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
64     private static final Comparator<Method> METHOD_BY_ALPHABET = (o1, o2) -> o1.getName().compareTo(o2.getName());
65
66     private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
67     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
68     private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
69     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
70     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
71     private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
72     private final MethodHandle proxyConstructor;
73
74     private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
75             new ConcurrentHashMap<>();
76     private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
77
78     private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
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     private void reloadAllAugmentations() {
135         for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
136             final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
137             if (augProto != null) {
138                 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
139                 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
140             }
141         }
142     }
143
144     @SuppressWarnings("unchecked")
145     @Override
146     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
147         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
148         return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
149                 childClass).get();
150     }
151
152     private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
153         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
154         if (childProto != null) {
155             return childProto;
156         }
157         if (Augmentation.class.isAssignableFrom(childClass)) {
158             return augmentationByClass(childClass);
159         }
160         return null;
161     }
162
163     @SuppressWarnings("unchecked")
164     @Override
165     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
166             final Class<C> childClass) {
167         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
168         if (childProto != null) {
169             return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
170         }
171         return Optional.absent();
172     }
173
174     @Override
175     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
176             final List<YangInstanceIdentifier.PathArgument> builder) {
177
178         final Class<? extends DataObject> argType = arg.getType();
179         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
180         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
181             ctxProto = augmentationByClass(argType);
182         }
183         final DataContainerCodecContext<?, ?> context =
184                 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
185         if (context instanceof ChoiceNodeCodecContext) {
186             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
187             final DataContainerCodecContext<?, ?> caze = choice.getCazeByChildClass(arg.getType());
188             choice.addYangPathArgument(arg, builder);
189             caze.addYangPathArgument(arg, builder);
190             return caze.bindingPathArgumentChild(arg, builder);
191         }
192         context.addYangPathArgument(arg, builder);
193         return context;
194     }
195
196     @SuppressWarnings("unchecked")
197     @Override
198     public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
199         final NodeContextSupplier childSupplier;
200         if (arg instanceof NodeIdentifierWithPredicates) {
201             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
202         } else if (arg instanceof AugmentationIdentifier) {
203             childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
204         } else {
205             childSupplier = byYang.get(arg);
206         }
207
208         return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
209             "Argument %s is not valid child of %s", arg, getSchema()).get();
210     }
211
212     protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
213         final LeafNodeCodecContext<?> value = leafChild.get(name);
214         return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
215     }
216
217     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
218         final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
219         // Direct instantiation or use in same module in which grouping
220         // was defined.
221         DataSchemaNode sameName;
222         try {
223             sameName = getSchema().getDataChildByName(origDef.getQName());
224         } catch (final IllegalArgumentException e) {
225             sameName = null;
226         }
227         final DataSchemaNode childSchema;
228         if (sameName != null) {
229             // Exactly same schema node
230             if (origDef.equals(sameName)) {
231                 childSchema = sameName;
232                 // We check if instantiated node was added via uses
233                 // statement and is instantiation of same grouping
234             } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
235                 childSchema = sameName;
236             } else {
237                 // Node has same name, but clearly is different
238                 childSchema = null;
239             }
240         } else {
241             // We are looking for instantiation via uses in other module
242             final QName instantiedName = origDef.getQName().withModule(namespace());
243             final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
244             // We check if it is really instantiated from same
245             // definition as class was derived
246             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
247                 childSchema = potential;
248             } else {
249                 childSchema = null;
250             }
251         }
252         final DataSchemaNode nonNullChild =
253                 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
254         return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
255     }
256
257     private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
258         final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
259         if (firstTry != null) {
260             return firstTry;
261         }
262         if (possibleAugmentations.containsKey(arg)) {
263             reloadAllAugmentations();
264             return byYangAugmented.get(arg);
265         }
266         return null;
267     }
268
269     @Nullable
270     private DataContainerCodecPrototype<?> augmentationByClass(@Nonnull final Class<?> childClass) {
271         final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
272         if (firstTry != null) {
273             return firstTry;
274         }
275         reloadAllAugmentations();
276         return augmentationByClassOrEquivalentClass(childClass);
277     }
278
279     @Nullable
280     private DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
281         final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
282         if (childProto != null) {
283             return childProto;
284         }
285
286         /*
287          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
288          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
289          * we'll cache it so we do not need to perform reflection operations again.
290          */
291         final DataContainerCodecPrototype<?> mismatched = mismatchedAugmented.get(childClass);
292         if (mismatched != null) {
293             return mismatched;
294         }
295
296         @SuppressWarnings("rawtypes")
297         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
298         if (getBindingClass().equals(augTarget)) {
299             for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
300                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
301                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
302                     return cacheMismatched(childClass, realChild);
303                 }
304             }
305         }
306         return null;
307     }
308
309     private synchronized DataContainerCodecPrototype<?> cacheMismatched(final Class<?> childClass,
310             final DataContainerCodecPrototype<?> prototype) {
311         // Original access was unsynchronized, we need to perform additional checking
312         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local = mismatchedAugmented;
313         final DataContainerCodecPrototype<?> existing = local.get(childClass);
314         if (existing != null) {
315             return existing;
316         }
317
318         final Builder<Class<?>, DataContainerCodecPrototype<?>> builder = ImmutableMap.builderWithExpectedSize(
319             local.size() + 1);
320         builder.putAll(local);
321         builder.put(childClass, prototype);
322
323         mismatchedAugmented = builder.build();
324         return prototype;
325     }
326
327     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
328         final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
329         @SuppressWarnings("rawtypes")
330         final Class augClass;
331         try {
332             augClass = loader.loadClass(value);
333         } catch (final ClassNotFoundException e) {
334             LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
335             return null;
336         }
337
338         @SuppressWarnings("unchecked")
339         final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
340                 .getResolvedAugmentationSchema(getSchema(), augClass);
341         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
342     }
343
344     @SuppressWarnings("rawtypes")
345     Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
346         final NodeCodecContext<?> childContext = byMethod.get(method).get();
347         @SuppressWarnings("unchecked")
348         final java.util.Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
349         if (domChild.isPresent()) {
350             return childContext.deserializeObject(domChild.get());
351         } else if (childContext instanceof LeafNodeCodecContext) {
352             return ((LeafNodeCodecContext)childContext).defaultObject();
353         } else {
354             return null;
355         }
356     }
357
358     @SuppressWarnings("checkstyle:illegalCatch")
359     protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
360         try {
361             return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
362         } catch (final Throwable e) {
363             Throwables.throwIfUnchecked(e);
364             throw new RuntimeException(e);
365         }
366     }
367
368     @SuppressWarnings("unchecked")
369     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
370             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
371
372         @SuppressWarnings("rawtypes")
373         final Map map = new HashMap<>();
374
375         for (final NormalizedNode<?, ?> childValue : data.getValue()) {
376             if (childValue instanceof AugmentationNode) {
377                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
378                 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
379                 if (codecProto != null) {
380                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
381                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
382                 }
383             }
384         }
385         for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
386             final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
387             if (augData.isPresent()) {
388                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
389             }
390         }
391         return map;
392     }
393
394     Collection<Method> getHashCodeAndEqualsMethods() {
395         return byMethod.keySet();
396     }
397
398     @Override
399     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
400         Preconditions.checkArgument(getDomPathArgument().equals(arg));
401         return bindingArg();
402     }
403
404     @Override
405     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
406         Preconditions.checkArgument(bindingArg().equals(arg));
407         return getDomPathArgument();
408     }
409 }