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.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.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * This class is an implementation detail. It is public only due to technical reasons and may change at any time.
58 public abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
59 extends DataContainerCodecContext<D, T> {
60 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
61 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class,
62 DataObjectCodecContext.class, DistinctNodeContainer.class);
63 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class,
64 DataObjectCodecContext.class, DistinctNodeContainer.class);
65 private static final VarHandle MISMATCHED_AUGMENTED;
69 MISMATCHED_AUGMENTED = MethodHandles.lookup().findVarHandle(DataObjectCodecContext.class,
70 "mismatchedAugmented", ImmutableMap.class);
71 } catch (NoSuchFieldException | IllegalAccessException e) {
72 throw new ExceptionInInitializerError(e);
76 private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
77 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
78 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
79 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
80 private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> augmentationByYang;
81 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> augmentationByStream;
82 private final @NonNull Class<? extends CodecDataObject<?>> generatedClass;
83 private final MethodHandle proxyConstructor;
85 // Note this the content of this field depends only of invariants expressed as this class's fields or
86 // BindingRuntimeContext. It is only accessed via MISMATCHED_AUGMENTED above.
87 @SuppressWarnings("unused")
88 private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
90 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
91 this(prototype, null);
94 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype, final Method keyMethod) {
97 final Class<D> bindingClass = getBindingClass();
99 final ImmutableMap<Method, ValueNodeCodecContext> tmpLeaves = factory().getLeafNodes(bindingClass, getSchema());
100 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
102 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
103 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
104 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
106 // Adds leaves to mapping
107 final Builder<String, ValueNodeCodecContext> leafChildBuilder =
108 ImmutableMap.builderWithExpectedSize(tmpLeaves.size());
109 for (final Entry<Method, ValueNodeCodecContext> entry : tmpLeaves.entrySet()) {
110 final ValueNodeCodecContext leaf = entry.getValue();
111 leafChildBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
112 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
114 this.leafChild = leafChildBuilder.build();
116 final Map<Method, Class<?>> tmpDataObjects = new HashMap<>();
117 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
118 final Method method = childDataObj.getValue();
119 verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
121 final Class<?> retClass = childDataObj.getKey();
122 if (OpaqueObject.class.isAssignableFrom(retClass)) {
123 // Filter OpaqueObjects, they are not containers
127 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(retClass);
128 tmpDataObjects.put(method, childProto.getBindingClass());
129 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
130 byYangBuilder.put(childProto.getYangArg(), childProto);
131 if (childProto.isChoice()) {
132 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
133 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
134 byBindingArgClassBuilder.put(cazeChild, childProto);
139 this.byYang = ImmutableMap.copyOf(byYangBuilder);
140 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
142 // Slight footprint optimization: we do not want to copy byStreamClass, as that would force its entrySet view
143 // to be instantiated. Furthermore the two maps can easily end up being equal -- hence we can reuse
144 // byStreamClass for the purposes of both.
145 byBindingArgClassBuilder.putAll(byStreamClassBuilder);
146 this.byBindingArgClass = byStreamClassBuilder.equals(byBindingArgClassBuilder) ? this.byStreamClass
147 : ImmutableMap.copyOf(byBindingArgClassBuilder);
149 final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
150 if (Augmentable.class.isAssignableFrom(bindingClass)) {
151 possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
152 generatedClass = CodecDataObjectGenerator.generateAugmentable(prototype.getFactory().getLoader(),
153 bindingClass, tmpLeaves, tmpDataObjects, keyMethod);
155 possibleAugmentations = ImmutableMap.of();
156 generatedClass = CodecDataObjectGenerator.generate(prototype.getFactory().getLoader(), bindingClass,
157 tmpLeaves, tmpDataObjects, keyMethod);
160 // Iterate over all possible augmentations, indexing them as needed
161 final Map<PathArgument, DataContainerCodecPrototype<?>> augByYang = new HashMap<>();
162 final Map<Class<?>, DataContainerCodecPrototype<?>> augByStream = new HashMap<>();
163 for (final Type augment : possibleAugmentations.values()) {
164 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
165 final PathArgument augYangArg = augProto.getYangArg();
166 if (augByYang.putIfAbsent(augYangArg, augProto) == null) {
167 LOG.trace("Discovered new YANG mapping {} -> {} in {}", augYangArg, augProto, this);
169 final Class<?> augBindingClass = augProto.getBindingClass();
170 if (augByStream.putIfAbsent(augBindingClass, augProto) == null) {
171 LOG.trace("Discovered new class mapping {} -> {} in {}", augBindingClass, augProto, this);
174 augmentationByYang = ImmutableMap.copyOf(augByYang);
175 augmentationByStream = ImmutableMap.copyOf(augByStream);
177 final MethodHandle ctor;
179 ctor = MethodHandles.publicLookup().findConstructor(generatedClass, CONSTRUCTOR_TYPE);
180 } catch (NoSuchMethodException | IllegalAccessException e) {
181 throw new LinkageError("Failed to find contructor for class " + generatedClass, e);
184 proxyConstructor = ctor.asType(DATAOBJECT_TYPE);
187 @SuppressWarnings("unchecked")
189 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
190 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
191 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
195 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
196 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
197 if (childProto != null) {
200 if (Augmentation.class.isAssignableFrom(childClass)) {
201 return augmentationByClass(childClass);
206 @SuppressWarnings("unchecked")
208 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
209 final Class<C> childClass) {
210 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
211 if (childProto != null) {
212 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
214 return Optional.empty();
218 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
219 final List<YangInstanceIdentifier.PathArgument> builder) {
221 final Class<? extends DataObject> argType = arg.getType();
222 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
223 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
224 ctxProto = augmentationByClass(argType);
226 final DataContainerCodecContext<?, ?> context = childNonNull(ctxProto, argType,
227 "Class %s is not valid child of %s", argType, getBindingClass()).get();
228 if (context instanceof ChoiceNodeCodecContext) {
229 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
230 choice.addYangPathArgument(arg, builder);
232 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
233 final Class<? extends DataObject> type = arg.getType();
234 final DataContainerCodecContext<?, ?> caze;
235 if (caseType.isPresent()) {
236 // Non-ambiguous addressing this should not pose any problems
237 caze = choice.streamChild(caseType.get());
239 caze = choice.getCaseByChildClass(type);
242 caze.addYangPathArgument(arg, builder);
243 return caze.bindingPathArgumentChild(arg, builder);
245 context.addYangPathArgument(arg, builder);
250 public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
251 final NodeContextSupplier childSupplier;
252 if (arg instanceof NodeIdentifierWithPredicates) {
253 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
254 } else if (arg instanceof AugmentationIdentifier) {
255 childSupplier = augmentationByYang.get(arg);
257 childSupplier = byYang.get(arg);
260 return childNonNull(childSupplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
263 protected final ValueNodeCodecContext getLeafChild(final String name) {
264 final ValueNodeCodecContext value = leafChild.get(name);
266 throw IncorrectNestingException.create("Leaf %s is not valid for %s", name, getBindingClass());
271 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
272 final DataSchemaNode nonNullChild = childNonNull(
273 factory().getRuntimeContext().findChildSchemaDefinition(getSchema(), namespace(), childClass), childClass,
274 "Node %s does not have child named %s", getSchema(), childClass);
275 return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
278 @SuppressWarnings("unchecked")
279 Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
280 return Item.of((Class<? extends DataObject>) childClass);
283 private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
284 final DataContainerCodecPrototype<?> childProto = augmentationByStream.get(childClass);
285 return childProto != null ? childProto : mismatchedAugmentationByClass(childClass);
288 private @Nullable DataContainerCodecPrototype<?> mismatchedAugmentationByClass(final @NonNull Class<?> childClass) {
290 * It is potentially mismatched valid augmentation - we look up equivalent augmentation using reflection
291 * and walk all stream child and compare augmentations classes if they are equivalent. When we find a match
292 * we'll cache it so we do not need to perform reflection operations again.
294 final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local =
295 (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) MISMATCHED_AUGMENTED.getAcquire(this);
296 final DataContainerCodecPrototype<?> mismatched = local.get(childClass);
297 return mismatched != null ? mismatched : loadMismatchedAugmentation(local, childClass);
301 private @Nullable DataContainerCodecPrototype<?> loadMismatchedAugmentation(
302 final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
303 final @NonNull Class<?> childClass) {
304 @SuppressWarnings("rawtypes")
305 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
306 // Do not bother with proposals which are not augmentations of our class, or do not match what the runtime
307 // context would load.
308 if (getBindingClass().equals(augTarget) && belongsToRuntimeContext(childClass)) {
309 for (final DataContainerCodecPrototype<?> realChild : augmentationByStream.values()) {
310 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
311 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
312 return cacheMismatched(oldMismatched, childClass, realChild);
316 LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
320 private @NonNull DataContainerCodecPrototype<?> cacheMismatched(
321 final @NonNull ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> oldMismatched,
322 final @NonNull Class<?> childClass, final @NonNull DataContainerCodecPrototype<?> prototype) {
324 ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> expected = oldMismatched;
326 final Map<Class<?>, DataContainerCodecPrototype<?>> newMismatched =
327 ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builderWithExpectedSize(expected.size() + 1)
329 .put(childClass, prototype)
332 final Object witness = MISMATCHED_AUGMENTED.compareAndExchangeRelease(this, expected, newMismatched);
333 if (witness == expected) {
334 LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
338 expected = (ImmutableMap<Class<?>, DataContainerCodecPrototype<?>>) witness;
339 final DataContainerCodecPrototype<?> existing = expected.get(childClass);
340 if (existing != null) {
341 LOG.trace("Using raced mismatched augmentation {} -> {} in {}", childClass, existing, this);
347 private boolean belongsToRuntimeContext(final Class<?> cls) {
348 final BindingRuntimeContext ctx = factory().getRuntimeContext();
349 final Class<?> loaded;
351 loaded = ctx.loadClass(Type.of(cls));
352 } catch (ClassNotFoundException e) {
353 LOG.debug("Proposed {} cannot be loaded in {}", cls, ctx, e);
356 return cls.equals(loaded);
359 private @NonNull DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
360 final BindingRuntimeContext ctx = factory().getRuntimeContext();
362 final Class<? extends Augmentation<?>> augClass;
364 augClass = ctx.loadClass(value);
365 } catch (final ClassNotFoundException e) {
366 throw new IllegalStateException("RuntimeContext references type " + value + " but failed to its class", e);
369 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema =
370 ctx.getResolvedAugmentationSchema(getSchema(), augClass);
371 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
374 @SuppressWarnings("checkstyle:illegalCatch")
375 protected final @NonNull D createBindingProxy(final DistinctNodeContainer<?, ?> node) {
377 return (D) proxyConstructor.invokeExact(this, node);
378 } catch (final Throwable e) {
379 Throwables.throwIfUnchecked(e);
380 throw new IllegalStateException(e);
384 @SuppressWarnings("unchecked")
385 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
386 final DistinctNodeContainer<PathArgument, NormalizedNode> data) {
388 @SuppressWarnings("rawtypes")
389 final Map map = new HashMap<>();
391 for (final NormalizedNode childValue : data.body()) {
392 if (childValue instanceof AugmentationNode) {
393 final AugmentationNode augDomNode = (AugmentationNode) childValue;
394 final DataContainerCodecPrototype<?> codecProto = augmentationByYang.get(augDomNode.getIdentifier());
395 if (codecProto != null) {
396 final DataContainerCodecContext<?, ?> codec = codecProto.get();
397 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
401 for (final DataContainerCodecPrototype<?> value : augmentationByStream.values()) {
402 final NormalizedNode augData = data.childByArg(value.getYangArg());
403 if (augData != null) {
404 map.put(value.getBindingClass(), value.get().deserializeObject(augData));
410 final @NonNull Class<? extends CodecDataObject<?>> generatedClass() {
411 return generatedClass;
415 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
416 checkArgument(getDomPathArgument().equals(arg));
421 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
422 checkArgument(bindingArg().equals(arg));
423 return getDomPathArgument();