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.verifyNotNull;
13 import com.google.common.base.Throwables;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSortedMap;
16 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
17 import java.lang.invoke.MethodHandle;
18 import java.lang.invoke.MethodHandles;
19 import java.lang.invoke.MethodType;
20 import java.lang.reflect.InvocationHandler;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.Proxy;
23 import java.util.Collection;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30 import java.util.SortedMap;
31 import java.util.TreeMap;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.concurrent.ConcurrentMap;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
37 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
38 import org.opendaylight.mdsal.binding.model.api.Type;
39 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
40 import org.opendaylight.yangtools.util.ClassLoaderUtils;
41 import org.opendaylight.yangtools.yang.binding.Augmentable;
42 import org.opendaylight.yangtools.yang.binding.Augmentation;
43 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
44 import org.opendaylight.yangtools.yang.binding.DataObject;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
53 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
56 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
60 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
65 extends DataContainerCodecContext<D, T> {
66 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
67 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
68 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
69 private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
71 private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
72 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
73 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
74 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
75 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
76 private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
77 private final MethodHandle proxyConstructor;
79 private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
80 new ConcurrentHashMap<>();
81 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
83 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
86 final Class<D> bindingClass = getBindingClass();
87 this.leafChild = factory().getLeafNodes(bindingClass, getSchema());
89 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
91 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
92 final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
93 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
94 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
96 // Adds leaves to mapping
97 for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
98 byMethodBuilder.put(leaf.getGetter(), leaf);
99 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
102 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
103 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
104 byMethodBuilder.put(childDataObj.getValue(), childProto);
105 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
106 byYangBuilder.put(childProto.getYangArg(), childProto);
107 if (childProto.isChoice()) {
108 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
109 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
110 byBindingArgClassBuilder.put(cazeChild, childProto);
114 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
115 this.byYang = ImmutableMap.copyOf(byYangBuilder);
116 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
117 byBindingArgClassBuilder.putAll(byStreamClass);
118 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
120 if (Augmentable.class.isAssignableFrom(bindingClass)) {
121 this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
123 this.possibleAugmentations = ImmutableMap.of();
125 reloadAllAugmentations();
127 final Class<?> proxyClass = Proxy.getProxyClass(bindingClass.getClassLoader(), bindingClass,
128 AugmentationHolder.class);
130 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
131 .asType(DATAOBJECT_TYPE);
132 } catch (NoSuchMethodException | IllegalAccessException e) {
133 throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
137 @SuppressFBWarnings("RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED")
138 private void reloadAllAugmentations() {
139 for (final Type augment : possibleAugmentations.values()) {
140 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
141 if (augProto != null) {
142 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
143 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
148 @SuppressWarnings("unchecked")
150 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
151 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
152 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
156 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
157 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
158 if (childProto != null) {
161 if (Augmentation.class.isAssignableFrom(childClass)) {
162 return augmentationByClass(childClass);
167 @SuppressWarnings("unchecked")
169 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
170 final Class<C> childClass) {
171 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
172 if (childProto != null) {
173 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
175 return Optional.empty();
179 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
180 final List<YangInstanceIdentifier.PathArgument> builder) {
182 final Class<? extends DataObject> argType = arg.getType();
183 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
184 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
185 ctxProto = augmentationByClass(argType);
187 final DataContainerCodecContext<?, ?> context =
188 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
189 if (context instanceof ChoiceNodeCodecContext) {
190 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
191 choice.addYangPathArgument(arg, builder);
193 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
194 final Class<? extends DataObject> type = arg.getType();
195 final DataContainerCodecContext<?, ?> caze;
196 if (caseType.isPresent()) {
197 // Non-ambiguous addressing this should not pose any problems
198 caze = choice.streamChild(caseType.get());
200 caze = choice.getCaseByChildClass(type);
203 caze.addYangPathArgument(arg, builder);
204 return caze.bindingPathArgumentChild(arg, builder);
206 context.addYangPathArgument(arg, builder);
210 @SuppressWarnings("unchecked")
212 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
213 final NodeContextSupplier childSupplier;
214 if (arg instanceof NodeIdentifierWithPredicates) {
215 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
216 } else if (arg instanceof AugmentationIdentifier) {
217 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
219 childSupplier = byYang.get(arg);
222 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
223 "Argument %s is not valid child of %s", arg, getSchema()).get();
226 protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
227 final LeafNodeCodecContext<?> value = leafChild.get(name);
228 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
231 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
232 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
233 // Direct instantiation or use in same module in which grouping
235 DataSchemaNode sameName;
237 sameName = getSchema().getDataChildByName(origDef.getQName());
238 } catch (final IllegalArgumentException e) {
241 final DataSchemaNode childSchema;
242 if (sameName != null) {
243 // Exactly same schema node
244 if (origDef.equals(sameName)) {
245 childSchema = sameName;
246 // We check if instantiated node was added via uses
247 // statement and is instantiation of same grouping
248 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
249 childSchema = sameName;
251 // Node has same name, but clearly is different
255 // We are looking for instantiation via uses in other module
256 final QName instantiedName = origDef.getQName().withModule(namespace());
257 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
258 // We check if it is really instantiated from same
259 // definition as class was derived
260 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
261 childSchema = potential;
266 final DataSchemaNode nonNullChild =
267 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
268 return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
271 @SuppressWarnings("unchecked")
272 Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
273 return Item.of((Class<? extends DataObject>) childClass);
276 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
277 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
278 if (firstTry != null) {
281 if (possibleAugmentations.containsKey(arg)) {
282 reloadAllAugmentations();
283 return byYangAugmented.get(arg);
288 private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
289 DataContainerCodecPrototype<?> lookup = augmentationByClassOrEquivalentClass(childClass);
290 if (lookup != null || !isPotentialAugmentation(childClass)) {
294 // Attempt to reload all augmentations using TCCL and lookup again
295 reloadAllAugmentations();
296 lookup = augmentationByClassOrEquivalentClass(childClass);
297 if (lookup != null) {
301 // Still no result, this can be caused by TCCL not being set up properly -- try the class's ClassLoader
303 final ClassLoader loader = childClass.getClassLoader();
304 if (loader == null) {
308 LOG.debug("Class {} not loaded via TCCL, attempting to recover", childClass);
309 ClassLoaderUtils.runWithClassLoader(loader, this::reloadAllAugmentations);
310 return augmentationByClassOrEquivalentClass(childClass);
313 private boolean isPotentialAugmentation(final Class<?> childClass) {
314 final JavaTypeName name = JavaTypeName.create(childClass);
315 for (Type type : possibleAugmentations.values()) {
316 if (name.equals(type.getIdentifier())) {
323 private @Nullable DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(
324 final @NonNull Class<?> childClass) {
325 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
326 if (childProto != null) {
331 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
332 * using reflection and walk all stream child and compare augmenations classes if they are
335 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
337 @SuppressWarnings("rawtypes")
338 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
339 if (getBindingClass().equals(augTarget)) {
340 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
341 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
342 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
350 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
351 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
352 @SuppressWarnings("rawtypes")
353 final Class augClass;
355 augClass = loader.loadClass(value);
356 } catch (final ClassNotFoundException e) {
357 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
361 @SuppressWarnings("unchecked")
362 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
363 .getResolvedAugmentationSchema(getSchema(), augClass);
364 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
367 @SuppressWarnings("rawtypes")
368 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
369 final NodeCodecContext<?> childContext = verifyNotNull(byMethod.get(method),
370 "Cannot find data handler for method %s", method).get();
371 @SuppressWarnings("unchecked")
372 final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
374 // We do not want to use Optional.map() here because we do not want to invoke defaultObject() when we have
375 // normal value because defaultObject() may end up throwing an exception intentionally.
376 return domChild.isPresent() ? childContext.deserializeObject(domChild.get()) : childContext.defaultObject();
379 @SuppressWarnings("checkstyle:illegalCatch")
380 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
382 return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
383 } catch (final Throwable e) {
384 Throwables.throwIfUnchecked(e);
385 throw new RuntimeException(e);
389 @SuppressWarnings("unchecked")
390 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
391 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
393 @SuppressWarnings("rawtypes")
394 final Map map = new HashMap<>();
396 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
397 if (childValue instanceof AugmentationNode) {
398 final AugmentationNode augDomNode = (AugmentationNode) childValue;
399 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
400 if (codecProto != null) {
401 final DataContainerCodecContext<?, ?> codec = codecProto.get();
402 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
406 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
407 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
408 if (augData.isPresent()) {
409 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
415 Collection<Method> getHashCodeAndEqualsMethods() {
416 return byMethod.keySet();
420 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
421 checkArgument(getDomPathArgument().equals(arg));
426 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
427 checkArgument(bindingArg().equals(arg));
428 return getDomPathArgument();