Bump upstreams
[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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
17 import java.lang.invoke.MethodHandles;
18 import java.lang.invoke.VarHandle;
19 import java.lang.reflect.Method;
20 import java.util.HashMap;
21 import java.util.Map;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
25 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
26 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
27 import org.opendaylight.mdsal.binding.model.api.Type;
28 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
29 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
30 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
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 CaseCodecContext, ContainerLikeCodecContext, ListCodecContext, 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     @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
74     private volatile ImmutableMap<Class<?>, CommonDataObjectCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
75
76     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype) {
77         this(prototype, CodecItemFactory.of());
78     }
79
80     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final CodecItemFactory itemFactory) {
81         this(prototype, new CodecDataObjectAnalysis<>(prototype, itemFactory, null));
82     }
83
84     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final Method keyMethod) {
85         this(prototype, new CodecDataObjectAnalysis<>(prototype, CodecItemFactory.of(), keyMethod));
86     }
87
88     private DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype,
89             final CodecDataObjectAnalysis<T> analysis) {
90         super(prototype, analysis);
91
92         // Inherit analysis stuff
93         generatedClass = analysis.generatedClass;
94
95         // Deal with augmentations, which are not something we analysis provides
96         final var augPathToBinding = new HashMap<NodeIdentifier, Class<?>>();
97         final var augClassToProto = new HashMap<Class<?>, AugmentationCodecPrototype>();
98         for (var augment : analysis.possibleAugmentations) {
99             final var augProto = loadAugmentPrototype(augment);
100             if (augProto != null) {
101                 final var augBindingClass = augProto.getBindingClass();
102                 for (var childPath : augProto.getChildArgs()) {
103                     augPathToBinding.putIfAbsent(childPath, augBindingClass);
104                 }
105                 augClassToProto.putIfAbsent(augBindingClass, augProto);
106             }
107         }
108         yangToAugmentClass = ImmutableMap.copyOf(augPathToBinding);
109         augmentToPrototype = ImmutableMap.copyOf(augClassToProto);
110     }
111
112     @Override
113     final CommonDataObjectCodecPrototype<?> pathChildPrototype(final Class<? extends DataObject> argType) {
114         final var child = super.pathChildPrototype(argType);
115         return child != null ? child : augmentToPrototype.get(argType);
116     }
117
118     @Override
119     final CommonDataObjectCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
120         final var child = super.streamChildPrototype(childClass);
121         if (child == null && Augmentation.class.isAssignableFrom(childClass)) {
122             return getAugmentationProtoByClass(childClass);
123         }
124         return child;
125     }
126
127     @Override
128     final CodecContextSupplier yangChildSupplier(final NodeIdentifier arg) {
129         final var child = super.yangChildSupplier(arg);
130         if (child == null) {
131             final var augClass = yangToAugmentClass.get(arg);
132             if (augClass != null) {
133                 return augmentToPrototype.get(augClass);
134             }
135         }
136         return child;
137     }
138
139     private @Nullable AugmentationCodecPrototype getAugmentationProtoByClass(final @NonNull Class<?> augmClass) {
140         final var childProto = augmentToPrototype.get(augmClass);
141         return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
142     }
143
144     private @Nullable AugmentationCodecPrototype mismatchedAugmentationByClass(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 = (ImmutableMap<Class<?>, AugmentationCodecPrototype>) MISMATCHED_AUGMENTED.getAcquire(this);
151         final var mismatched = local.get(childClass);
152         return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
153     }
154
155     private @Nullable AugmentationCodecPrototype loadMismatchedAugmentation(
156             final ImmutableMap<Class<?>, AugmentationCodecPrototype> oldMismatched,
157             final @NonNull Class<?> childClass) {
158         @SuppressWarnings("rawtypes")
159         final Class<?> augTarget = findAugmentationTarget((Class) childClass);
160         // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
161         // context would load.
162         if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
163             for (var realChild : augmentToPrototype.values()) {
164                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
165                         && isSubstitutionFor(childClass, realChild.getBindingClass())) {
166                     return cacheMismatched(oldMismatched, childClass, realChild);
167                 }
168             }
169         }
170         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
171         return null;
172     }
173
174     private @NonNull AugmentationCodecPrototype cacheMismatched(
175             final @NonNull ImmutableMap<Class<?>, AugmentationCodecPrototype> oldMismatched,
176             final @NonNull Class<?> childClass, final @NonNull AugmentationCodecPrototype prototype) {
177         var expected = oldMismatched;
178         while (true) {
179             final var newMismatched =
180                 ImmutableMap.<Class<?>, CommonDataObjectCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
181                     .putAll(expected)
182                     .put(childClass, prototype)
183                     .build();
184
185             final var witness = (ImmutableMap<Class<?>, AugmentationCodecPrototype>)
186                 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
187             if (witness == expected) {
188                 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
189                 return prototype;
190             }
191
192             expected = witness;
193             final var existing = expected.get(childClass);
194             if (existing != null) {
195                 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
196                 return existing;
197             }
198         }
199     }
200
201     private boolean belongsToRuntimeContext(final Class<?> cls) {
202         final BindingRuntimeContext ctx = factory().getRuntimeContext();
203         final Class<?> loaded;
204         try {
205             loaded = ctx.loadClass(Type.of(cls));
206         } catch (ClassNotFoundException e) {
207             LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
208             return false;
209         }
210         return cls.equals(loaded);
211     }
212
213     private @Nullable AugmentationCodecPrototype loadAugmentPrototype(final AugmentRuntimeType augment) {
214         // FIXME: in face of deviations this code should be looking at declared view, i.e. all possibilities at augment
215         //        declaration site
216         final var childPaths = augment.statement()
217             .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
218             .map(stmt -> new NodeIdentifier((QName) stmt.argument()))
219             .collect(ImmutableSet.toImmutableSet());
220
221         if (childPaths.isEmpty()) {
222             return null;
223         }
224
225         final var factory = factory();
226         final GeneratedType javaType = augment.javaType();
227         final Class<? extends Augmentation<?>> augClass;
228         try {
229             augClass = factory.getRuntimeContext().loadClass(javaType);
230         } catch (final ClassNotFoundException e) {
231             throw new IllegalStateException(
232                 "RuntimeContext references type " + javaType + " but failed to load its class", e);
233         }
234         return new AugmentationCodecPrototype(augClass, augment, factory, childPaths);
235     }
236
237     @Override
238     @SuppressWarnings("unchecked")
239     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(final DataContainerNode data) {
240         /**
241          * Due to augmentation fields are at same level as direct children the data of each augmentation needs to be
242          * aggregated into own container node, then only deserialized using associated prototype.
243          */
244         final var builders = new HashMap<Class<?>, DataContainerNodeBuilder>();
245         for (var childValue : data.body()) {
246             final var bindingClass = yangToAugmentClass.get(childValue.name());
247             if (bindingClass != null) {
248                 builders.computeIfAbsent(bindingClass,
249                     key -> Builders.containerBuilder()
250                         .withNodeIdentifier(new NodeIdentifier(data.name().getNodeType())))
251                         .addChild(childValue);
252             }
253         }
254         @SuppressWarnings("rawtypes")
255         final var map = new HashMap();
256         for (final var entry : builders.entrySet()) {
257             final var bindingClass = entry.getKey();
258             final var codecProto = augmentToPrototype.get(bindingClass);
259             if (codecProto != null) {
260                 final var bindingObj = codecProto.get().deserializeObject(entry.getValue().build());
261                 if (bindingObj != null) {
262                     map.put(bindingClass, bindingObj);
263                 }
264             }
265         }
266         return map;
267     }
268
269     final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
270         return generatedClass;
271     }
272
273     @Override
274     public InstanceIdentifier.PathArgument deserializePathArgument(final PathArgument arg) {
275         checkArgument(getDomPathArgument().equals(arg));
276         return bindingArg();
277     }
278
279     @Override
280     public PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
281         checkArgument(bindingArg().equals(arg));
282         return getDomPathArgument();
283     }
284
285     @Override
286     public NormalizedNode serialize(final D data) {
287         return serializeImpl(data);
288     }
289
290     @Override
291     public final BindingNormalizedNodeCachingCodec<D> createCachingCodec(
292             final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
293         return createCachingCodec(this, cacheSpecifier);
294     }
295 }