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