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