Bug 3067: Improved error reporting in Binding Data Codec
[yangtools.git] / code-generator / binding-data-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.MethodHandles.Lookup;
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 org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
31 import org.opendaylight.yangtools.sal.binding.model.api.Type;
32 import org.opendaylight.yangtools.yang.binding.Augmentable;
33 import org.opendaylight.yangtools.yang.binding.Augmentation;
34 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
35 import org.opendaylight.yangtools.yang.binding.DataObject;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
46 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
47 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 abstract class DataObjectCodecContext<D extends DataObject,T extends DataNodeContainer> extends DataContainerCodecContext<D,T> {
54     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
55     private static final Lookup LOOKUP = MethodHandles.publicLookup();
56     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
57     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
58     private static final Comparator<Method> METHOD_BY_ALPHABET = new Comparator<Method>() {
59         @Override
60         public int compare(final Method o1, final Method o2) {
61             return o1.getName().compareTo(o2.getName());
62         }
63     };
64
65     private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
66     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
67     private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
68     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
69     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
70     private final MethodHandle proxyConstructor;
71
72     protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
73         super(prototype);
74
75         this.leafChild = factory().getLeafNodes(getBindingClass(), schema());
76
77         final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
78
79         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
80         final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
81         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
82         final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
83
84         // Adds leaves to mapping
85         for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
86             byMethodBuilder.put(leaf.getGetter(), leaf);
87             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
88         }
89
90         for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
91             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
92             byMethodBuilder.put(childDataObj.getValue(), childProto);
93             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
94             byYangBuilder.put(childProto.getYangArg(), childProto);
95             if (childProto.isChoice()) {
96                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
97                 for(final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
98                     byBindingArgClassBuilder.put(cazeChild, childProto);
99                 }
100             }
101         }
102         this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
103         if (Augmentable.class.isAssignableFrom(getBindingClass())) {
104             final ImmutableMap<AugmentationIdentifier, Type> augmentations = factory().getRuntimeContext()
105                     .getAvailableAugmentationTypes(schema());
106             for (final Entry<AugmentationIdentifier, Type> augment : augmentations.entrySet()) {
107                 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
108                 if (augProto != null) {
109                     byYangBuilder.put(augProto.getYangArg(), augProto);
110                     byStreamClassBuilder.put(augProto.getBindingClass(), augProto);
111                 }
112             }
113         }
114
115         this.byYang = ImmutableMap.copyOf(byYangBuilder);
116         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
117         byBindingArgClassBuilder.putAll(byStreamClass);
118         this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
119
120         final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(),  new Class[] { getBindingClass(), AugmentationHolder.class });
121         try {
122             proxyConstructor = LOOKUP.findConstructor(proxyClass, CONSTRUCTOR_TYPE).asType(DATAOBJECT_TYPE);
123         } catch (NoSuchMethodException | IllegalAccessException e) {
124             throw new IllegalStateException("Failed to find contructor for class " + proxyClass);
125         }
126     }
127
128
129     @SuppressWarnings("unchecked")
130     @Override
131     public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass) {
132         DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
133         if (childProto != null) {
134             return (DataContainerCodecContext<DV,?>) childProto.get();
135         }
136
137         if (Augmentation.class.isAssignableFrom(childClass))  {
138             /*
139              * It is potentially mismatched valid augmentation - we look up equivalent augmentation
140              * using reflection and walk all stream child and compare augmenations classes
141              * if they are equivalent.
142              *
143              * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
144              */
145             @SuppressWarnings("rawtypes")
146             final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
147             if ((getBindingClass().equals(augTarget))) {
148                 for (final DataContainerCodecPrototype<?> realChild : byStreamClass.values()) {
149                     if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
150                             && BindingReflections.isSubstitutionFor(childClass,realChild.getBindingClass())) {
151                         childProto = realChild;
152                         break;
153                     }
154                 }
155             }
156         }
157         return (DataContainerCodecContext<DV, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.").get();
158     }
159
160
161     @SuppressWarnings("unchecked")
162     @Override
163     public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
164             final Class<DV> childClass) {
165         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
166         if(childProto != null) {
167             return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV,?>) childProto.get());
168         }
169         return Optional.absent();
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         final DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
178         final DataContainerCodecContext<?, ?> context =
179                 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
180         if (context instanceof ChoiceNodeCodecContext) {
181             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
182             final DataContainerCodecContext<?, ?> caze = choice.getCazeByChildClass(arg.getType());
183             choice.addYangPathArgument(arg, builder);
184             caze.addYangPathArgument(arg, builder);
185             return caze.bindingPathArgumentChild(arg, builder);
186         }
187         context.addYangPathArgument(arg, builder);
188         return context;
189     }
190
191     @SuppressWarnings("unchecked")
192     @Override
193     public NodeCodecContext<D> yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg) {
194         if(arg instanceof NodeIdentifierWithPredicates) {
195             arg = new NodeIdentifier(arg.getNodeType());
196         }
197         final NodeContextSupplier childSupplier = byYang.get(arg);
198         childNonNull(childSupplier != null, arg, "Argument %s is not valid child of %s", arg, schema());
199         return (NodeCodecContext<D>) childSupplier.get();
200     }
201
202     protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
203         final LeafNodeCodecContext<?> value = leafChild.get(name);
204         return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
205     }
206
207     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
208         final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
209         // Direct instantiation or use in same module in which grouping
210         // was defined.
211         DataSchemaNode sameName;
212         try {
213             sameName = schema().getDataChildByName(origDef.getQName());
214         } catch (final IllegalArgumentException e) {
215             sameName = null;
216         }
217         final DataSchemaNode childSchema;
218         if (sameName != null) {
219             // Exactly same schema node
220             if (origDef.equals(sameName)) {
221                 childSchema = sameName;
222                 // We check if instantiated node was added via uses
223                 // statement and is instantiation of same grouping
224             } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
225                 childSchema = sameName;
226             } else {
227                 // Node has same name, but clearly is different
228                 childSchema = null;
229             }
230         } else {
231             // We are looking for instantiation via uses in other module
232             final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
233             final DataSchemaNode potential = schema().getDataChildByName(instantiedName);
234             // We check if it is really instantiated from same
235             // definition as class was derived
236             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
237                 childSchema = potential;
238             } else {
239                 childSchema = null;
240             }
241         }
242         final DataSchemaNode nonNullChild =
243                 childNonNull(childSchema, childClass, "Node %s does not have child named %s", schema(), childClass);
244         return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
245     }
246
247     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
248         final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
249         @SuppressWarnings("rawtypes")
250         final Class augClass;
251         try {
252             augClass = loader.loadClass(value);
253         } catch (final ClassNotFoundException e) {
254             LOG.warn("Failed to load augmentation prototype for {}", value, e);
255             return null;
256         }
257
258         @SuppressWarnings("unchecked")
259         final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
260                 .getResolvedAugmentationSchema(schema(), augClass);
261         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
262     }
263
264     @SuppressWarnings("rawtypes")
265     Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
266         final NodeCodecContext<?> childContext = byMethod.get(method).get();
267         @SuppressWarnings("unchecked")
268         final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
269         if (domChild.isPresent()) {
270             return childContext.deserializeObject(domChild.get());
271         }
272         return null;
273     }
274
275     protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
276         try {
277             return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
278         } catch (final Throwable e) {
279             throw Throwables.propagate(e);
280         }
281     }
282
283     @SuppressWarnings("unchecked")
284     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
285             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
286
287         @SuppressWarnings("rawtypes")
288         final Map map = new HashMap<>();
289
290         for(final DataContainerCodecPrototype<?> value : byStreamClass.values()) {
291             if(Augmentation.class.isAssignableFrom(value.getBindingClass())) {
292                 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
293                 if(augData.isPresent()) {
294                     map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
295                 }
296             }
297         }
298         return map;
299     }
300
301     public Collection<Method> getHashCodeAndEqualsMethods() {
302         // FIXME: Sort method in same order as in hashCode for generated class.
303         return byMethod.keySet();
304     }
305
306     @Override
307     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
308         Preconditions.checkArgument(getDomPathArgument().equals(arg));
309         return bindingArg();
310     }
311
312     @Override
313     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
314         Preconditions.checkArgument(bindingArg().equals(arg));
315         return getDomPathArgument();
316     }
317 }