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 java.lang.invoke.MethodHandle;
18 import java.lang.invoke.MethodHandles;
19 import java.lang.invoke.MethodType;
20 import java.lang.invoke.VarHandle;
21 import java.lang.reflect.Method;
22 import java.util.HashMap;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.Optional;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
30 import org.opendaylight.mdsal.binding.model.api.DefaultType;
31 import org.opendaylight.mdsal.binding.model.api.Type;
32 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
33 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
34 import org.opendaylight.yangtools.yang.binding.Augmentable;
35 import org.opendaylight.yangtools.yang.binding.Augmentation;
36 import org.opendaylight.yangtools.yang.binding.DataObject;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
39 import org.opendaylight.yangtools.yang.binding.OpaqueObject;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
46 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
54 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
62 public abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
63 extends DataContainerCodecContext<D, T> {
64 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
65 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
66 DataObjectCodecContext.class, DistinctNodeContainer.class);
67 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
68 DataObjectCodecContext.class, DistinctNodeContainer.class);
69 private static final VarHandle MISMATCHED_AUGMENTED;
73 MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
74 "mismatchedAugmented", ImmutableMap.class);
75 } catch (NoSuchFieldException | IllegalAccessException e) {
76 throw new ExceptionInInitializerError(e);
80 private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
81 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
82 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
83 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
84 private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> augmentationByYang;
85 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> augmentationByStream;
86 private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
87 private final MethodHandle proxyConstructor;
89 // Note this the content of this field depends only of invariants expressed as this class's fields or
90 // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
91 @SuppressWarnings("unused")
92 private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
94 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
95 this(prototype, null);
98 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
101 final Class<D> bindingClass = getBindingClass();
103 final ImmutableMap<Method, ValueNodeCodecContext> tmpLeaves = factory().getLeafNodes(bindingClass, getSchema());
104 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
106 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
107 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
108 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
110 // Adds leaves to mapping
111 final Builder<String, ValueNodeCodecContext> leafChildBuilder =
112 ImmutableMap.builderWithExpectedSize(tmpLeaves.size());
113 for (final Entry<Method, ValueNodeCodecContext> entry : tmpLeaves.entrySet()) {
114 final ValueNodeCodecContext leaf = entry.getValue();
115 leafChildBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
116 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
118 this.leafChild = leafChildBuilder.build();
120 final Map<Method, Class<?>> tmpDataObjects = new HashMap<>();
121 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
122 final Method method = childDataObj.getValue();
123 verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
125 final Class<?> retClass = childDataObj.getKey();
126 if (OpaqueObject.class.isAssignableFrom(retClass)) {
127 // Filter OpaqueObjects, they are not containers
131 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(retClass);
132 tmpDataObjects.put(method, childProto.getBindingClass());
133 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
134 byYangBuilder.put(childProto.getYangArg(), childProto);
135 if (childProto.isChoice()) {
136 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
137 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
138 byBindingArgClassBuilder.put(cazeChild, childProto);
143 this.byYang = ImmutableMap.copyOf(byYangBuilder);
144 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
146 // Slight footprint optimization: we do not want to copy byStreamClass, as that would force its entrySet view
147 // to be instantiated. Furthermore the two maps can easily end up being equal -- hence we can reuse
148 // byStreamClass for the purposes of both.
149 byBindingArgClassBuilder.putAll(byStreamClassBuilder);
150 this.byBindingArgClass = byStreamClassBuilder.equals(byBindingArgClassBuilder) ? this.byStreamClass
151 : ImmutableMap.copyOf(byBindingArgClassBuilder);
153 final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
154 if (Augmentable.class.isAssignableFrom(bindingClass)) {
155 possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
156 generatedClass = CodecDataObjectGenerator.generateAugmentable(prototype.getFactory().getLoader(),
157 bindingClass, tmpLeaves, tmpDataObjects, keyMethod);
159 possibleAugmentations = ImmutableMap.of();
160 generatedClass = CodecDataObjectGenerator.generate(prototype.getFactory().getLoader(), bindingClass,
161 tmpLeaves, tmpDataObjects, keyMethod);
164 // Iterate over all possible augmentations, indexing them as needed
165 final Map<PathArgument, DataContainerCodecPrototype<?>> augByYang = new HashMap<>();
166 final Map<Class<?>, DataContainerCodecPrototype<?>> augByStream = new HashMap<>();
167 for (final Type augment : possibleAugmentations.values()) {
168 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
169 final PathArgument augYangArg = augProto.getYangArg();
170 if (augByYang.putIfAbsent(augYangArg, augProto) == null) {
171 LOG.trace("Discovered new YANG mapping {} -> {} in {}", augYangArg, augProto, this);
173 final Class<?> augBindingClass = augProto.getBindingClass();
174 if (augByStream.putIfAbsent(augBindingClass, augProto) == null) {
175 LOG.trace("Discovered new class mapping {} -> {} in {}", augBindingClass, augProto, this);
178 augmentationByYang = ImmutableMap.copyOf(augByYang);
179 augmentationByStream = ImmutableMap.copyOf(augByStream);
181 final MethodHandle ctor;
183 ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
184 } catch (NoSuchMethodException | IllegalAccessException e) {
185 throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
188 proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
191 @SuppressWarnings("unchecked")
193 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
194 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
195 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
199 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
200 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
201 if (childProto != null) {
204 if (Augmentation.class.isAssignableFrom(childClass)) {
205 return augmentationByClass(childClass);
210 @SuppressWarnings("unchecked")
212 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
213 final Class<C> childClass) {
214 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
215 if (childProto != null) {
216 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
218 return Optional.empty();
222 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
223 final List<YangInstanceIdentifier.PathArgument> builder) {
225 final Class<? extends DataObject> argType = arg.getType();
226 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
227 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
228 ctxProto = augmentationByClass(argType);
230 final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
231 "Class %s is not valid child of %s", argType, getBindingClass()).get();
232 if (context instanceof ChoiceNodeCodecContext) {
233 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
234 choice.addYangPathArgument(arg, builder);
236 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
237 final Class<? extends DataObject> type = arg.getType();
238 final DataContainerCodecContext<?, ?> caze;
239 if (caseType.isPresent()) {
240 // Non-ambiguous addressing this should not pose any problems
241 caze = choice.streamChild(caseType.get());
243 caze = choice.getCaseByChildClass(type);
246 caze.addYangPathArgument(arg, builder);
247 return caze.bindingPathArgumentChild(arg, builder);
249 context.addYangPathArgument(arg, builder);
254 public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
255 final NodeContextSupplier childSupplier;
256 if (arg instanceof NodeIdentifierWithPredicates) {
257 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
258 } else if (arg instanceof AugmentationIdentifier) {
259 childSupplier = augmentationByYang.get(arg);
261 childSupplier = byYang.get(arg);
264 return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
267 protected final ValueNodeCodecContext getLeafChild(final String name) {
268 final ValueNodeCodecContext value = leafChild.get(name);
270 throw IncorrectNestingException.create("Leaf %s is not valid for %s", name, getBindingClass());
275 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
276 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
277 // Direct instantiation or use in same module in which grouping
279 DataSchemaNode sameName;
281 sameName = getSchema().dataChildByName(origDef.getQName());
282 } catch (final IllegalArgumentException e) {
283 LOG.trace("Failed to find schema for {}", origDef, e);
286 final DataSchemaNode childSchema;
287 if (sameName != null) {
289 // - exactly same schema node, or
290 // - instantiated node was added via uses statement and is instantiation of same grouping
291 if (origDef.equals(sameName) || origDef.equals(getRootOriginalIfPossible(sameName))) {
292 childSchema = sameName;
294 // Node has same name, but clearly is different
298 // We are looking for instantiation via uses in other module
299 final QName instantiedName = origDef.getQName().bindTo(namespace());
300 final DataSchemaNode potential = getSchema().dataChildByName(instantiedName);
301 // We check if it is really instantiated from same definition as class was derived
302 if (potential != null && origDef.equals(getRootOriginalIfPossible(potential))) {
303 childSchema = potential;
308 final DataSchemaNode nonNullChild =
309 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
310 return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
313 private static SchemaNode getRootOriginalIfPossible(final SchemaNode data) {
314 Optional<SchemaNode> previous = Optional.empty();
315 Optional<SchemaNode> next = getOriginalIfPossible(data);
316 while (next.isPresent()) {
318 next = getOriginalIfPossible(next.get());
320 return previous.orElse(null);
323 private static Optional<SchemaNode> getOriginalIfPossible(final SchemaNode node) {
324 if (node instanceof DerivableSchemaNode) {
325 @SuppressWarnings("unchecked")
326 final Optional<SchemaNode> ret = (Optional<SchemaNode>) ((DerivableSchemaNode) node).getOriginal();
329 return Optional.empty();
332 @SuppressWarnings("unchecked")
333 Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
334 return Item.of((Class<? extends DataObject>) childClass);
337 private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
338 final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
339 return childProto != null ? childProto : mismatchedAugmentationByClass(childClass);
342 private @Nullable DataContainerCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
344 * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
345 * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
346 * we'll cache it so we do not need to perform reflection operations again.
348 final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local =
349 (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
350 final DataContainerCodecPrototype<?> mismatched = local.get(childClass);
351 return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
355 private @Nullable DataContainerCodecPrototype<?> loadMismatchedAugmentation(
356 final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
357 final @NonNull Class<?> childClass) {
358 @SuppressWarnings("rawtypes")
359 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
360 // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
361 // context would load.
362 if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
363 for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
364 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
365 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
366 return cacheMismatched(oldMismatched, childClass, realChild);
370 LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
374 private @NonNull DataContainerCodecPrototype<?> cacheMismatched(
375 final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
376 final @NonNull Class<?> childClass, final @NonNull DataContainerCodecPrototype<?> prototype) {
378 ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> expected = oldMismatched;
380 final Map<Class<?>, DataContainerCodecPrototype<?>> newMismatched =
381 ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
383 .put(childClass, prototype)
386 final Object witness = MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
387 if (witness == expected) {
388 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
392 expected = (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) witness;
393 final DataContainerCodecPrototype<?> existing = expected.get(childClass);
394 if (existing != null) {
395 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
401 private boolean belongsToRuntimeContext(final Class<?> cls) {
402 final BindingRuntimeContext ctx = factory().getRuntimeContext();
403 final Class<?> loaded;
405 loaded = ctx.loadClass(DefaultType.of(cls));
406 } catch (ClassNotFoundException e) {
407 LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
410 return cls.equals(loaded);
413 private @NonNull DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
414 final BindingRuntimeContext ctx = factory().getRuntimeContext();
416 final Class<? extends Augmentation<?>> augClass;
418 augClass = ctx.loadClass(value);
419 } catch (final ClassNotFoundException e) {
420 throw new IllegalStateException("RuntimeContext references type " + value + " but failed to its class", e);
423 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema =
424 ctx.getResolvedAugmentationSchema(getSchema(), augClass);
425 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
428 @SuppressWarnings("checkstyle:illegalCatch")
429 protected final @NonNull D createBindingProxy(final DistinctNodeContainer<?, ?> node) {
431 return (D) proxyConstructor.invokeExact(this, node);
432 } catch (final Throwable e) {
433 Throwables.throwIfUnchecked(e);
434 throw new IllegalStateException(e);
438 @SuppressWarnings("unchecked")
439 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
440 final DistinctNodeContainer<PathArgument, NormalizedNode> data) {
442 @SuppressWarnings("rawtypes")
443 final Map map = new HashMap<>();
445 for (final NormalizedNode childValue : data.body()) {
446 if (childValue instanceof AugmentationNode) {
447 final AugmentationNode augDomNode = (AugmentationNode) childValue;
448 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
449 if (codecProto != null) {
450 final DataContainerCodecContext<?, ?> codec = codecProto.get();
451 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
455 for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
456 final NormalizedNode augData = data.childByArg(value.getYangArg());
457 if (augData != null) {
458 map.put(value.getBindingClass(), value.get().deserializeObject(augData));
464 final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
465 return generatedClass;
469 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
470 checkArgument(getDomPathArgument().equals(arg));
475 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
476 checkArgument(bindingArg().equals(arg));
477 return getDomPathArgument();