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