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