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