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