Moved binding MD-SAL APIs to binding folder
[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.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 java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.ConcurrentMap;
32 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
35 import org.opendaylight.yangtools.sal.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.AugmentationSchema;
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.util.SchemaNodeUtils;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 abstract class DataObjectCodecContext<D extends DataObject,T extends DataNodeContainer> extends DataContainerCodecContext<D,T> {
59     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
60     private static final Lookup LOOKUP = MethodHandles.publicLookup();
61     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
62     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
63     private static final Comparator<Method> METHOD_BY_ALPHABET = new Comparator<Method>() {
64         @Override
65         public int compare(final Method o1, final Method o2) {
66             return o1.getName().compareTo(o2.getName());
67         }
68     };
69
70     private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
71     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
72     private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
73     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
74     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
75     private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
76     private final MethodHandle proxyConstructor;
77
78     private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
79             new ConcurrentHashMap<>();
80     private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
81
82
83     protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
84         super(prototype);
85
86         this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
87
88         final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
89
90         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
91         final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
92         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
93         final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
94
95         // Adds leaves to mapping
96         for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
97             byMethodBuilder.put(leaf.getGetter(), leaf);
98             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
99         }
100
101         for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
102             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
103             byMethodBuilder.put(childDataObj.getValue(), childProto);
104             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
105             byYangBuilder.put(childProto.getYangArg(), childProto);
106             if (childProto.isChoice()) {
107                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
108                 for(final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
109                     byBindingArgClassBuilder.put(cazeChild, childProto);
110                 }
111             }
112         }
113         this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
114         this.byYang = ImmutableMap.copyOf(byYangBuilder);
115         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
116         byBindingArgClassBuilder.putAll(byStreamClass);
117         this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
118
119
120         if (Augmentable.class.isAssignableFrom(getBindingClass())) {
121             this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
122         } else {
123             this.possibleAugmentations = ImmutableMap.of();
124         }
125         reloadAllAugmentations();
126
127         final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(),  new Class[] { getBindingClass(), AugmentationHolder.class });
128         try {
129             proxyConstructor = LOOKUP.findConstructor(proxyClass, CONSTRUCTOR_TYPE).asType(DATAOBJECT_TYPE);
130         } catch (NoSuchMethodException | IllegalAccessException e) {
131             throw new IllegalStateException("Failed to find contructor for class " + proxyClass);
132         }
133     }
134
135     private void reloadAllAugmentations() {
136         for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
137             final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
138             if (augProto != null) {
139                 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
140                 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
141             }
142         }
143     }
144
145     @SuppressWarnings("unchecked")
146     @Override
147     public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass) {
148         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
149         return (DataContainerCodecContext<DV, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
150                 childClass).get();
151     }
152
153     private final DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
154         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
155         if (childProto != null) {
156             return childProto;
157         }
158         if (Augmentation.class.isAssignableFrom(childClass)) {
159             return augmentationByClass(childClass);
160         }
161         return null;
162     }
163
164     @SuppressWarnings("unchecked")
165     @Override
166     public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
167             final Class<DV> childClass) {
168         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
169         if(childProto != null) {
170             return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV,?>) childProto.get());
171         }
172         return Optional.absent();
173     }
174
175     @Override
176     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
177             final List<YangInstanceIdentifier.PathArgument> builder) {
178
179         final Class<? extends DataObject> argType = arg.getType();
180         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
181         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
182             ctxProto = augmentationByClass(argType);
183         }
184         final DataContainerCodecContext<?, ?> context =
185                 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
186         if (context instanceof ChoiceNodeCodecContext) {
187             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
188             final DataContainerCodecContext<?, ?> caze = choice.getCazeByChildClass(arg.getType());
189             choice.addYangPathArgument(arg, builder);
190             caze.addYangPathArgument(arg, builder);
191             return caze.bindingPathArgumentChild(arg, builder);
192         }
193         context.addYangPathArgument(arg, builder);
194         return context;
195     }
196
197     @SuppressWarnings("unchecked")
198     @Override
199     public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
200         final NodeContextSupplier childSupplier;
201         if(arg instanceof NodeIdentifierWithPredicates) {
202             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
203         } else if (arg instanceof AugmentationIdentifier) {
204             childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
205         } else {
206             childSupplier = byYang.get(arg);
207         }
208         childNonNull(childSupplier != null, arg, "Argument %s is not valid child of %s", arg, getSchema());
209         return (NodeCodecContext<D>) childSupplier.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         }
331         return null;
332     }
333
334     protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
335         try {
336             return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
337         } catch (final Throwable e) {
338             throw Throwables.propagate(e);
339         }
340     }
341
342     @SuppressWarnings("unchecked")
343     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
344             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
345
346         @SuppressWarnings("rawtypes")
347         final Map map = new HashMap<>();
348
349         for (final NormalizedNode<?, ?> childValue : data.getValue()) {
350             if (childValue instanceof AugmentationNode) {
351                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
352                 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
353                 if(codecProto != null) {
354                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
355                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
356                 }
357             }
358         }
359         for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
360             final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
361             if (augData.isPresent()) {
362                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
363             }
364         }
365         return map;
366     }
367
368     public Collection<Method> getHashCodeAndEqualsMethods() {
369         return byMethod.keySet();
370     }
371
372     @Override
373     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
374         Preconditions.checkArgument(getDomPathArgument().equals(arg));
375         return bindingArg();
376     }
377
378     @Override
379     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
380         Preconditions.checkArgument(bindingArg().equals(arg));
381         return getDomPathArgument();
382     }
383 }