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.reflect.Method;
21 import java.util.HashMap;
22 import java.util.List;
24 import java.util.Map.Entry;
25 import java.util.Optional;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
29 import org.opendaylight.mdsal.binding.model.api.DefaultType;
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.DataObject;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
38 import org.opendaylight.yangtools.yang.binding.OpaqueObject;
39 import org.opendaylight.yangtools.yang.common.QName;
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.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
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.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
60 public abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
61 extends DataContainerCodecContext<D, T> {
62 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
63 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
64 DataObjectCodecContext.class, NormalizedNodeContainer.class);
65 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
66 DataObjectCodecContext.class, NormalizedNodeContainer.class);
68 private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
69 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
70 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
71 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
72 private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> augmentationByYang;
73 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> augmentationByStream;
74 private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
75 private final MethodHandle proxyConstructor;
77 // Note this the content of this field depends only of invariants expressed as this class's fields or
78 // BindingRuntimeContext.
79 private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
81 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
82 this(prototype, null);
85 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
88 final Class<D> bindingClass = getBindingClass();
90 final ImmutableMap<Method, ValueNodeCodecContext> tmpLeaves = factory().getLeafNodes(bindingClass, getSchema());
91 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
93 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
94 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
95 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
97 // Adds leaves to mapping
98 final Builder<String, ValueNodeCodecContext> leafChildBuilder =
99 ImmutableMap.builderWithExpectedSize(tmpLeaves.size());
100 for (final Entry<Method, ValueNodeCodecContext> entry : tmpLeaves.entrySet()) {
101 final ValueNodeCodecContext leaf = entry.getValue();
102 leafChildBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
103 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
105 this.leafChild = leafChildBuilder.build();
107 final Map<Method, Class<?>> tmpDataObjects = new HashMap<>();
108 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
109 final Method method = childDataObj.getValue();
110 verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
112 final Class<?> retClass = childDataObj.getKey();
113 if (OpaqueObject.class.isAssignableFrom(retClass)) {
114 // Filter OpaqueObjects, they are not containers
118 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(retClass);
119 tmpDataObjects.put(method, childProto.getBindingClass());
120 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
121 byYangBuilder.put(childProto.getYangArg(), childProto);
122 if (childProto.isChoice()) {
123 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
124 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
125 byBindingArgClassBuilder.put(cazeChild, childProto);
130 this.byYang = ImmutableMap.copyOf(byYangBuilder);
131 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
133 // Slight footprint optimization: we do not want to copy byStreamClass, as that would force its entrySet view
134 // to be instantiated. Furthermore the two maps can easily end up being equal -- hence we can reuse
135 // byStreamClass for the purposes of both.
136 byBindingArgClassBuilder.putAll(byStreamClassBuilder);
137 this.byBindingArgClass = byStreamClassBuilder.equals(byBindingArgClassBuilder) ? this.byStreamClass
138 : ImmutableMap.copyOf(byBindingArgClassBuilder);
140 final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
141 if (Augmentable.class.isAssignableFrom(bindingClass)) {
142 possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
143 generatedClass = CodecDataObjectGenerator.generateAugmentable(prototype.getFactory().getLoader(),
144 bindingClass, tmpLeaves, tmpDataObjects, keyMethod);
146 possibleAugmentations = ImmutableMap.of();
147 generatedClass = CodecDataObjectGenerator.generate(prototype.getFactory().getLoader(), bindingClass,
148 tmpLeaves, tmpDataObjects, keyMethod);
151 // Iterate over all possible augmentations, indexing them as needed
152 final Map<PathArgument, DataContainerCodecPrototype<?>> augByYang = new HashMap<>();
153 final Map<Class<?>, DataContainerCodecPrototype<?>> augByStream = new HashMap<>();
154 for (final Type augment : possibleAugmentations.values()) {
155 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
156 final PathArgument augYangArg = augProto.getYangArg();
157 if (augByYang.putIfAbsent(augYangArg, augProto) == null) {
158 LOG.trace("Discovered new YANG mapping {} -> {} in {}", augYangArg, augProto, this);
160 final Class<?> augBindingClass = augProto.getBindingClass();
161 if (augByStream.putIfAbsent(augBindingClass, augProto) == null) {
162 LOG.trace("Discovered new class mapping {} -> {} in {}", augBindingClass, augProto, this);
165 augmentationByYang = ImmutableMap.copyOf(augByYang);
166 augmentationByStream = ImmutableMap.copyOf(augByStream);
168 final MethodHandle ctor;
170 ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
171 } catch (NoSuchMethodException | IllegalAccessException e) {
172 throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
175 proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
178 @SuppressWarnings("unchecked")
180 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
181 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
182 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
186 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
187 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
188 if (childProto != null) {
191 if (Augmentation.class.isAssignableFrom(childClass)) {
192 return augmentationByClass(childClass);
197 @SuppressWarnings("unchecked")
199 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
200 final Class<C> childClass) {
201 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
202 if (childProto != null) {
203 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
205 return Optional.empty();
209 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
210 final List<YangInstanceIdentifier.PathArgument> builder) {
212 final Class<? extends DataObject> argType = arg.getType();
213 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
214 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
215 ctxProto = augmentationByClass(argType);
217 final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
218 "Class %s is not valid child of %s", argType, getBindingClass()).get();
219 if (context instanceof ChoiceNodeCodecContext) {
220 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
221 choice.addYangPathArgument(arg, builder);
223 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
224 final Class<? extends DataObject> type = arg.getType();
225 final DataContainerCodecContext<?, ?> caze;
226 if (caseType.isPresent()) {
227 // Non-ambiguous addressing this should not pose any problems
228 caze = choice.streamChild(caseType.get());
230 caze = choice.getCaseByChildClass(type);
233 caze.addYangPathArgument(arg, builder);
234 return caze.bindingPathArgumentChild(arg, builder);
236 context.addYangPathArgument(arg, builder);
241 public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
242 final NodeContextSupplier childSupplier;
243 if (arg instanceof NodeIdentifierWithPredicates) {
244 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
245 } else if (arg instanceof AugmentationIdentifier) {
246 childSupplier = augmentationByYang.get(arg);
248 childSupplier = byYang.get(arg);
251 return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
254 protected final ValueNodeCodecContext getLeafChild(final String name) {
255 final ValueNodeCodecContext value = leafChild.get(name);
257 throw IncorrectNestingException.create("Leaf %s is not valid for %s", name, getBindingClass());
262 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
263 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
264 // Direct instantiation or use in same module in which grouping
266 DataSchemaNode sameName;
268 sameName = getSchema().getDataChildByName(origDef.getQName());
269 } catch (final IllegalArgumentException e) {
272 final DataSchemaNode childSchema;
273 if (sameName != null) {
274 // Exactly same schema node
275 if (origDef.equals(sameName)) {
276 childSchema = sameName;
277 // We check if instantiated node was added via uses
278 // statement and is instantiation of same grouping
279 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
280 childSchema = sameName;
282 // Node has same name, but clearly is different
286 // We are looking for instantiation via uses in other module
287 final QName instantiedName = origDef.getQName().bindTo(namespace());
288 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
289 // We check if it is really instantiated from same
290 // definition as class was derived
291 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
292 childSchema = potential;
297 final DataSchemaNode nonNullChild =
298 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
299 return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
302 @SuppressWarnings("unchecked")
303 Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
304 return Item.of((Class<? extends DataObject>) childClass);
307 private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
308 final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
309 if (childProto != null) {
314 * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
315 * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
316 * we'll cache it so we do not need to perform reflection operations again.
318 final DataContainerCodecPrototype<?> mismatched = mismatchedAugmented.get(childClass);
319 if (mismatched != null) {
323 @SuppressWarnings("rawtypes")
324 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
325 // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
326 // context would load.
327 if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
328 for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
329 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
330 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
331 return cacheMismatched(childClass, realChild);
335 LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
339 // TODO: can we ditch this synchronized block?
340 private synchronized DataContainerCodecPrototype<?> cacheMismatched(final Class<?> childClass,
341 final DataContainerCodecPrototype<?> prototype) {
342 // Original access was unsynchronized, we need to perform additional checking
343 final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local = mismatchedAugmented;
344 final DataContainerCodecPrototype<?> existing = local.get(childClass);
345 if (existing != null) {
349 final Builder<Class<?>, DataContainerCodecPrototype<?>> builder = ImmutableMap.builderWithExpectedSize(
351 builder.putAll(local);
352 builder.put(childClass, prototype);
354 mismatchedAugmented = builder.build();
355 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
359 private boolean belongsToRuntimeContext(final Class<?> cls) {
360 final BindingRuntimeContext ctx = factory().getRuntimeContext();
361 final Class<?> loaded;
363 loaded = ctx.loadClass(DefaultType.of(cls));
364 } catch (ClassNotFoundException e) {
365 LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx);
368 return cls.equals(loaded);
371 private @NonNull DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
372 final BindingRuntimeContext ctx = factory().getRuntimeContext();
374 final Class<? extends Augmentation<?>> augClass;
376 augClass = ctx.loadClass(value);
377 } catch (final ClassNotFoundException e) {
378 throw new IllegalStateException("RuntimeContext references type " + value + " but failed to its class", e);
381 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema =
382 ctx.getResolvedAugmentationSchema(getSchema(), augClass);
383 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
386 @SuppressWarnings("checkstyle:illegalCatch")
387 protected final @NonNull D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
389 return (D) proxyConstructor.invokeExact(this, node);
390 } catch (final Throwable e) {
391 Throwables.throwIfUnchecked(e);
392 throw new IllegalStateException(e);
396 @SuppressWarnings("unchecked")
397 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
398 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
400 @SuppressWarnings("rawtypes")
401 final Map map = new HashMap<>();
403 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
404 if (childValue instanceof AugmentationNode) {
405 final AugmentationNode augDomNode = (AugmentationNode) childValue;
406 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
407 if (codecProto != null) {
408 final DataContainerCodecContext<?, ?> codec = codecProto.get();
409 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
413 for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
414 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
415 if (augData.isPresent()) {
416 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
422 final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
423 return generatedClass;
427 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
428 checkArgument(getDomPathArgument().equals(arg));
433 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
434 checkArgument(bindingArg().equals(arg));
435 return getDomPathArgument();