ed07b6aae524bfe5091a94a46a7778acb97793f6
[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.yangtools.yang.binding.Augmentation;
31 import org.opendaylight.yangtools.yang.binding.BindingObject;
32 import org.opendaylight.yangtools.yang.binding.DataObject;
33 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
37 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
40 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
41 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
47  */
48 @Beta
49 public abstract sealed class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
50         extends AbstractDataObjectCodecContext<D, T> implements BindingDataObjectCodecTreeNode<D>
51         permits CaseCodecContext, ContainerLikeCodecContext, ListCodecContext, NotificationCodecContext {
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<?>, AugmentationCodecPrototype> augmentToPrototype;
66     private final ImmutableMap<NodeIdentifier, 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<?>, CommonDataObjectCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
73
74     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype) {
75         this(prototype, CodecItemFactory.of());
76     }
77
78     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final CodecItemFactory itemFactory) {
79         this(prototype, new CodecDataObjectAnalysis<>(prototype, itemFactory, null));
80     }
81
82     DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final Method keyMethod) {
83         this(prototype, new CodecDataObjectAnalysis<>(prototype, CodecItemFactory.of(), keyMethod));
84     }
85
86     private DataObjectCodecContext(final CommonDataObjectCodecPrototype<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<NodeIdentifier, Class<?>>();
95         final var augClassToProto = new HashMap<Class<?>, AugmentationCodecPrototype>();
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 CommonDataObjectCodecPrototype<?> 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 CommonDataObjectCodecPrototype<?> 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 CodecContextSupplier yangChildSupplier(final NodeIdentifier 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 @Nullable AugmentationCodecPrototype getAugmentationProtoByClass(final @NonNull Class<?> augmClass) {
138         final var childProto = augmentToPrototype.get(augmClass);
139         return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
140     }
141
142     private @Nullable AugmentationCodecPrototype mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
143         /*
144          * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
145          * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
146          * we'll cache it so we do not need to perform reflection operations again.
147          */
148         final var local = (ImmutableMap<Class<?>, AugmentationCodecPrototype>) MISMATCHED_AUGMENTED.getAcquire(this);
149         final var mismatched = local.get(childClass);
150         return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
151     }
152
153     private @Nullable AugmentationCodecPrototype loadMismatchedAugmentation(
154             final ImmutableMap<Class<?>, AugmentationCodecPrototype> oldMismatched,
155             final @NonNull Class<?> childClass) {
156         @SuppressWarnings("rawtypes")
157         final Class<?> augTarget = findAugmentationTarget((Class) childClass);
158         // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
159         // context would load.
160         if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
161             for (var realChild : augmentToPrototype.values()) {
162                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
163                         && isSubstitutionFor(childClass, realChild.getBindingClass())) {
164                     return cacheMismatched(oldMismatched, childClass, realChild);
165                 }
166             }
167         }
168         LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
169         return null;
170     }
171
172     private @NonNull AugmentationCodecPrototype cacheMismatched(
173             final @NonNull ImmutableMap<Class<?>, AugmentationCodecPrototype> oldMismatched,
174             final @NonNull Class<?> childClass, final @NonNull AugmentationCodecPrototype prototype) {
175         var expected = oldMismatched;
176         while (true) {
177             final var newMismatched =
178                 ImmutableMap.<Class<?>, CommonDataObjectCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
179                     .putAll(expected)
180                     .put(childClass, prototype)
181                     .build();
182
183             final var witness = (ImmutableMap<Class<?>, AugmentationCodecPrototype>)
184                 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
185             if (witness == expected) {
186                 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
187                 return prototype;
188             }
189
190             expected = witness;
191             final var existing = expected.get(childClass);
192             if (existing != null) {
193                 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
194                 return existing;
195             }
196         }
197     }
198
199     private boolean belongsToRuntimeContext(final Class<?> cls) {
200         final BindingRuntimeContext ctx = factory().getRuntimeContext();
201         final Class<?> loaded;
202         try {
203             loaded = ctx.loadClass(Type.of(cls));
204         } catch (ClassNotFoundException e) {
205             LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
206             return false;
207         }
208         return cls.equals(loaded);
209     }
210
211     private @Nullable AugmentationCodecPrototype loadAugmentPrototype(final AugmentRuntimeType augment) {
212         // FIXME: in face of deviations this code should be looking at declared view, i.e. all possibilities at augment
213         //        declaration site
214         final var childPaths = augment.statement()
215             .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
216             .map(stmt -> new NodeIdentifier((QName) stmt.argument()))
217             .collect(ImmutableSet.toImmutableSet());
218
219         if (childPaths.isEmpty()) {
220             return null;
221         }
222
223         final var factory = factory();
224         final GeneratedType javaType = augment.javaType();
225         final Class<? extends Augmentation<?>> augClass;
226         try {
227             augClass = factory.getRuntimeContext().loadClass(javaType);
228         } catch (final ClassNotFoundException e) {
229             throw new IllegalStateException(
230                 "RuntimeContext references type " + javaType + " but failed to load its class", e);
231         }
232         return new AugmentationCodecPrototype(augClass, augment, factory, childPaths);
233     }
234
235     @Override
236     @SuppressWarnings("unchecked")
237     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(final DataContainerNode data) {
238         /**
239          * Due to augmentation fields are at same level as direct children the data of each augmentation needs to be
240          * aggregated into own container node, then only deserialized using associated prototype.
241          */
242         final var builders = new HashMap<Class<?>, DataContainerNodeBuilder>();
243         for (var childValue : data.body()) {
244             final var bindingClass = yangToAugmentClass.get(childValue.name());
245             if (bindingClass != null) {
246                 builders.computeIfAbsent(bindingClass,
247                     key -> Builders.containerBuilder()
248                         .withNodeIdentifier(new NodeIdentifier(data.name().getNodeType())))
249                         .addChild(childValue);
250             }
251         }
252         @SuppressWarnings("rawtypes")
253         final var map = new HashMap();
254         for (final var entry : builders.entrySet()) {
255             final var bindingClass = entry.getKey();
256             final var codecProto = augmentToPrototype.get(bindingClass);
257             if (codecProto != null) {
258                 final var bindingObj = codecProto.get().deserializeObject(entry.getValue().build());
259                 if (bindingObj != null) {
260                     map.put(bindingClass, bindingObj);
261                 }
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 }