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.Type;
37 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
38 import org.opendaylight.yangtools.yang.binding.Augmentable;
39 import org.opendaylight.yangtools.yang.binding.Augmentation;
40 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
41 import org.opendaylight.yangtools.yang.binding.DataObject;
42 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
50 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
53 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
57 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
62 extends DataContainerCodecContext<D, T> {
63 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
64 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
65 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
66 private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
68 private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
69 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
70 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
71 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
72 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
73 private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
74 private final MethodHandle proxyConstructor;
76 private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
77 new ConcurrentHashMap<>();
78 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
80 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
83 this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
85 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
87 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
88 final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
89 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
90 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
92 // Adds leaves to mapping
93 for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
94 byMethodBuilder.put(leaf.getGetter(), leaf);
95 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
98 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
99 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
100 byMethodBuilder.put(childDataObj.getValue(), childProto);
101 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
102 byYangBuilder.put(childProto.getYangArg(), childProto);
103 if (childProto.isChoice()) {
104 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
105 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
106 byBindingArgClassBuilder.put(cazeChild, childProto);
110 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
111 this.byYang = ImmutableMap.copyOf(byYangBuilder);
112 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
113 byBindingArgClassBuilder.putAll(byStreamClass);
114 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
117 if (Augmentable.class.isAssignableFrom(getBindingClass())) {
118 this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
120 this.possibleAugmentations = ImmutableMap.of();
122 reloadAllAugmentations();
124 final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), getBindingClass(),
125 AugmentationHolder.class);
127 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
128 .asType(DATAOBJECT_TYPE);
129 } catch (NoSuchMethodException | IllegalAccessException e) {
130 throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
134 @SuppressFBWarnings("RV_RETURN_VALUE_OF_PUTIFABSENT_IGNORED")
135 private void reloadAllAugmentations() {
136 for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
137 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
138 if (augProto != null) {
139 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
140 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
145 @SuppressWarnings("unchecked")
147 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
148 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
149 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
153 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
154 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
155 if (childProto != null) {
158 if (Augmentation.class.isAssignableFrom(childClass)) {
159 return augmentationByClass(childClass);
164 @SuppressWarnings("unchecked")
166 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
167 final Class<C> childClass) {
168 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
169 if (childProto != null) {
170 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
172 return Optional.empty();
176 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
177 final List<YangInstanceIdentifier.PathArgument> builder) {
179 final Class<? extends DataObject> argType = arg.getType();
180 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
181 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
182 ctxProto = augmentationByClass(argType);
184 final DataContainerCodecContext<?, ?> context =
185 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
186 if (context instanceof ChoiceNodeCodecContext) {
187 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
188 choice.addYangPathArgument(arg, builder);
190 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
191 final Class<? extends DataObject> type = arg.getType();
192 final DataContainerCodecContext<?, ?> caze;
193 if (caseType.isPresent()) {
194 // Non-ambiguous addressing this should not pose any problems
195 caze = choice.streamChild(caseType.get());
197 caze = choice.getCaseByChildClass(type);
200 caze.addYangPathArgument(arg, builder);
201 return caze.bindingPathArgumentChild(arg, builder);
203 context.addYangPathArgument(arg, builder);
207 @SuppressWarnings("unchecked")
209 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
210 final NodeContextSupplier childSupplier;
211 if (arg instanceof NodeIdentifierWithPredicates) {
212 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
213 } else if (arg instanceof AugmentationIdentifier) {
214 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
216 childSupplier = byYang.get(arg);
219 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
220 "Argument %s is not valid child of %s", arg, getSchema()).get();
223 protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
224 final LeafNodeCodecContext<?> value = leafChild.get(name);
225 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
228 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
229 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
230 // Direct instantiation or use in same module in which grouping
232 DataSchemaNode sameName;
234 sameName = getSchema().getDataChildByName(origDef.getQName());
235 } catch (final IllegalArgumentException e) {
238 final DataSchemaNode childSchema;
239 if (sameName != null) {
240 // Exactly same schema node
241 if (origDef.equals(sameName)) {
242 childSchema = sameName;
243 // We check if instantiated node was added via uses
244 // statement and is instantiation of same grouping
245 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
246 childSchema = sameName;
248 // Node has same name, but clearly is different
252 // We are looking for instantiation via uses in other module
253 final QName instantiedName = origDef.getQName().withModule(namespace());
254 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
255 // We check if it is really instantiated from same
256 // definition as class was derived
257 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
258 childSchema = potential;
263 final DataSchemaNode nonNullChild =
264 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
265 return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
268 @SuppressWarnings("unchecked")
269 Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
270 return Item.of((Class<? extends DataObject>) childClass);
273 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
274 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
275 if (firstTry != null) {
278 if (possibleAugmentations.containsKey(arg)) {
279 reloadAllAugmentations();
280 return byYangAugmented.get(arg);
285 private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
286 final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
287 if (firstTry != null) {
290 reloadAllAugmentations();
291 return augmentationByClassOrEquivalentClass(childClass);
294 private @Nullable DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(
295 final @NonNull Class<?> childClass) {
296 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
297 if (childProto != null) {
302 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
303 * using reflection and walk all stream child and compare augmenations classes if they are
306 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
308 @SuppressWarnings("rawtypes")
309 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
310 if (getBindingClass().equals(augTarget)) {
311 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
312 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
313 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
321 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
322 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
323 @SuppressWarnings("rawtypes")
324 final Class augClass;
326 augClass = loader.loadClass(value);
327 } catch (final ClassNotFoundException e) {
328 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
332 @SuppressWarnings("unchecked")
333 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
334 .getResolvedAugmentationSchema(getSchema(), augClass);
335 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
338 @SuppressWarnings("rawtypes")
339 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
340 final NodeCodecContext<?> childContext = byMethod.get(method).get();
341 @SuppressWarnings("unchecked")
342 final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
343 if (domChild.isPresent()) {
344 return childContext.deserializeObject(domChild.get());
345 } else if (childContext instanceof LeafNodeCodecContext) {
346 return ((LeafNodeCodecContext)childContext).defaultObject();
352 @SuppressWarnings("checkstyle:illegalCatch")
353 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
355 return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
356 } catch (final Throwable e) {
357 Throwables.throwIfUnchecked(e);
358 throw new RuntimeException(e);
362 @SuppressWarnings("unchecked")
363 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
364 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
366 @SuppressWarnings("rawtypes")
367 final Map map = new HashMap<>();
369 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
370 if (childValue instanceof AugmentationNode) {
371 final AugmentationNode augDomNode = (AugmentationNode) childValue;
372 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
373 if (codecProto != null) {
374 final DataContainerCodecContext<?, ?> codec = codecProto.get();
375 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
379 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
380 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
381 if (augData.isPresent()) {
382 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
388 Collection<Method> getHashCodeAndEqualsMethods() {
389 return byMethod.keySet();
393 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
394 checkArgument(getDomPathArgument().equals(arg));
399 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
400 checkArgument(bindingArg().equals(arg));
401 return getDomPathArgument();