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.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;
47 * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
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);
55 private static final VarHandle MISMATCHED_AUGMENTED;
59 MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
60 "mismatchedAugmented", ImmutableMap.class);
61 } catch (NoSuchFieldException | IllegalAccessException e) {
62 throw new ExceptionInInitializerError(e);
66 private final ImmutableMap<Class<?>, AugmentationCodecPrototype> augmentToPrototype;
67 private final ImmutableMap<NodeIdentifier, Class<?>> yangToAugmentClass;
68 private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
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();
75 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
76 this(prototype, CodecItemFactory.of());
79 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final CodecItemFactory itemFactory) {
80 this(prototype, new CodecDataObjectAnalysis<>(prototype, itemFactory, null));
83 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
84 this(prototype, new CodecDataObjectAnalysis<>(prototype, CodecItemFactory.of(), keyMethod));
87 private DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype,
88 final CodecDataObjectAnalysis<T> analysis) {
89 super(prototype, analysis);
91 // Inherit analysis stuff
92 generatedClass = analysis.generatedClass;
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);
104 augClassToProto.putIfAbsent(augBindingClass, augProto);
107 yangToAugmentClass = ImmutableMap.copyOf(augPathToBinding);
108 augmentToPrototype = ImmutableMap.copyOf(augClassToProto);
112 final DataContainerCodecPrototype<?> pathChildPrototype(final Class<? extends DataObject> argType) {
113 final var child = super.pathChildPrototype(argType);
114 return child != null ? child : augmentToPrototype.get(argType);
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);
127 final CodecContextSupplier yangChildSupplier(final NodeIdentifier arg) {
128 final var child = super.yangChildSupplier(arg);
130 final var augClass = yangToAugmentClass.get(arg);
131 if (augClass != null) {
132 return augmentToPrototype.get(augClass);
138 private @Nullable AugmentationCodecPrototype getAugmentationProtoByClass(final @NonNull Class<?> augmClass) {
139 final var childProto = augmentToPrototype.get(augmClass);
140 return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
143 private @Nullable AugmentationCodecPrototype mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
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.
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);
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);
169 LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
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;
178 final var newMismatched =
179 ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
181 .put(childClass, prototype)
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);
192 final var existing = expected.get(childClass);
193 if (existing != null) {
194 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
200 private boolean belongsToRuntimeContext(final Class<?> cls) {
201 final BindingRuntimeContext ctx = factory().getRuntimeContext();
202 final Class<?> loaded;
204 loaded = ctx.loadClass(Type.of(cls));
205 } catch (ClassNotFoundException e) {
206 LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
209 return cls.equals(loaded);
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
215 final var childPaths = augment.statement()
216 .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
217 .map(stmt -> new NodeIdentifier((QName) stmt.argument()))
218 .collect(ImmutableSet.toImmutableSet());
220 final var it = childPaths.iterator();
224 final var namespace = it.next().getNodeType().getModule();
226 final var factory = factory();
227 final GeneratedType javaType = augment.javaType();
228 final Class<? extends Augmentation<?>> augClass;
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);
235 return new AugmentationCodecPrototype(augClass, namespace, augment, factory, childPaths);
239 @SuppressWarnings("unchecked")
240 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(final DataContainerNode data) {
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.
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);
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()));
267 final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
268 return generatedClass;
272 public InstanceIdentifier.PathArgument deserializePathArgument(final PathArgument arg) {
273 checkArgument(getDomPathArgument().equals(arg));
278 public PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
279 checkArgument(bindingArg().equals(arg));
280 return getDomPathArgument();
284 public NormalizedNode serialize(final D data) {
285 return serializeImpl(data);
289 public final BindingNormalizedNodeCachingCodec<D> createCachingCodec(
290 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
291 return createCachingCodec(this, cacheSpecifier);