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 class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
51 extends AbstractDataObjectCodecContext<D, T> implements BindingDataObjectCodecTreeNode<D> {
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<?>, DataContainerCodecPrototype.Augmentation> 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<?>, DataContainerCodecPrototype.Augmentation>();
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 NodeContextSupplier 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 DataContainerCodecPrototype.@Nullable Augmentation getAugmentationProtoByClass(
138 final @NonNull Class<?> augmClass) {
139 final var childProto = augmentToPrototype.get(augmClass);
140 return childProto != null ? childProto : mismatchedAugmentationByClass(augmClass);
143 private DataContainerCodecPrototype.@Nullable Augmentation mismatchedAugmentationByClass(
144 final @NonNull Class<?> childClass) {
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.
151 (ImmutableMap<Class<?>, DataContainerCodecPrototype.Augmentation>) MISMATCHED_AUGMENTED.getAcquire(this);
152 final var mismatched = local.get(childClass);
153 return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
156 private DataContainerCodecPrototype.@Nullable Augmentation loadMismatchedAugmentation(
157 final ImmutableMap<Class<?>, DataContainerCodecPrototype.Augmentation> oldMismatched,
158 final @NonNull Class<?> childClass) {
159 @SuppressWarnings("rawtypes")
160 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
161 // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
162 // context would load.
163 if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
164 for (var realChild : augmentToPrototype.values()) {
165 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
166 && isSubstitutionFor(childClass, realChild.getBindingClass())) {
167 return cacheMismatched(oldMismatched, childClass, realChild);
171 LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
175 private DataContainerCodecPrototype.@NonNull Augmentation cacheMismatched(
176 final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype.Augmentation> oldMismatched,
177 final @NonNull Class<?> childClass, final DataContainerCodecPrototype.@NonNull Augmentation prototype) {
179 var expected = oldMismatched;
181 final var newMismatched =
182 ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
184 .put(childClass, prototype)
187 final var witness = (ImmutableMap<Class<?>, DataContainerCodecPrototype.Augmentation>)
188 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
189 if (witness == expected) {
190 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
195 final var existing = expected.get(childClass);
196 if (existing != null) {
197 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
203 private boolean belongsToRuntimeContext(final Class<?> cls) {
204 final BindingRuntimeContext ctx = factory().getRuntimeContext();
205 final Class<?> loaded;
207 loaded = ctx.loadClass(Type.of(cls));
208 } catch (ClassNotFoundException e) {
209 LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
212 return cls.equals(loaded);
215 private DataContainerCodecPrototype.@Nullable Augmentation loadAugmentPrototype(final AugmentRuntimeType augment) {
216 // FIXME: in face of deviations this code should be looking at declared view, i.e. all possibilities at augment
218 final var childPaths = augment.statement()
219 .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
220 .map(stmt -> new NodeIdentifier((QName) stmt.argument()))
221 .collect(ImmutableSet.toImmutableSet());
223 final var it = childPaths.iterator();
227 final var namespace = it.next().getNodeType().getModule();
229 final var factory = factory();
230 final GeneratedType javaType = augment.javaType();
231 final Class<? extends Augmentation<?>> augClass;
233 augClass = factory.getRuntimeContext().loadClass(javaType);
234 } catch (final ClassNotFoundException e) {
235 throw new IllegalStateException(
236 "RuntimeContext references type " + javaType + " but failed to load its class", e);
238 return new DataContainerCodecPrototype.Augmentation(augClass, namespace, augment, factory, childPaths);
242 @SuppressWarnings("unchecked")
243 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(final DataContainerNode data) {
245 * Due to augmentation fields are at same level as direct children the data of each augmentation needs to be
246 * aggregated into own container node, then only deserialized using associated prototype.
248 final var builders = new HashMap<Class<?>, DataContainerNodeBuilder>();
249 for (var childValue : data.body()) {
250 final var bindingClass = yangToAugmentClass.get(childValue.name());
251 if (bindingClass != null) {
252 builders.computeIfAbsent(bindingClass,
253 key -> Builders.containerBuilder()
254 .withNodeIdentifier(new NodeIdentifier(data.name().getNodeType())))
255 .addChild(childValue);
258 @SuppressWarnings("rawtypes")
259 final var map = new HashMap();
260 for (final var entry : builders.entrySet()) {
261 final var bindingClass = entry.getKey();
262 final var codecProto = augmentToPrototype.get(bindingClass);
263 if (codecProto != null) {
264 map.put(bindingClass, codecProto.get().deserializeObject(entry.getValue().build()));
270 final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
271 return generatedClass;
275 public InstanceIdentifier.PathArgument deserializePathArgument(final PathArgument arg) {
276 checkArgument(getDomPathArgument().equals(arg));
281 public PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
282 checkArgument(bindingArg().equals(arg));
283 return getDomPathArgument();
287 public NormalizedNode serialize(final D data) {
288 return serializeImpl(data);
292 public final BindingNormalizedNodeCachingCodec<D> createCachingCodec(
293 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
294 return createCachingCodec(this, cacheSpecifier);