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