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;
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableSortedMap;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.lang.invoke.MethodHandle;
17 import java.lang.invoke.MethodHandles;
18 import java.lang.invoke.MethodType;
19 import java.lang.reflect.InvocationHandler;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Proxy;
22 import java.util.Collection;
23 import java.util.Comparator;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.Map.Entry;
28 import java.util.Optional;
29 import java.util.SortedMap;
30 import java.util.TreeMap;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ConcurrentMap;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
36 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
37 import org.opendaylight.mdsal.binding.model.api.Type;
38 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
39 import org.opendaylight.yangtools.util.ClassLoaderUtils;
40 import org.opendaylight.yangtools.yang.binding.Augmentable;
41 import org.opendaylight.yangtools.yang.binding.Augmentation;
42 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
43 import org.opendaylight.yangtools.yang.binding.DataObject;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
52 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
55 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
57 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
59 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
64 extends DataContainerCodecContext<D, T> {
65 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
66 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
67 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
68 private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
70 private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
71 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
72 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
73 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
74 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
75 private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
76 private final MethodHandle proxyConstructor;
78 private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
79 new ConcurrentHashMap<>();
80 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
82 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
85 final Class<D> bindingClass = getBindingClass();
86 this.leafChild = factory().getLeafNodes(bindingClass, getSchema());
88 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass);
90 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
91 final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
92 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
93 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
95 // Adds leaves to mapping
96 for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
97 byMethodBuilder.put(leaf.getGetter(), leaf);
98 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
101 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
102 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
103 byMethodBuilder.put(childDataObj.getValue(), childProto);
104 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
105 byYangBuilder.put(childProto.getYangArg(), childProto);
106 if (childProto.isChoice()) {
107 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
108 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
109 byBindingArgClassBuilder.put(cazeChild, childProto);
113 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
114 this.byYang = ImmutableMap.copyOf(byYangBuilder);
115 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
116 byBindingArgClassBuilder.putAll(byStreamClass);
117 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
119 if (Augmentable.class.isAssignableFrom(bindingClass)) {
120 this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
122 this.possibleAugmentations = ImmutableMap.of();
124 reloadAllAugmentations();
126 final Class<?> proxyClass = Proxy.getProxyClass(bindingClass.getClassLoader(), bindingClass,
127 AugmentationHolder.class);
129 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
130 .asType(DATAOBJECT_TYPE);
131 } catch (NoSuchMethodException | IllegalAccessException e) {
132 throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
136 @SuppressFBWarnings("RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED")
137 private void reloadAllAugmentations() {
138 for (final Type augment : possibleAugmentations.values()) {
139 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
140 if (augProto != null) {
141 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
142 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
147 @SuppressWarnings("unchecked")
149 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
150 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
151 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
155 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
156 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
157 if (childProto != null) {
160 if (Augmentation.class.isAssignableFrom(childClass)) {
161 return augmentationByClass(childClass);
166 @SuppressWarnings("unchecked")
168 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
169 final Class<C> childClass) {
170 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
171 if (childProto != null) {
172 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
174 return Optional.empty();
178 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
179 final List<YangInstanceIdentifier.PathArgument> builder) {
181 final Class<? extends DataObject> argType = arg.getType();
182 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
183 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
184 ctxProto = augmentationByClass(argType);
186 final DataContainerCodecContext<?, ?> context =
187 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
188 if (context instanceof ChoiceNodeCodecContext) {
189 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
190 choice.addYangPathArgument(arg, builder);
192 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
193 final Class<? extends DataObject> type = arg.getType();
194 final DataContainerCodecContext<?, ?> caze;
195 if (caseType.isPresent()) {
196 // Non-ambiguous addressing this should not pose any problems
197 caze = choice.streamChild(caseType.get());
199 caze = choice.getCaseByChildClass(type);
202 caze.addYangPathArgument(arg, builder);
203 return caze.bindingPathArgumentChild(arg, builder);
205 context.addYangPathArgument(arg, builder);
209 @SuppressWarnings("unchecked")
211 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
212 final NodeContextSupplier childSupplier;
213 if (arg instanceof NodeIdentifierWithPredicates) {
214 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
215 } else if (arg instanceof AugmentationIdentifier) {
216 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
218 childSupplier = byYang.get(arg);
221 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
222 "Argument %s is not valid child of %s", arg, getSchema()).get();
225 protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
226 final LeafNodeCodecContext<?> value = leafChild.get(name);
227 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
230 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
231 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
232 // Direct instantiation or use in same module in which grouping
234 DataSchemaNode sameName;
236 sameName = getSchema().getDataChildByName(origDef.getQName());
237 } catch (final IllegalArgumentException e) {
240 final DataSchemaNode childSchema;
241 if (sameName != null) {
242 // Exactly same schema node
243 if (origDef.equals(sameName)) {
244 childSchema = sameName;
245 // We check if instantiated node was added via uses
246 // statement and is instantiation of same grouping
247 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
248 childSchema = sameName;
250 // Node has same name, but clearly is different
254 // We are looking for instantiation via uses in other module
255 final QName instantiedName = origDef.getQName().withModule(namespace());
256 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
257 // We check if it is really instantiated from same
258 // definition as class was derived
259 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
260 childSchema = potential;
265 final DataSchemaNode nonNullChild =
266 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
267 return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
270 @SuppressWarnings("unchecked")
271 Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
272 return Item.of((Class<? extends DataObject>) childClass);
275 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
276 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
277 if (firstTry != null) {
280 if (possibleAugmentations.containsKey(arg)) {
281 reloadAllAugmentations();
282 return byYangAugmented.get(arg);
287 private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
288 DataContainerCodecPrototype<?> lookup = augmentationByClassOrEquivalentClass(childClass);
289 if (lookup != null || !isPotentialAugmentation(childClass)) {
293 // Attempt to reload all augmentations using TCCL and lookup again
294 reloadAllAugmentations();
295 lookup = augmentationByClassOrEquivalentClass(childClass);
296 if (lookup != null) {
300 // Still no result, this can be caused by TCCL not being set up properly -- try the class's ClassLoader
302 final ClassLoader loader = childClass.getClassLoader();
303 if (loader == null) {
307 LOG.debug("Class {} not loaded via TCCL, attempting to recover", childClass);
308 ClassLoaderUtils.runWithClassLoader(loader, this::reloadAllAugmentations);
309 return augmentationByClassOrEquivalentClass(childClass);
312 private boolean isPotentialAugmentation(final Class<?> childClass) {
313 final JavaTypeName name = JavaTypeName.create(childClass);
314 for (Type type : possibleAugmentations.values()) {
315 if (name.equals(type.getIdentifier())) {
322 private @Nullable DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(
323 final @NonNull Class<?> childClass) {
324 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
325 if (childProto != null) {
330 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
331 * using reflection and walk all stream child and compare augmenations classes if they are
334 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
336 @SuppressWarnings("rawtypes")
337 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
338 if (getBindingClass().equals(augTarget)) {
339 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
340 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
341 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
349 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
350 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
351 @SuppressWarnings("rawtypes")
352 final Class augClass;
354 augClass = loader.loadClass(value);
355 } catch (final ClassNotFoundException e) {
356 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
360 @SuppressWarnings("unchecked")
361 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
362 .getResolvedAugmentationSchema(getSchema(), augClass);
363 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
366 @SuppressWarnings("rawtypes")
367 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
368 final NodeCodecContext<?> childContext = byMethod.get(method).get();
369 @SuppressWarnings("unchecked")
370 final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
372 // We do not want to use Optional.map() here because we do not want to invoke defaultObject() when we have
373 // normal value because defaultObject() may end up throwing an exception intentionally.
374 return domChild.isPresent() ? childContext.deserializeObject(domChild.get()) : childContext.defaultObject();
377 @SuppressWarnings("checkstyle:illegalCatch")
378 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
380 return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
381 } catch (final Throwable e) {
382 Throwables.throwIfUnchecked(e);
383 throw new RuntimeException(e);
387 @SuppressWarnings("unchecked")
388 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
389 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
391 @SuppressWarnings("rawtypes")
392 final Map map = new HashMap<>();
394 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
395 if (childValue instanceof AugmentationNode) {
396 final AugmentationNode augDomNode = (AugmentationNode) childValue;
397 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
398 if (codecProto != null) {
399 final DataContainerCodecContext<?, ?> codec = codecProto.get();
400 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
404 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
405 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
406 if (augData.isPresent()) {
407 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
413 Collection<Method> getHashCodeAndEqualsMethods() {
414 return byMethod.keySet();
418 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
419 checkArgument(getDomPathArgument().equals(arg));
424 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
425 checkArgument(bindingArg().equals(arg));
426 return getDomPathArgument();