2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Throwables;
14 import com.google.common.base.VerifyException;
15 import com.google.common.collect.ImmutableCollection;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableSet;
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.lang.invoke.MethodHandle;
20 import java.lang.invoke.MethodHandles;
21 import java.lang.invoke.MethodType;
22 import java.lang.invoke.VarHandle;
23 import java.lang.reflect.Method;
24 import java.util.HashMap;
25 import java.util.List;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
31 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
32 import org.opendaylight.mdsal.binding.model.api.Type;
33 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
34 import org.opendaylight.mdsal.binding.runtime.api.AugmentableRuntimeType;
35 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
36 import org.opendaylight.yangtools.yang.binding.Augmentable;
37 import org.opendaylight.yangtools.yang.binding.Augmentation;
38 import org.opendaylight.yangtools.yang.binding.BindingObject;
39 import org.opendaylight.yangtools.yang.binding.DataObject;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
47 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
48 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
56 public abstract sealed class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
57 extends AbstractDataObjectCodecContext<D, T> implements BindingDataObjectCodecTreeNode<D>
58 permits CaseCodecContext, ContainerLikeCodecContext, ListCodecContext, NotificationCodecContext {
59 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
61 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
62 AbstractDataObjectCodecContext.class, DataContainerNode.class);
63 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
64 DataObjectCodecContext.class, DataContainerNode.class);
65 private static final VarHandle MISMATCHED_AUGMENTED;
69 MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
70 "mismatchedAugmented", ImmutableMap.class);
71 } catch (NoSuchFieldException | IllegalAccessException e) {
72 throw new ExceptionInInitializerError(e);
76 private final ImmutableMap<Class<?>, AugmentationCodecPrototype> augmentToPrototype;
77 private final ImmutableMap<NodeIdentifier, Class<?>> yangToAugmentClass;
78 private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
79 private final MethodHandle proxyConstructor;
81 // Note this the content of this field depends only of invariants expressed as this class's fields or
82 // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
83 @SuppressWarnings("unused")
84 @SuppressFBWarnings(value = "URF_UNREAD_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
85 private volatile ImmutableMap<Class<?>, CommonDataObjectCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
87 DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype) {
88 this(prototype, CodecItemFactory.of());
91 DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final CodecItemFactory itemFactory) {
92 this(prototype, new DataContainerAnalysis<>(prototype, itemFactory), null);
95 DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype, final Method keyMethod) {
96 this(prototype, new DataContainerAnalysis<>(prototype, CodecItemFactory.of()), keyMethod);
99 private DataObjectCodecContext(final CommonDataObjectCodecPrototype<T> prototype,
100 final DataContainerAnalysis<T> analysis, final Method keyMethod) {
101 super(prototype, analysis);
103 final var bindingClass = getBindingClass();
105 // Final bits: generate the appropriate class, As a side effect we identify what Augmentations are possible
106 final List<AugmentRuntimeType> possibleAugmentations;
107 final var loader = prototype().contextFactory().getLoader();
108 if (Augmentable.class.isAssignableFrom(bindingClass)) {
109 // Verify we have the appropriate backing runtimeType
110 final var runtimeType = prototype.runtimeType();
111 if (!(runtimeType instanceof AugmentableRuntimeType augmentableRuntimeType)) {
112 throw new VerifyException(
113 "Unexpected type %s backing augmenable %s".formatted(runtimeType, bindingClass));
116 possibleAugmentations = augmentableRuntimeType.augments();
117 generatedClass = CodecDataObjectGenerator.generateAugmentable(loader, bindingClass, analysis.leafContexts,
118 analysis.daoProperties, keyMethod);
120 possibleAugmentations = List.of();
121 generatedClass = CodecDataObjectGenerator.generate(loader, bindingClass, analysis.leafContexts,
122 analysis.daoProperties, keyMethod);
125 // All done: acquire the constructor: it is supposed to be public
126 final MethodHandle ctor;
128 ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
129 } catch (NoSuchMethodException | IllegalAccessException e) {
130 throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
133 proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
135 // Deal with augmentations, which are not something we analysis provides
136 final var augPathToBinding = new HashMap<NodeIdentifier, Class<?>>();
137 final var augClassToProto = new HashMap<Class<?>, AugmentationCodecPrototype>();
138 for (var augment : possibleAugmentations) {
139 final var augProto = loadAugmentPrototype(augment);
140 if (augProto != null) {
141 final var augBindingClass = augProto.javaClass();
142 for (var childPath : augProto.getChildArgs()) {
143 augPathToBinding.putIfAbsent(childPath, augBindingClass);
145 augClassToProto.putIfAbsent(augBindingClass, augProto);
148 yangToAugmentClass = ImmutableMap.copyOf(augPathToBinding);
149 augmentToPrototype = ImmutableMap.copyOf(augClassToProto);
153 final DataContainerPrototype<?, ?> pathChildPrototype(final Class<? extends DataObject> argType) {
154 final var child = super.pathChildPrototype(argType);
155 return child != null ? child : augmentToPrototype.get(argType);
159 final DataContainerPrototype<?, ?> streamChildPrototype(final Class<?> childClass) {
160 final var child = super.streamChildPrototype(childClass);
161 if (child == null && Augmentation.class.isAssignableFrom(childClass)) {
162 return getAugmentationProtoByClass(childClass);
168 final CodecContextSupplier yangChildSupplier(final NodeIdentifier arg) {
169 final var child = super.yangChildSupplier(arg);
171 final var augClass = yangToAugmentClass.get(arg);
172 if (augClass != null) {
173 return augmentToPrototype.get(augClass);
179 private @Nullable AugmentationCodecPrototype getAugmentationProtoByClass(final @NonNull Class<?> augmClass) {
180 final var childProto = augmentToPrototype.get(augmClass);
181 return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
184 private @Nullable AugmentationCodecPrototype mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
186 * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
187 * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
188 * we'll cache it so we do not need to perform reflection operations again.
190 final var local = (ImmutableMap<Class<?>, AugmentationCodecPrototype>) MISMATCHED_AUGMENTED.getAcquire(this);
191 final var mismatched = local.get(childClass);
192 return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
195 private @Nullable AugmentationCodecPrototype loadMismatchedAugmentation(
196 final ImmutableMap<Class<?>, AugmentationCodecPrototype> oldMismatched,
197 final @NonNull Class<?> childClass) {
198 @SuppressWarnings("rawtypes")
199 final Class<?> augTarget = findAugmentationTarget((Class) childClass);
200 // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
201 // context would load.
202 if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
203 for (var realChild : augmentToPrototype.values()) {
204 final var realClass = realChild.javaClass();
205 if (Augmentation.class.isAssignableFrom(realClass) && isSubstitutionFor(childClass, realClass)) {
206 return cacheMismatched(oldMismatched, childClass, realChild);
210 LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
214 private @NonNull AugmentationCodecPrototype cacheMismatched(
215 final @NonNull ImmutableMap<Class<?>, AugmentationCodecPrototype> oldMismatched,
216 final @NonNull Class<?> childClass, final @NonNull AugmentationCodecPrototype prototype) {
217 var expected = oldMismatched;
219 final var newMismatched =
220 ImmutableMap.<Class<?>, CommonDataObjectCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
222 .put(childClass, prototype)
225 final var witness = (ImmutableMap<Class<?>, AugmentationCodecPrototype>)
226 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
227 if (witness == expected) {
228 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
233 final var existing = expected.get(childClass);
234 if (existing != null) {
235 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
241 private boolean belongsToRuntimeContext(final Class<?> cls) {
242 final var ctx = prototype().contextFactory().getRuntimeContext();
243 final Class<?> loaded;
245 loaded = ctx.loadClass(Type.of(cls));
246 } catch (ClassNotFoundException e) {
247 LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
250 return cls.equals(loaded);
253 private @Nullable AugmentationCodecPrototype loadAugmentPrototype(final AugmentRuntimeType augment) {
254 // FIXME: in face of deviations this code should be looking at declared view, i.e. all possibilities at augment
256 final var childPaths = augment.statement()
257 .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
258 .map(stmt -> new NodeIdentifier((QName) stmt.argument()))
259 .collect(ImmutableSet.toImmutableSet());
261 if (childPaths.isEmpty()) {
265 final var factory = prototype().contextFactory();
266 final GeneratedType javaType = augment.javaType();
267 final Class<? extends Augmentation<?>> augClass;
269 augClass = factory.getRuntimeContext().loadClass(javaType);
270 } catch (final ClassNotFoundException e) {
271 throw new IllegalStateException(
272 "RuntimeContext references type " + javaType + " but failed to load its class", e);
274 return new AugmentationCodecPrototype(augClass, augment, factory, childPaths);
278 @SuppressWarnings("unchecked")
279 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(final DataContainerNode data) {
281 * Due to augmentation fields are at same level as direct children the data of each augmentation needs to be
282 * aggregated into own container node, then only deserialized using associated prototype.
284 final var builders = new HashMap<Class<?>, DataContainerNodeBuilder>();
285 for (var childValue : data.body()) {
286 final var bindingClass = yangToAugmentClass.get(childValue.name());
287 if (bindingClass != null) {
288 builders.computeIfAbsent(bindingClass,
289 key -> Builders.containerBuilder()
290 .withNodeIdentifier(new NodeIdentifier(data.name().getNodeType())))
291 .addChild(childValue);
294 @SuppressWarnings("rawtypes")
295 final var map = new HashMap();
296 for (final var entry : builders.entrySet()) {
297 final var bindingClass = entry.getKey();
298 final var codecProto = augmentToPrototype.get(bindingClass);
299 if (codecProto != null) {
300 final var bindingObj = codecProto.getCodecContext().deserializeObject(entry.getValue().build());
301 if (bindingObj != null) {
302 map.put(bindingClass, bindingObj);
310 public InstanceIdentifier.PathArgument deserializePathArgument(final PathArgument arg) {
311 checkArgument(getDomPathArgument().equals(arg));
316 public PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
317 checkArgument(bindingArg().equals(arg));
318 return getDomPathArgument();
322 public NormalizedNode serialize(final D data) {
323 return serializeImpl(data);
327 public final BindingNormalizedNodeCachingCodec<D> createCachingCodec(
328 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
329 return createCachingCodec(this, cacheSpecifier);
332 final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
333 return generatedClass;
336 @SuppressWarnings("checkstyle:illegalCatch")
337 final @NonNull D createBindingProxy(final DataContainerNode node) {
339 return (D) proxyConstructor.invokeExact(this, node);
340 } catch (final Throwable e) {
341 Throwables.throwIfUnchecked(e);
342 throw new IllegalStateException(e);