Update binding-dom adaptation to remove AugmentationNode
[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
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.ImmutableCollection;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import java.lang.invoke.MethodHandles;
17 import java.lang.invoke.VarHandle;
18 import java.lang.reflect.Method;
19 import java.util.HashMap;
20 import java.util.Map;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
24 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
25 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
26 import org.opendaylight.mdsal.binding.model.api.Type;
27 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
28 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
29 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
30 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
31 import org.opendaylight.yangtools.yang.binding.Augmentation;
32 import org.opendaylight.yangtools.yang.binding.BindingObject;
33 import org.opendaylight.yangtools.yang.binding.DataObject;
34 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
38 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
41 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
42 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
48  */
49 @Beta
50 public abstract class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
51         extends AbstractDataObjectCodecContext<D, T> implements BindingDataObjectCodecTreeNode<D> {
52     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
53
54     private static final VarHandle MISMATCHED_AUGMENTED;
55
56     static {
57         try {
58             MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
59                 "mismatchedAugmented", ImmutableMap.class);
60         } catch (NoSuchFieldException | IllegalAccessException e) {
61             throw new ExceptionInInitializerError(e);
62         }
63     }
64
65     private final ImmutableMap<Class<?>, DataContainerCodecPrototype.Augmentation> augmentToPrototype;
66     private final ImmutableMap<PathArgument, Class<?>> yangToAugmentClass;
67     private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
68
69     // Note this the content of this field depends only of invariants expressed as this class's fields or
70     // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
71     @SuppressWarnings("unused")
72     private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
73
74     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
75         this(prototype, CodecItemFactory.of());
76     }
77
78     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final CodecItemFactory itemFactory) {
79         this(prototype, new CodecDataObjectAnalysis<>(prototype, itemFactory, null));
80     }
81
82     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
83         this(prototype, new CodecDataObjectAnalysis<>(prototype, CodecItemFactory.of(), keyMethod));
84     }
85
86     private DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype,
87             final CodecDataObjectAnalysis<T> analysis) {
88         super(prototype, analysis);
89
90         // Inherit analysis stuff
91         generatedClass = analysis.generatedClass;
92
93         // Deal with augmentations, which are not something we analysis provides
94         final var augPathToBinding = new HashMap<PathArgument, Class<?>>();
95         final var augClassToProto = new HashMap<Class<?>, DataContainerCodecPrototype.Augmentation>();
96         for (var augment : analysis.possibleAugmentations) {
97             final var augProto = loadAugmentPrototype(augment);
98             if (augProto != null) {
99                 final var augBindingClass = augProto.getBindingClass();
100                 for (var childPath : augProto.getChildArgs()) {
101                     augPathToBinding.putIfAbsent(childPath, augBindingClass);
102                 }
103                 augClassToProto.putIfAbsent(augBindingClass, augProto);
104             }
105         }
106         yangToAugmentClass = ImmutableMap.copyOf(augPathToBinding);
107         augmentToPrototype = ImmutableMap.copyOf(augClassToProto);
108     }
109
110     @Override
111     final DataContainerCodecPrototype<?> pathChildPrototype(final Class<? extends DataObject> argType) {
112         final var child = super.pathChildPrototype(argType);
113         return child != null ? child : augmentToPrototype.get(argType);
114     }
115
116     @Override
117     final DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
118         final var child = super.streamChildPrototype(childClass);
119         if (child == null && Augmentation.class.isAssignableFrom(childClass)) {
120             return getAugmentationProtoByClass(childClass);
121         }
122         return child;
123     }
124
125     @Override
126     final NodeContextSupplier yangChildSupplier(final PathArgument arg) {
127         final var child = super.yangChildSupplier(arg);
128         if (child == null) {
129             final var augClass = yangToAugmentClass.get(arg);
130             if (augClass != null) {
131                 return augmentToPrototype.get(augClass);
132             }
133         }
134         return child;
135     }
136
137     private DataContainerCodecPrototype.@Nullable Augmentation getAugmentationProtoByClass(
138             final @NonNull Class<?> augmClass) {
139         final var childProto = augmentToPrototype.get(augmClass);
140         return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
141     }
142
143     private DataContainerCodecPrototype.@Nullable Augmentation mismatchedAugmentationByClass(
144             final @NonNull Class<?> childClass) {
145         /*
146          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
147          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
148          * we'll cache it so we do not need to perform reflection operations again.
149          */
150         final var local =
151             (ImmutableMap<Class<?>, DataContainerCodecPrototype.Augmentation>) MISMATCHED_AUGMENTED.getAcquire(this);
152         final var mismatched = local.get(childClass);
153         return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
154     }
155
156     private DataContainerCodecPrototype.@Nullable Augmentation loadMismatchedAugmentation(
157             final ImmutableMap<Class<?>, DataContainerCodecPrototype.Augmentation> oldMismatched,
158             final @NonNull Class<?> childClass) {
159         @SuppressWarnings("rawtypes")
160         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
161         // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
162         // context would load.
163         if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
164             for (var realChild : augmentToPrototype.values()) {
165                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
166                         && isSubstitutionFor(childClass, realChild.getBindingClass())) {
167                     return cacheMismatched(oldMismatched, childClass, realChild);
168                 }
169             }
170         }
171         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
172         return null;
173     }
174
175     private DataContainerCodecPrototype.@NonNull Augmentation cacheMismatched(
176             final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype.Augmentation> oldMismatched,
177             final @NonNull Class<?> childClass, final DataContainerCodecPrototype.@NonNull Augmentation prototype) {
178
179         var expected = oldMismatched;
180         while (true) {
181             final var newMismatched =
182                 ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
183                     .putAll(expected)
184                     .put(childClass, prototype)
185                     .build();
186
187             final var witness = (ImmutableMap<Class<?>, DataContainerCodecPrototype.Augmentation>)
188                 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
189             if (witness == expected) {
190                 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
191                 return prototype;
192             }
193
194             expected = witness;
195             final var existing = expected.get(childClass);
196             if (existing != null) {
197                 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
198                 return existing;
199             }
200         }
201     }
202
203     private boolean belongsToRuntimeContext(final Class<?> cls) {
204         final BindingRuntimeContext ctx = factory().getRuntimeContext();
205         final Class<?> loaded;
206         try {
207             loaded = ctx.loadClass(Type.of(cls));
208         } catch (ClassNotFoundException e) {
209             LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
210             return false;
211         }
212         return cls.equals(loaded);
213     }
214
215     private DataContainerCodecPrototype.@Nullable Augmentation loadAugmentPrototype(final AugmentRuntimeType augment) {
216         // FIXME: in face of deviations this code should be looking at declared view, i.e. all possibilities at augment
217         //        declaration site
218         final var childPaths = augment.statement()
219             .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
220             .map(stmt -> new NodeIdentifier((QName) stmt.argument()))
221             .collect(ImmutableSet.toImmutableSet());
222
223         final var it = childPaths.iterator();
224         if (!it.hasNext()) {
225             return null;
226         }
227         final var namespace = it.next().getNodeType().getModule();
228
229         final var factory = factory();
230         final GeneratedType javaType = augment.javaType();
231         final Class<? extends Augmentation<?>> augClass;
232         try {
233             augClass = factory.getRuntimeContext().loadClass(javaType);
234         } catch (final ClassNotFoundException e) {
235             throw new IllegalStateException(
236                 "RuntimeContext references type " + javaType + " but failed to load its class", e);
237         }
238         return new DataContainerCodecPrototype.Augmentation(augClass, namespace, augment, factory, childPaths);
239     }
240
241     @Override
242     @SuppressWarnings("unchecked")
243     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
244             final DistinctNodeContainer<PathArgument, NormalizedNode> data) {
245         /**
246          * Due to augmentation fields are at same level as direct children the data of each augmentation needs to be
247          * aggregated into own container node, then only deserialized using associated prototype.
248          */
249         final var builders = new HashMap<Class<?>, DataContainerNodeBuilder>();
250         for (var childValue : data.body()) {
251             final var bindingClass = yangToAugmentClass.get(childValue.getIdentifier());
252             if (bindingClass != null) {
253                 builders.computeIfAbsent(bindingClass,
254                     key -> Builders.containerBuilder()
255                         .withNodeIdentifier(new NodeIdentifier(data.getIdentifier().getNodeType())))
256                         .addChild(childValue);
257             }
258         }
259         @SuppressWarnings("rawtypes")
260         final var map = new HashMap();
261         for (final var entry : builders.entrySet()) {
262             final var bindingClass = entry.getKey();
263             final var codecProto = augmentToPrototype.get(bindingClass);
264             if (codecProto != null) {
265                 map.put(bindingClass, codecProto.get().deserializeObject(entry.getValue().build()));
266             }
267         }
268         return map;
269     }
270
271     final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
272         return generatedClass;
273     }
274
275     @Override
276     public InstanceIdentifier.PathArgument deserializePathArgument(final PathArgument arg) {
277         checkArgument(getDomPathArgument().equals(arg));
278         return bindingArg();
279     }
280
281     @Override
282     public PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
283         checkArgument(bindingArg().equals(arg));
284         return getDomPathArgument();
285     }
286
287     @Override
288     public NormalizedNode serialize(final D data) {
289         return serializeImpl(data);
290     }
291
292     @Override
293     public final BindingNormalizedNodeCachingCodec<D> createCachingCodec(
294             final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
295         return createCachingCodec(this, cacheSpecifier);
296     }
297 }