2 * Copyright (c) 2017 Pantheon Technologies s.r.o. 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
9 package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base;
11 import com.google.common.annotations.Beta;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Throwables;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSortedMap;
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 javax.annotation.Nonnull;
34 import javax.annotation.Nullable;
35 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ChoiceNodeCodecContext;
36 import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy;
37 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
38 import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections;
39 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument;
40 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
41 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
42 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
43 import org.opendaylight.mdsal.binding.javav2.spec.structural.AugmentationHolder;
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.util.SchemaNodeUtils;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
61 public abstract class TreeNodeCodecContext<D extends TreeNode, T extends DataNodeContainer>
62 extends DataContainerCodecContext<D, T> {
64 private static final Logger LOG = LoggerFactory.getLogger(TreeNodeCodecContext.class);
65 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
66 private static final MethodType TREENODE_TYPE = MethodType.methodType(TreeNode.class, InvocationHandler.class);
67 private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
69 private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
70 private final ImmutableMap<String, AnyxmlNodeCodecContext<?>> anyxmlChild;
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<PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
79 new ConcurrentHashMap<>();
80 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
83 protected TreeNodeCodecContext(final DataContainerCodecPrototype<T> prototype) {
86 this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
87 this.anyxmlChild = factory().getAnyxmlNodes(getBindingClass(), getSchema());
89 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
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 AnyxmlNodeCodecContext<?> anyxml : anyxmlChild.values()) {
103 byMethodBuilder.put(anyxml.getGetter(), anyxml);
104 byYangBuilder.put(anyxml.getDomPathArgument(), anyxml);
107 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
108 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
109 byMethodBuilder.put(childDataObj.getValue(), childProto);
110 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
111 byYangBuilder.put(childProto.getYangArg(), childProto);
113 if (childProto.isChoice()) {
114 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
115 choice.getClassCaseChildren().entrySet().forEach(entry ->
116 byBindingArgClassBuilder.put(entry.getKey(), childProto));
118 choice.getYangCaseChildren().entrySet().forEach(entry ->
119 byYangBuilder.put(entry.getKey(), childProto));
123 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
124 this.byYang = ImmutableMap.copyOf(byYangBuilder);
125 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
126 byBindingArgClassBuilder.putAll(byStreamClass);
127 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
130 if (Augmentable.class.isAssignableFrom(getBindingClass())) {
131 this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
133 this.possibleAugmentations = ImmutableMap.of();
135 reloadAllAugmentations();
137 final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(),
138 new Class[] { getBindingClass(), AugmentationHolder.class });
140 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
141 .asType(TREENODE_TYPE);
142 } catch (NoSuchMethodException | IllegalAccessException e) {
143 throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
147 private void reloadAllAugmentations() {
148 for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
149 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
150 if (augProto != null) {
151 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
152 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
158 @SuppressWarnings("unchecked")
160 public <C extends TreeNode> DataContainerCodecContext<C, ?> streamChild(@Nonnull final Class<C> childClass) {
161 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
162 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
166 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
167 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
168 if (childProto != null) {
171 if (Augmentation.class.isAssignableFrom(childClass)) {
172 return augmentationByClass(childClass);
177 @SuppressWarnings("unchecked")
179 public <C extends TreeNode> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
180 @Nonnull final Class<C> childClass) {
181 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
182 if (childProto != null) {
183 return Optional.of((DataContainerCodecContext<C,?>) childProto.get());
185 return Optional.empty();
190 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final TreeArgument<?> arg,
191 final List<PathArgument> builder) {
193 final Class<? extends TreeNode> argType = (Class<? extends TreeNode>) arg.getType();
194 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
195 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
196 ctxProto = augmentationByClass(argType);
198 final DataContainerCodecContext<?, ?> context =
199 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
201 if (context instanceof ChoiceNodeCodecContext) {
202 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
203 final DataContainerCodecContext<?, ?> caze = choice.getCaseByChildClass(argType);
204 // FIXME: Instance identifier should not reference choice or case as they're
205 // not data tree nodes.
206 return caze.bindingPathArgumentChild(arg, builder);
209 context.addYangPathArgument(arg, builder);
214 @SuppressWarnings("unchecked")
216 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
217 final NodeContextSupplier childSupplier;
218 if (arg instanceof NodeIdentifierWithPredicates) {
219 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
220 } else if (arg instanceof AugmentationIdentifier) {
221 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
223 childSupplier = byYang.get(arg);
226 // FIXME: Since instance identifier does not reference choice or case,
227 // we should search in data children of choice/case
228 if (childSupplier instanceof DataContainerCodecPrototype) {
229 final DataContainerCodecContext<?,T> context = ((DataContainerCodecPrototype) childSupplier).get();
230 if (context instanceof ChoiceNodeCodecContext) {
231 return (NodeCodecContext<D>) childNonNull(((ChoiceNodeCodecContext) context).yangPathArgumentChild(arg),
232 arg, "Argument %s is not valid child of %s", arg, getSchema());
236 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
237 "Argument %s is not valid child of %s", arg, getSchema()).get();
240 public final LeafNodeCodecContext<?> getLeafChild(final String name) {
241 final LeafNodeCodecContext<?> value = leafChild.get(name);
242 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
245 public final AnyxmlNodeCodecContext<?> getAnyxmlChild(final String name) {
246 final AnyxmlNodeCodecContext<?> value = anyxmlChild.get(name);
247 return IncorrectNestingException.checkNonNull(value, "Anyxml %s is not valid for %s", name, getBindingClass());
250 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
251 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
252 // Direct instantiation or use in same module in which grouping
254 DataSchemaNode sameName;
256 sameName = getSchema().getDataChildByName(origDef.getQName());
257 } catch (final IllegalArgumentException e) {
260 final DataSchemaNode childSchema;
261 if (sameName != null) {
262 // Exactly same schema node
263 if (origDef.equals(sameName)) {
264 childSchema = sameName;
265 // We check if instantiated node was added via uses
266 // statement and is instantiation of same grouping
267 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
268 childSchema = sameName;
270 // Node has same name, but clearly is different
274 // We are looking for instantiation via uses in other module
275 final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
276 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
277 // We check if it is really instantiated from same
278 // definition as class was derived
279 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
280 childSchema = potential;
285 final DataSchemaNode nonNullChild =
286 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
287 return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
290 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
291 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
292 if (firstTry != null) {
295 if (possibleAugmentations.containsKey(arg)) {
296 reloadAllAugmentations();
297 return byYangAugmented.get(arg);
303 private DataContainerCodecPrototype<?> augmentationByClass(@Nonnull final Class<?> childClass) {
304 final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
305 if (firstTry != null) {
308 reloadAllAugmentations();
309 return augmentationByClassOrEquivalentClass(childClass);
313 private DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
314 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
315 if (childProto != null) {
320 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
321 * using reflection and walk all stream child and compare augmenations classes if they are
324 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
326 @SuppressWarnings("rawtypes")
327 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
328 if (getBindingClass().equals(augTarget)) {
329 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
330 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
331 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
339 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
340 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
341 @SuppressWarnings("rawtypes")
342 final Class augClass;
344 augClass = loader.loadClass(value);
345 } catch (final ClassNotFoundException e) {
346 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
350 @SuppressWarnings("unchecked")
351 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
352 .getResolvedAugmentationSchema(getSchema(), augClass);
353 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
356 @SuppressWarnings("rawtypes")
357 public Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
358 final NodeCodecContext<?> childContext = byMethod.get(method).get();
359 @SuppressWarnings("unchecked")
360 final java.util.Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
361 if (domChild.isPresent()) {
362 return childContext.deserializeObject(domChild.get());
363 } else if (childContext instanceof LeafNodeCodecContext) {
364 return ((LeafNodeCodecContext)childContext).defaultObject();
370 @SuppressWarnings("checkstyle:illegalCatch")
371 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
373 return (D) proxyConstructor.invokeExact((InvocationHandler) new LazyTreeNode<>(this, node));
374 } catch (final Throwable e) {
375 throw Throwables.propagate(e);
379 @SuppressWarnings("unchecked")
380 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
381 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
383 @SuppressWarnings("rawtypes")
384 final Map map = new HashMap<>();
386 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
387 if (childValue instanceof AugmentationNode) {
388 final AugmentationNode augDomNode = (AugmentationNode) childValue;
389 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
390 if (codecProto != null) {
391 final DataContainerCodecContext<?, ?> codec = codecProto.get();
392 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
396 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
397 final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
398 if (augData.isPresent()) {
399 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
405 public Collection<Method> getHashCodeAndEqualsMethods() {
406 return byMethod.keySet();
410 public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
411 Preconditions.checkArgument(getDomPathArgument().equals(arg));
416 public YangInstanceIdentifier.PathArgument serializePathArgument(final TreeArgument arg) {
417 Preconditions.checkArgument(bindingArg().equals(arg));
418 return getDomPathArgument();