73fa12e6ed816d7cd6fbe4f5c8a67b74f9d57f20
[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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableMap.Builder;
17 import java.lang.invoke.MethodHandle;
18 import java.lang.invoke.MethodHandles;
19 import java.lang.invoke.MethodType;
20 import java.lang.reflect.Method;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.Optional;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
29 import org.opendaylight.mdsal.binding.model.api.DefaultType;
30 import org.opendaylight.mdsal.binding.model.api.Type;
31 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
32 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
33 import org.opendaylight.yangtools.yang.binding.Augmentable;
34 import org.opendaylight.yangtools.yang.binding.Augmentation;
35 import org.opendaylight.yangtools.yang.binding.DataObject;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
38 import org.opendaylight.yangtools.yang.binding.OpaqueObject;
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.AugmentationNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
48 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
52 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
58  */
59 @Beta
60 public abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
61         extends DataContainerCodecContext<D, T> {
62     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
63     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
64         DataObjectCodecContext.class, NormalizedNodeContainer.class);
65     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
66         DataObjectCodecContext.class, NormalizedNodeContainer.class);
67
68     private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
69     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
70     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
71     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
72     private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> augmentationByYang;
73     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> augmentationByStream;
74     private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
75     private final MethodHandle proxyConstructor;
76
77     // Note this the content of this field depends only of invariants expressed as this class's fields or
78     // BindingRuntimeContext.
79     private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
80
81     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
82         this(prototype, null);
83     }
84
85     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
86         super(prototype);
87
88         final Class<D> bindingClass = getBindingClass();
89
90         final ImmutableMap<Method, ValueNodeCodecContext> tmpLeaves = factory().getLeafNodes(bindingClass, getSchema());
91         final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
92
93         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
94         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
95         final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
96
97         // Adds leaves to mapping
98         final Builder<String, ValueNodeCodecContext> leafChildBuilder =
99                 ImmutableMap.builderWithExpectedSize(tmpLeaves.size());
100         for (final Entry<Method, ValueNodeCodecContext> entry : tmpLeaves.entrySet()) {
101             final ValueNodeCodecContext leaf = entry.getValue();
102             leafChildBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
103             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
104         }
105         this.leafChild = leafChildBuilder.build();
106
107         final Map<Method, Class<?>> tmpDataObjects = new HashMap<>();
108         for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
109             final Method method = childDataObj.getValue();
110             verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
111
112             final Class<?> retClass = childDataObj.getKey();
113             if (OpaqueObject.class.isAssignableFrom(retClass)) {
114                 // Filter OpaqueObjects, they are not containers
115                 continue;
116             }
117
118             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(retClass);
119             tmpDataObjects.put(method, childProto.getBindingClass());
120             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
121             byYangBuilder.put(childProto.getYangArg(), childProto);
122             if (childProto.isChoice()) {
123                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
124                 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
125                     byBindingArgClassBuilder.put(cazeChild, childProto);
126                 }
127             }
128         }
129
130         this.byYang = ImmutableMap.copyOf(byYangBuilder);
131         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
132
133         // Slight footprint optimization: we do not want to copy byStreamClass, as that would force its entrySet view
134         // to be instantiated. Furthermore the two maps can easily end up being equal -- hence we can reuse
135         // byStreamClass for the purposes of both.
136         byBindingArgClassBuilder.putAll(byStreamClassBuilder);
137         this.byBindingArgClass = byStreamClassBuilder.equals(byBindingArgClassBuilder) ? this.byStreamClass
138                 : ImmutableMap.copyOf(byBindingArgClassBuilder);
139
140         final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
141         if (Augmentable.class.isAssignableFrom(bindingClass)) {
142             possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
143             generatedClass = CodecDataObjectGenerator.generateAugmentable(prototype.getFactory().getLoader(),
144                 bindingClass, tmpLeaves, tmpDataObjects, keyMethod);
145         } else {
146             possibleAugmentations = ImmutableMap.of();
147             generatedClass = CodecDataObjectGenerator.generate(prototype.getFactory().getLoader(), bindingClass,
148                 tmpLeaves, tmpDataObjects, keyMethod);
149         }
150
151         // Iterate over all possible augmentations, indexing them as needed
152         final Map<PathArgument, DataContainerCodecPrototype<?>> augByYang = new HashMap<>();
153         final Map<Class<?>, DataContainerCodecPrototype<?>> augByStream = new HashMap<>();
154         for (final Type augment : possibleAugmentations.values()) {
155             final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
156             final PathArgument augYangArg = augProto.getYangArg();
157             if (augByYang.putIfAbsent(augYangArg, augProto) == null) {
158                 LOG.trace("Discovered new YANG mapping {} -> {} in {}", augYangArg, augProto, this);
159             }
160             final Class<?> augBindingClass = augProto.getBindingClass();
161             if (augByStream.putIfAbsent(augBindingClass, augProto) == null) {
162                 LOG.trace("Discovered new class mapping {} -> {} in {}", augBindingClass, augProto, this);
163             }
164         }
165         augmentationByYang = ImmutableMap.copyOf(augByYang);
166         augmentationByStream = ImmutableMap.copyOf(augByStream);
167
168         final MethodHandle ctor;
169         try {
170             ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
171         } catch (NoSuchMethodException | IllegalAccessException e) {
172             throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
173         }
174
175         proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
176     }
177
178     @SuppressWarnings("unchecked")
179     @Override
180     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
181         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
182         return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
183                 childClass).get();
184     }
185
186     private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
187         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
188         if (childProto != null) {
189             return childProto;
190         }
191         if (Augmentation.class.isAssignableFrom(childClass)) {
192             return augmentationByClass(childClass);
193         }
194         return null;
195     }
196
197     @SuppressWarnings("unchecked")
198     @Override
199     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
200             final Class<C> childClass) {
201         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
202         if (childProto != null) {
203             return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
204         }
205         return Optional.empty();
206     }
207
208     @Override
209     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
210             final List<YangInstanceIdentifier.PathArgument> builder) {
211
212         final Class<? extends DataObject> argType = arg.getType();
213         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
214         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
215             ctxProto = augmentationByClass(argType);
216         }
217         final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
218             "Class %s is not valid child of %s", argType, getBindingClass()).get();
219         if (context instanceof ChoiceNodeCodecContext) {
220             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
221             choice.addYangPathArgument(arg, builder);
222
223             final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
224             final Class<? extends DataObject> type = arg.getType();
225             final DataContainerCodecContext<?, ?> caze;
226             if (caseType.isPresent()) {
227                 // Non-ambiguous addressing this should not pose any problems
228                 caze = choice.streamChild(caseType.get());
229             } else {
230                 caze = choice.getCaseByChildClass(type);
231             }
232
233             caze.addYangPathArgument(arg, builder);
234             return caze.bindingPathArgumentChild(arg, builder);
235         }
236         context.addYangPathArgument(arg, builder);
237         return context;
238     }
239
240     @Override
241     public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
242         final NodeContextSupplier childSupplier;
243         if (arg instanceof NodeIdentifierWithPredicates) {
244             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
245         } else if (arg instanceof AugmentationIdentifier) {
246             childSupplier = augmentationByYang.get(arg);
247         } else {
248             childSupplier = byYang.get(arg);
249         }
250
251         return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
252     }
253
254     protected final ValueNodeCodecContext getLeafChild(final String name) {
255         final ValueNodeCodecContext value = leafChild.get(name);
256         if (value == null) {
257             throw IncorrectNestingException.create("Leaf %s is not valid for %s", name, getBindingClass());
258         }
259         return value;
260     }
261
262     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
263         final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
264         // Direct instantiation or use in same module in which grouping
265         // was defined.
266         DataSchemaNode sameName;
267         try {
268             sameName = getSchema().getDataChildByName(origDef.getQName());
269         } catch (final IllegalArgumentException e) {
270             sameName = null;
271         }
272         final DataSchemaNode childSchema;
273         if (sameName != null) {
274             // Exactly same schema node
275             if (origDef.equals(sameName)) {
276                 childSchema = sameName;
277                 // We check if instantiated node was added via uses
278                 // statement and is instantiation of same grouping
279             } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
280                 childSchema = sameName;
281             } else {
282                 // Node has same name, but clearly is different
283                 childSchema = null;
284             }
285         } else {
286             // We are looking for instantiation via uses in other module
287             final QName instantiedName = origDef.getQName().bindTo(namespace());
288             final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
289             // We check if it is really instantiated from same
290             // definition as class was derived
291             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
292                 childSchema = potential;
293             } else {
294                 childSchema = null;
295             }
296         }
297         final DataSchemaNode nonNullChild =
298                 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
299         return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
300     }
301
302     @SuppressWarnings("unchecked")
303     Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
304         return Item.of((Class<? extends DataObject>) childClass);
305     }
306
307     private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
308         final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
309         if (childProto != null) {
310             return childProto;
311         }
312
313         /*
314          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
315          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
316          * we'll cache it so we do not need to perform reflection operations again.
317          */
318         final DataContainerCodecPrototype<?> mismatched = mismatchedAugmented.get(childClass);
319         if (mismatched != null) {
320             return mismatched;
321         }
322
323         @SuppressWarnings("rawtypes")
324         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
325         // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
326         // context would load.
327         if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
328             for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
329                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
330                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
331                     return cacheMismatched(childClass, realChild);
332                 }
333             }
334         }
335         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
336         return null;
337     }
338
339     // TODO: can we ditch this synchronized block?
340     private synchronized DataContainerCodecPrototype<?> cacheMismatched(final Class<?> childClass,
341             final DataContainerCodecPrototype<?> prototype) {
342         // Original access was unsynchronized, we need to perform additional checking
343         final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local = mismatchedAugmented;
344         final DataContainerCodecPrototype<?> existing = local.get(childClass);
345         if (existing != null) {
346             return existing;
347         }
348
349         final Builder<Class<?>, DataContainerCodecPrototype<?>> builder = ImmutableMap.builderWithExpectedSize(
350             local.size() + 1);
351         builder.putAll(local);
352         builder.put(childClass, prototype);
353
354         mismatchedAugmented = builder.build();
355         LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
356         return prototype;
357     }
358
359     private boolean belongsToRuntimeContext(final Class<?> cls) {
360         final BindingRuntimeContext ctx = factory().getRuntimeContext();
361         final Class<?> loaded;
362         try {
363             loaded = ctx.loadClass(DefaultType.of(cls));
364         } catch (ClassNotFoundException e) {
365             LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx);
366             return false;
367         }
368         return cls.equals(loaded);
369     }
370
371     private @NonNull DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
372         final BindingRuntimeContext ctx = factory().getRuntimeContext();
373
374         final Class<? extends Augmentation<?>> augClass;
375         try {
376             augClass = ctx.loadClass(value);
377         } catch (final ClassNotFoundException e) {
378             throw new IllegalStateException("RuntimeContext references type " + value + " but failed to its class", e);
379         }
380
381         final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema =
382                 ctx.getResolvedAugmentationSchema(getSchema(), augClass);
383         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
384     }
385
386     @SuppressWarnings("checkstyle:illegalCatch")
387     protected final @NonNull D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
388         try {
389             return (D) proxyConstructor.invokeExact(this, node);
390         } catch (final Throwable e) {
391             Throwables.throwIfUnchecked(e);
392             throw new IllegalStateException(e);
393         }
394     }
395
396     @SuppressWarnings("unchecked")
397     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
398             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
399
400         @SuppressWarnings("rawtypes")
401         final Map map = new HashMap<>();
402
403         for (final NormalizedNode<?, ?> childValue : data.getValue()) {
404             if (childValue instanceof AugmentationNode) {
405                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
406                 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
407                 if (codecProto != null) {
408                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
409                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
410                 }
411             }
412         }
413         for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
414             final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
415             if (augData.isPresent()) {
416                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
417             }
418         }
419         return map;
420     }
421
422     final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
423         return generatedClass;
424     }
425
426     @Override
427     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
428         checkArgument(getDomPathArgument().equals(arg));
429         return bindingArg();
430     }
431
432     @Override
433     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
434         checkArgument(bindingArg().equals(arg));
435         return getDomPathArgument();
436     }
437 }