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;
11 import static com.google.common.base.Verify.verify;
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableMap.Builder;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Iterables;
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 java.util.Map.Entry;
28 import java.util.Optional;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
32 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
33 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
34 import org.opendaylight.mdsal.binding.model.api.Type;
35 import org.opendaylight.mdsal.binding.runtime.api.AugmentRuntimeType;
36 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
37 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
38 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
39 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
40 import org.opendaylight.yangtools.yang.binding.Augmentable;
41 import org.opendaylight.yangtools.yang.binding.Augmentation;
42 import org.opendaylight.yangtools.yang.binding.DataContainer;
43 import org.opendaylight.yangtools.yang.binding.DataObject;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
46 import org.opendaylight.yangtools.yang.binding.OpaqueObject;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
52 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
56 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
57 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
62 * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
65 public abstract class DataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
66 extends DataContainerCodecContext<D, T> {
67 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
68 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
69 DataObjectCodecContext.class, DistinctNodeContainer.class);
70 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
71 DataObjectCodecContext.class, DistinctNodeContainer.class);
72 private static final VarHandle MISMATCHED_AUGMENTED;
76 MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
77 "mismatchedAugmented", ImmutableMap.class);
78 } catch (NoSuchFieldException | IllegalAccessException e) {
79 throw new ExceptionInInitializerError(e);
83 private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
84 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
85 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
86 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
87 private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> augmentationByYang;
88 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> augmentationByStream;
89 private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
90 private final MethodHandle proxyConstructor;
92 // Note this the content of this field depends only of invariants expressed as this class's fields or
93 // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
94 @SuppressWarnings("unused")
95 private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
97 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
98 this(prototype, null);
101 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
104 final Class<D> bindingClass = getBindingClass();
106 final ImmutableMap<Method, ValueNodeCodecContext> tmpLeaves = factory().getLeafNodes(bindingClass,
107 getType().statement());
108 final Map<Class<? extends DataContainer>, Method> clsToMethod =
109 BindingReflections.getChildrenClassToMethod(bindingClass);
111 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
112 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
113 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
115 // Adds leaves to mapping
116 final Builder<String, ValueNodeCodecContext> leafChildBuilder =
117 ImmutableMap.builderWithExpectedSize(tmpLeaves.size());
118 for (final ValueNodeCodecContext leaf : tmpLeaves.values()) {
119 leafChildBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
120 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
122 this.leafChild = leafChildBuilder.build();
124 final Map<Method, Class<?>> tmpDataObjects = new HashMap<>();
125 for (final Entry<Class<? extends DataContainer>, Method> childDataObj : clsToMethod.entrySet()) {
126 final Method method = childDataObj.getValue();
127 verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
129 final Class<? extends DataContainer> retClass = childDataObj.getKey();
130 if (OpaqueObject.class.isAssignableFrom(retClass)) {
131 // Filter OpaqueObjects, they are not containers
135 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(retClass);
136 final Class<?> childClass = childProto.getBindingClass();
137 tmpDataObjects.put(method, childClass);
138 byStreamClassBuilder.put(childClass, childProto);
139 byYangBuilder.put(childProto.getYangArg(), childProto);
141 // FIXME: It really feels like we should be specializing DataContainerCodecPrototype so as to ditch
142 // createInstance() and then we could do an instanceof check instead.
143 if (childProto.getType() instanceof ChoiceRuntimeType) {
144 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
145 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
146 byBindingArgClassBuilder.put(cazeChild, childProto);
151 this.byYang = ImmutableMap.copyOf(byYangBuilder);
152 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
154 // Slight footprint optimization: we do not want to copy byStreamClass, as that would force its entrySet view
155 // to be instantiated. Furthermore the two maps can easily end up being equal -- hence we can reuse
156 // byStreamClass for the purposes of both.
157 byBindingArgClassBuilder.putAll(byStreamClassBuilder);
158 this.byBindingArgClass = byStreamClassBuilder.equals(byBindingArgClassBuilder) ? this.byStreamClass
159 : ImmutableMap.copyOf(byBindingArgClassBuilder);
161 final Iterable<AugmentRuntimeType> possibleAugmentations;
162 if (Augmentable.class.isAssignableFrom(bindingClass)) {
163 final var type = getType();
164 possibleAugmentations = Iterables.concat(type.augments(), type.mismatchedAugments());
165 generatedClass = CodecDataObjectGenerator.generateAugmentable(prototype.getFactory().getLoader(),
166 bindingClass, tmpLeaves, tmpDataObjects, keyMethod);
168 possibleAugmentations = List.of();
169 generatedClass = CodecDataObjectGenerator.generate(prototype.getFactory().getLoader(), bindingClass,
170 tmpLeaves, tmpDataObjects, keyMethod);
173 // Iterate over all possible augmentations, indexing them as needed
174 final Map<PathArgument, DataContainerCodecPrototype<?>> augByYang = new HashMap<>();
175 final Map<Class<?>, DataContainerCodecPrototype<?>> augByStream = new HashMap<>();
176 for (final AugmentRuntimeType augment : possibleAugmentations) {
177 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
178 final PathArgument augYangArg = augProto.getYangArg();
179 if (augByYang.putIfAbsent(augYangArg, augProto) == null) {
180 LOG.trace("Discovered new YANG mapping {} -> {} in {}", augYangArg, augProto, this);
182 final Class<?> augBindingClass = augProto.getBindingClass();
183 if (augByStream.putIfAbsent(augBindingClass, augProto) == null) {
184 LOG.trace("Discovered new class mapping {} -> {} in {}", augBindingClass, augProto, this);
187 augmentationByYang = ImmutableMap.copyOf(augByYang);
188 augmentationByStream = ImmutableMap.copyOf(augByStream);
190 final MethodHandle ctor;
192 ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
193 } catch (NoSuchMethodException | IllegalAccessException e) {
194 throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
197 proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
201 public final WithStatus getSchema() {
202 // FIXME: Bad cast, we should be returning an EffectiveStatement perhaps?
203 return (WithStatus) getType().statement();
207 @SuppressWarnings("unchecked")
208 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
209 return (DataContainerCodecContext<C, ?>) childNonNull(streamChildPrototype(childClass), childClass,
210 "Child %s is not valid child of %s", getBindingClass(), childClass).get();
213 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
214 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
215 if (childProto != null) {
218 if (Augmentation.class.isAssignableFrom(childClass)) {
219 return augmentationByClass(childClass);
224 @SuppressWarnings("unchecked")
226 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
227 final Class<C> childClass) {
228 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
229 if (childProto != null) {
230 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
232 return Optional.empty();
236 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
237 final List<YangInstanceIdentifier.PathArgument> builder) {
239 final Class<? extends DataObject> argType = arg.getType();
240 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
241 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
242 ctxProto = augmentationByClass(argType);
244 final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
245 "Class %s is not valid child of %s", argType, getBindingClass()).get();
246 if (context instanceof ChoiceNodeCodecContext) {
247 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
248 choice.addYangPathArgument(arg, builder);
250 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
251 final Class<? extends DataObject> type = arg.getType();
252 final DataContainerCodecContext<?, ?> caze;
253 if (caseType.isPresent()) {
254 // Non-ambiguous addressing this should not pose any problems
255 caze = choice.streamChild(caseType.get());
257 caze = choice.getCaseByChildClass(type);
260 caze.addYangPathArgument(arg, builder);
261 return caze.bindingPathArgumentChild(arg, builder);
263 context.addYangPathArgument(arg, builder);
268 public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
269 final NodeContextSupplier childSupplier;
270 if (arg instanceof NodeIdentifierWithPredicates) {
271 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
272 } else if (arg instanceof AugmentationIdentifier) {
273 childSupplier = augmentationByYang.get(arg);
275 childSupplier = byYang.get(arg);
278 return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
281 protected final ValueNodeCodecContext getLeafChild(final String name) {
282 final ValueNodeCodecContext value = leafChild.get(name);
284 throw IncorrectNestingException.create("Leaf %s is not valid for %s", name, getBindingClass());
289 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<? extends DataContainer> childClass) {
290 final var type = getType();
291 final var child = childNonNull(type.bindingChild(JavaTypeName.create(childClass)), childClass,
292 "Node %s does not have child named %s", type, childClass);
294 return DataContainerCodecPrototype.from(createBindingArg(childClass, child.statement()),
295 (CompositeRuntimeType) child, factory());
298 // FIXME: MDSAL-697: move this method into BindingRuntimeContext
299 // This method is only called from loadChildPrototype() and exists only to be overridden by
300 // CaseNodeCodecContext. Since we are providing childClass and our schema to BindingRuntimeContext
301 // and receiving childSchema from it via findChildSchemaDefinition, we should be able to receive
302 // the equivalent of Map.Entry<Item, DataSchemaNode>, along with the override we create here. One
303 // more input we may need to provide is our bindingClass().
304 @SuppressWarnings("unchecked")
305 Item<?> createBindingArg(final Class<?> childClass, final EffectiveStatement<?, ?> childSchema) {
306 return Item.of((Class<? extends DataObject>) childClass);
309 private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
310 final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
311 return childProto != null ? childProto : mismatchedAugmentationByClass(childClass);
314 private @Nullable DataContainerCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
316 * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
317 * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
318 * we'll cache it so we do not need to perform reflection operations again.
320 final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local =
321 (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
322 final DataContainerCodecPrototype<?> mismatched = local.get(childClass);
323 return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
327 private @Nullable DataContainerCodecPrototype<?> loadMismatchedAugmentation(
328 final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
329 final @NonNull Class<?> childClass) {
330 @SuppressWarnings("rawtypes")
331 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
332 // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
333 // context would load.
334 if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
335 for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
336 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
337 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
338 return cacheMismatched(oldMismatched, childClass, realChild);
342 LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
346 private @NonNull DataContainerCodecPrototype<?> cacheMismatched(
347 final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
348 final @NonNull Class<?> childClass, final @NonNull DataContainerCodecPrototype<?> prototype) {
350 ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> expected = oldMismatched;
352 final Map<Class<?>, DataContainerCodecPrototype<?>> newMismatched =
353 ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
355 .put(childClass, prototype)
358 final var witness = (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>)
359 MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
360 if (witness == expected) {
361 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
366 final DataContainerCodecPrototype<?> existing = expected.get(childClass);
367 if (existing != null) {
368 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
374 private boolean belongsToRuntimeContext(final Class<?> cls) {
375 final BindingRuntimeContext ctx = factory().getRuntimeContext();
376 final Class<?> loaded;
378 loaded = ctx.loadClass(Type.of(cls));
379 } catch (ClassNotFoundException e) {
380 LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
383 return cls.equals(loaded);
386 private @NonNull DataContainerCodecPrototype<?> getAugmentationPrototype(final AugmentRuntimeType augment) {
387 final BindingRuntimeContext ctx = factory().getRuntimeContext();
389 final GeneratedType javaType = augment.javaType();
390 final Class<? extends Augmentation<?>> augClass;
392 augClass = ctx.loadClass(javaType);
393 } catch (final ClassNotFoundException e) {
394 throw new IllegalStateException(
395 "RuntimeContext references type " + javaType + " but failed to load its class", e);
398 // TODO: at some point we need the effective children
399 return DataContainerCodecPrototype.from(augClass, new AugmentationIdentifier(augment.statement()
400 .streamEffectiveSubstatements(SchemaTreeEffectiveStatement.class)
401 .map(SchemaTreeEffectiveStatement::getIdentifier)
402 .collect(ImmutableSet.toImmutableSet())), augment, factory());
405 @SuppressWarnings("checkstyle:illegalCatch")
406 protected final @NonNull D createBindingProxy(final DistinctNodeContainer<?, ?> node) {
408 return (D) proxyConstructor.invokeExact(this, node);
409 } catch (final Throwable e) {
410 Throwables.throwIfUnchecked(e);
411 throw new IllegalStateException(e);
415 @SuppressWarnings("unchecked")
416 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
417 final DistinctNodeContainer<PathArgument, NormalizedNode> data) {
419 @SuppressWarnings("rawtypes")
420 final Map map = new HashMap<>();
422 for (final NormalizedNode childValue : data.body()) {
423 if (childValue instanceof AugmentationNode) {
424 final AugmentationNode augDomNode = (AugmentationNode) childValue;
425 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
426 if (codecProto != null) {
427 final DataContainerCodecContext<?, ?> codec = codecProto.get();
428 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
432 for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
433 final var augClass = value.getBindingClass();
434 // Do not perform duplicate deserialization if we have already created the corresponding augmentation
435 // and validate whether the proposed augmentation is valid ion this instantiation context.
436 if (!map.containsKey(augClass) && getType().augments().contains(value.getType())) {
437 final NormalizedNode augData = data.childByArg(value.getYangArg());
438 if (augData != null) {
439 // ... make sure we do not replace an e
440 map.putIfAbsent(augClass, value.get().deserializeObject(augData));
447 final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
448 return generatedClass;
452 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
453 checkArgument(getDomPathArgument().equals(arg));
458 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
459 checkArgument(bindingArg().equals(arg));
460 return getDomPathArgument();