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