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.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;
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;
46 * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
49 public abstract sealed class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
50 extends AbstractDataObjectCodecContext<D, T> implements BindingDataObjectCodecTreeNode<D>
51 permits CaseNodeCodecContext, ContainerNodeCodecContext, ListNodeCodecContext, NotificationCodecContext {
52 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
54 private static final VarHandle MISMATCHED_AUGMENTED;
58 MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
59 "mismatchedAugmented", ImmutableMap.class);
60 } catch (NoSuchFieldException | IllegalAccessException e) {
61 throw new ExceptionInInitializerError(e);
65 private final ImmutableMap<Class<?>, AugmentationCodecPrototype> augmentToPrototype;
66 private final ImmutableMap<NodeIdentifier, Class<?>> yangToAugmentClass;
67 private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
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();
74 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
75 this(prototype, CodecItemFactory.of());
78 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final CodecItemFactory itemFactory) {
79 this(prototype, new CodecDataObjectAnalysis<>(prototype, itemFactory, null));
82 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
83 this(prototype, new CodecDataObjectAnalysis<>(prototype, CodecItemFactory.of(), keyMethod));
86 private DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype,
87 final CodecDataObjectAnalysis<T> analysis) {
88 super(prototype, analysis);
90 // Inherit analysis stuff
91 generatedClass = analysis.generatedClass;
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);
103 augClassToProto.putIfAbsent(augBindingClass, augProto);
106 yangToAugmentClass = ImmutableMap.copyOf(augPathToBinding);
107 augmentToPrototype = ImmutableMap.copyOf(augClassToProto);
111 final DataContainerCodecPrototype<?> pathChildPrototype(final Class<? extends DataObject> argType) {
112 final var child = super.pathChildPrototype(argType);
113 return child != null ? child : augmentToPrototype.get(argType);
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);
126 final CodecContextSupplier yangChildSupplier(final NodeIdentifier arg) {
127 final var child = super.yangChildSupplier(arg);
129 final var augClass = yangToAugmentClass.get(arg);
130 if (augClass != null) {
131 return augmentToPrototype.get(augClass);
137 private @Nullable AugmentationCodecPrototype getAugmentationProtoByClass(final @NonNull Class<?> augmClass) {
138 final var childProto = augmentToPrototype.get(augmClass);
139 return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
142 private @Nullable AugmentationCodecPrototype mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
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.
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);
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);
168 LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
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;
177 final var newMismatched =
178 ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
180 .put(childClass, prototype)
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);
191 final var existing = expected.get(childClass);
192 if (existing != null) {
193 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
199 private boolean belongsToRuntimeContext(final Class<?> cls) {
200 final BindingRuntimeContext ctx = factory().getRuntimeContext();
201 final Class<?> loaded;
203 loaded = ctx.loadClass(Type.of(cls));
204 } catch (ClassNotFoundException e) {
205 LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
208 return cls.equals(loaded);
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
214 final var childPaths = augment.statement()
215 .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
216 .map(stmt -> new NodeIdentifier((QName) stmt.argument()))
217 .collect(ImmutableSet.toImmutableSet());
219 final var it = childPaths.iterator();
223 final var namespace = it.next().getNodeType().getModule();
225 final var factory = factory();
226 final GeneratedType javaType = augment.javaType();
227 final Class<? extends Augmentation<?>> augClass;
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);
234 return new AugmentationCodecPrototype(augClass, namespace, augment, factory, childPaths);
238 @SuppressWarnings("unchecked")
239 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(final DataContainerNode data) {
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.
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);
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);
269 final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
270 return generatedClass;
274 public InstanceIdentifier.PathArgument deserializePathArgument(final PathArgument arg) {
275 checkArgument(getDomPathArgument().equals(arg));
280 public PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
281 checkArgument(bindingArg().equals(arg));
282 return getDomPathArgument();
286 public NormalizedNode serialize(final D data) {
287 return serializeImpl(data);
291 public final BindingNormalizedNodeCachingCodec<D> createCachingCodec(
292 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
293 return createCachingCodec(this, cacheSpecifier);