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.Type;
31 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
32 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
33 import org.opendaylight.yangtools.yang.binding.Augmentable;
34 import org.opendaylight.yangtools.yang.binding.Augmentation;
35 import org.opendaylight.yangtools.yang.binding.DataContainer;
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.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
59 public abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
60 extends DataContainerCodecContext<D, T> {
61 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
62 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
63 DataObjectCodecContext.class, DistinctNodeContainer.class);
64 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
65 DataObjectCodecContext.class, DistinctNodeContainer.class);
66 private static final VarHandle MISMATCHED_AUGMENTED;
70 MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
71 "mismatchedAugmented", ImmutableMap.class);
72 } catch (NoSuchFieldException | IllegalAccessException e) {
73 throw new ExceptionInInitializerError(e);
77 private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
78 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
79 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
80 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
81 private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> augmentationByYang;
82 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> augmentationByStream;
83 private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
84 private final MethodHandle proxyConstructor;
86 // Note this the content of this field depends only of invariants expressed as this class's fields or
87 // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
88 @SuppressWarnings("unused")
89 private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
91 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
92 this(prototype, null);
95 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
98 final Class<D> bindingClass = getBindingClass();
100 final ImmutableMap<Method, ValueNodeCodecContext> tmpLeaves = factory().getLeafNodes(bindingClass, getSchema());
101 final Map<Class<? extends DataContainer>, Method> clsToMethod =
102 BindingReflections.getChildrenClassToMethod(bindingClass);
104 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
105 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
106 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
108 // Adds leaves to mapping
109 final Builder<String, ValueNodeCodecContext> leafChildBuilder =
110 ImmutableMap.builderWithExpectedSize(tmpLeaves.size());
111 for (final ValueNodeCodecContext leaf : tmpLeaves.values()) {
112 leafChildBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
113 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
115 this.leafChild = leafChildBuilder.build();
117 final Map<Method, Class<?>> tmpDataObjects = new HashMap<>();
118 for (final Entry<Class<? extends DataContainer>, Method> childDataObj : clsToMethod.entrySet()) {
119 final Method method = childDataObj.getValue();
120 verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
122 final Class<? extends DataContainer> retClass = childDataObj.getKey();
123 if (OpaqueObject.class.isAssignableFrom(retClass)) {
124 // Filter OpaqueObjects, they are not containers
128 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(retClass);
129 final Class<?> childClass = childProto.getBindingClass();
130 tmpDataObjects.put(method, childClass);
131 byStreamClassBuilder.put(childClass, childProto);
132 byYangBuilder.put(childProto.getYangArg(), childProto);
134 // FIXME: It really feels like we should be specializing DataContainerCodecPrototype so as to ditch
135 // createInstance() and then we could do an instanceof check instead.
136 if (childProto.isChoice()) {
137 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
138 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
139 byBindingArgClassBuilder.put(cazeChild, childProto);
144 this.byYang = ImmutableMap.copyOf(byYangBuilder);
145 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
147 // Slight footprint optimization: we do not want to copy byStreamClass, as that would force its entrySet view
148 // to be instantiated. Furthermore the two maps can easily end up being equal -- hence we can reuse
149 // byStreamClass for the purposes of both.
150 byBindingArgClassBuilder.putAll(byStreamClassBuilder);
151 this.byBindingArgClass = byStreamClassBuilder.equals(byBindingArgClassBuilder) ? this.byStreamClass
152 : ImmutableMap.copyOf(byBindingArgClassBuilder);
154 final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
155 if (Augmentable.class.isAssignableFrom(bindingClass)) {
156 possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
157 generatedClass = CodecDataObjectGenerator.generateAugmentable(prototype.getFactory().getLoader(),
158 bindingClass, tmpLeaves, tmpDataObjects, keyMethod);
160 possibleAugmentations = ImmutableMap.of();
161 generatedClass = CodecDataObjectGenerator.generate(prototype.getFactory().getLoader(), bindingClass,
162 tmpLeaves, tmpDataObjects, keyMethod);
165 // Iterate over all possible augmentations, indexing them as needed
166 final Map<PathArgument, DataContainerCodecPrototype<?>> augByYang = new HashMap<>();
167 final Map<Class<?>, DataContainerCodecPrototype<?>> augByStream = new HashMap<>();
168 for (final Type augment : possibleAugmentations.values()) {
169 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
170 final PathArgument augYangArg = augProto.getYangArg();
171 if (augByYang.putIfAbsent(augYangArg, augProto) == null) {
172 LOG.trace("Discovered new YANG mapping {} -> {} in {}", augYangArg, augProto, this);
174 final Class<?> augBindingClass = augProto.getBindingClass();
175 if (augByStream.putIfAbsent(augBindingClass, augProto) == null) {
176 LOG.trace("Discovered new class mapping {} -> {} in {}", augBindingClass, augProto, this);
179 augmentationByYang = ImmutableMap.copyOf(augByYang);
180 augmentationByStream = ImmutableMap.copyOf(augByStream);
182 final MethodHandle ctor;
184 ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
185 } catch (NoSuchMethodException | IllegalAccessException e) {
186 throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
189 proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
192 @SuppressWarnings("unchecked")
194 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
195 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
196 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
200 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
201 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
202 if (childProto != null) {
205 if (Augmentation.class.isAssignableFrom(childClass)) {
206 return augmentationByClass(childClass);
211 @SuppressWarnings("unchecked")
213 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
214 final Class<C> childClass) {
215 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
216 if (childProto != null) {
217 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
219 return Optional.empty();
223 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
224 final List<YangInstanceIdentifier.PathArgument> builder) {
226 final Class<? extends DataObject> argType = arg.getType();
227 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
228 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
229 ctxProto = augmentationByClass(argType);
231 final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
232 "Class %s is not valid child of %s", argType, getBindingClass()).get();
233 if (context instanceof ChoiceNodeCodecContext) {
234 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
235 choice.addYangPathArgument(arg, builder);
237 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
238 final Class<? extends DataObject> type = arg.getType();
239 final DataContainerCodecContext<?, ?> caze;
240 if (caseType.isPresent()) {
241 // Non-ambiguous addressing this should not pose any problems
242 caze = choice.streamChild(caseType.get());
244 caze = choice.getCaseByChildClass(type);
247 caze.addYangPathArgument(arg, builder);
248 return caze.bindingPathArgumentChild(arg, builder);
250 context.addYangPathArgument(arg, builder);
255 public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
256 final NodeContextSupplier childSupplier;
257 if (arg instanceof NodeIdentifierWithPredicates) {
258 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
259 } else if (arg instanceof AugmentationIdentifier) {
260 childSupplier = augmentationByYang.get(arg);
262 childSupplier = byYang.get(arg);
265 return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
268 protected final ValueNodeCodecContext getLeafChild(final String name) {
269 final ValueNodeCodecContext value = leafChild.get(name);
271 throw IncorrectNestingException.create("Leaf %s is not valid for %s", name, getBindingClass());
276 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<? extends DataContainer> childClass) {
277 final DataSchemaNode childSchema = childNonNull(
278 factory().getRuntimeContext().findChildSchemaDefinition(getSchema(), namespace(), childClass), childClass,
279 "Node %s does not have child named %s", getSchema(), childClass);
280 return DataContainerCodecPrototype.from(createBindingArg(childClass, childSchema), childSchema, factory());
283 // FIXME: MDSAL-697: move this method into BindingRuntimeContext
284 // This method is only called from loadChildPrototype() and exists only to be overridden by
285 // CaseNodeCodecContext. Since we are providing childClass and our schema to BindingRuntimeContext
286 // and receiving childSchema from it via findChildSchemaDefinition, we should be able to receive
287 // the equivalent of Map.Entry<Item, DataSchemaNode>, along with the override we create here. One
288 // more input we may need to provide is our bindingClass().
289 @SuppressWarnings("unchecked")
290 Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
291 return Item.of((Class<? extends DataObject>) childClass);
294 private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
295 final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
296 return childProto != null ? childProto : mismatchedAugmentationByClass(childClass);
299 private @Nullable DataContainerCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
301 * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
302 * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
303 * we'll cache it so we do not need to perform reflection operations again.
305 final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local =
306 (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
307 final DataContainerCodecPrototype<?> mismatched = local.get(childClass);
308 return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
312 private @Nullable DataContainerCodecPrototype<?> loadMismatchedAugmentation(
313 final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
314 final @NonNull Class<?> childClass) {
315 @SuppressWarnings("rawtypes")
316 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
317 // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
318 // context would load.
319 if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
320 for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
321 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
322 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
323 return cacheMismatched(oldMismatched, childClass, realChild);
327 LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
331 private @NonNull DataContainerCodecPrototype<?> cacheMismatched(
332 final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
333 final @NonNull Class<?> childClass, final @NonNull DataContainerCodecPrototype<?> prototype) {
335 ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> expected = oldMismatched;
337 final Map<Class<?>, DataContainerCodecPrototype<?>> newMismatched =
338 ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
340 .put(childClass, prototype)
343 final Object witness = MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
344 if (witness == expected) {
345 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
349 expected = (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) witness;
350 final DataContainerCodecPrototype<?> existing = expected.get(childClass);
351 if (existing != null) {
352 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
358 private boolean belongsToRuntimeContext(final Class<?> cls) {
359 final BindingRuntimeContext ctx = factory().getRuntimeContext();
360 final Class<?> loaded;
362 loaded = ctx.loadClass(Type.of(cls));
363 } catch (ClassNotFoundException e) {
364 LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
367 return cls.equals(loaded);
370 private @NonNull DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
371 final BindingRuntimeContext ctx = factory().getRuntimeContext();
373 final Class<? extends Augmentation<?>> augClass;
375 augClass = ctx.loadClass(value);
376 } catch (final ClassNotFoundException e) {
377 throw new IllegalStateException("RuntimeContext references type " + value + " but failed to its class", e);
380 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema =
381 ctx.getResolvedAugmentationSchema(getSchema(), augClass);
382 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
385 @SuppressWarnings("checkstyle:illegalCatch")
386 protected final @NonNull D createBindingProxy(final DistinctNodeContainer<?, ?> node) {
388 return (D) proxyConstructor.invokeExact(this, node);
389 } catch (final Throwable e) {
390 Throwables.throwIfUnchecked(e);
391 throw new IllegalStateException(e);
395 @SuppressWarnings("unchecked")
396 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
397 final DistinctNodeContainer<PathArgument, NormalizedNode> data) {
399 @SuppressWarnings("rawtypes")
400 final Map map = new HashMap<>();
402 for (final NormalizedNode childValue : data.body()) {
403 if (childValue instanceof AugmentationNode) {
404 final AugmentationNode augDomNode = (AugmentationNode) childValue;
405 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
406 if (codecProto != null) {
407 final DataContainerCodecContext<?, ?> codec = codecProto.get();
408 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
412 for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
413 final NormalizedNode augData = data.childByArg(value.getYangArg());
414 if (augData != null) {
415 map.put(value.getBindingClass(), value.get().deserializeObject(augData));
421 final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
422 return generatedClass;
426 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
427 checkArgument(getDomPathArgument().equals(arg));
432 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
433 checkArgument(bindingArg().equals(arg));
434 return getDomPathArgument();