BUG-8004: handle implicit RPC input
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / yangtools / binding / data / 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.yangtools.binding.data.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.ImmutableSortedMap;
15 import java.lang.invoke.MethodHandle;
16 import java.lang.invoke.MethodHandles;
17 import java.lang.invoke.MethodType;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Proxy;
21 import java.util.Collection;
22 import java.util.Comparator;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
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.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
34 import org.opendaylight.yangtools.sal.binding.model.api.Type;
35 import org.opendaylight.yangtools.yang.binding.Augmentable;
36 import org.opendaylight.yangtools.yang.binding.Augmentation;
37 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
47 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
51 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
52 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 abstract class DataObjectCodecContext<D extends DataObject,T extends DataNodeContainer> extends DataContainerCodecContext<D,T> {
58     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
59     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
60     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
61     private static final Comparator<Method> METHOD_BY_ALPHABET = new Comparator<Method>() {
62         @Override
63         public int compare(final Method o1, final Method o2) {
64             return o1.getName().compareTo(o2.getName());
65         }
66     };
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
81     protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
82         super(prototype);
83
84         this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
85
86         final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
87
88         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
89         final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
90         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
91         final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
92
93         // Adds leaves to mapping
94         for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
95             byMethodBuilder.put(leaf.getGetter(), leaf);
96             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
97         }
98
99         for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
100             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
101             byMethodBuilder.put(childDataObj.getValue(), childProto);
102             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
103             byYangBuilder.put(childProto.getYangArg(), childProto);
104             if (childProto.isChoice()) {
105                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
106                 for(final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
107                     byBindingArgClassBuilder.put(cazeChild, childProto);
108                 }
109             }
110         }
111         this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
112         this.byYang = ImmutableMap.copyOf(byYangBuilder);
113         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
114         byBindingArgClassBuilder.putAll(byStreamClass);
115         this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
116
117
118         if (Augmentable.class.isAssignableFrom(getBindingClass())) {
119             this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
120         } else {
121             this.possibleAugmentations = ImmutableMap.of();
122         }
123         reloadAllAugmentations();
124
125         final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(),  new Class[] { getBindingClass(), 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);
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 <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass) {
147         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
148         return (DataContainerCodecContext<DV, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
149                 childClass).get();
150     }
151
152     private final 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 <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
166             final Class<DV> childClass) {
167         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
168         if (childProto != null) {
169             return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV,?>) 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 = QName.create(namespace(), origDef.getQName().getLocalName());
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 final 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
288          * using reflection and walk all stream child and compare augmenations classes if they are
289          * equivalent.
290          *
291          * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
292          */
293         @SuppressWarnings("rawtypes")
294         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
295         if ((getBindingClass().equals(augTarget))) {
296             for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
297                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
298                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
299                     return realChild;
300                 }
301             }
302         }
303         return null;
304     }
305
306     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
307         final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
308         @SuppressWarnings("rawtypes")
309         final Class augClass;
310         try {
311             augClass = loader.loadClass(value);
312         } catch (final ClassNotFoundException e) {
313             LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
314             return null;
315         }
316
317         @SuppressWarnings("unchecked")
318         final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
319                 .getResolvedAugmentationSchema(getSchema(), augClass);
320         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
321     }
322
323     @SuppressWarnings("rawtypes")
324     Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
325         final NodeCodecContext<?> childContext = byMethod.get(method).get();
326         @SuppressWarnings("unchecked")
327         final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
328         if (domChild.isPresent()) {
329             return childContext.deserializeObject(domChild.get());
330         } else if (childContext instanceof LeafNodeCodecContext) {
331             return ((LeafNodeCodecContext)childContext).defaultObject();
332         } else {
333             return null;
334         }
335     }
336
337     protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
338         try {
339             return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
340         } catch (final Throwable e) {
341             throw Throwables.propagate(e);
342         }
343     }
344
345     @SuppressWarnings("unchecked")
346     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
347             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
348
349         @SuppressWarnings("rawtypes")
350         final Map map = new HashMap<>();
351
352         for (final NormalizedNode<?, ?> childValue : data.getValue()) {
353             if (childValue instanceof AugmentationNode) {
354                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
355                 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
356                 if (codecProto != null) {
357                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
358                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
359                 }
360             }
361         }
362         for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
363             final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
364             if (augData.isPresent()) {
365                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
366             }
367         }
368         return map;
369     }
370
371     public Collection<Method> getHashCodeAndEqualsMethods() {
372         return byMethod.keySet();
373     }
374
375     @Override
376     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
377         Preconditions.checkArgument(getDomPathArgument().equals(arg));
378         return bindingArg();
379     }
380
381     @Override
382     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
383         Preconditions.checkArgument(bindingArg().equals(arg));
384         return getDomPathArgument();
385     }
386 }