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.generator.api.ClassLoadingStrategy;
36 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
37 import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections;
38 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument;
39 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
40 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
41 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
42 import org.opendaylight.mdsal.binding.javav2.spec.structural.AugmentationHolder;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
52 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
54 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
55 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
60 public abstract class TreeNodeCodecContext<D extends TreeNode, T extends DataNodeContainer>
61 extends DataContainerCodecContext<D, T> {
63 private static final Logger LOG = LoggerFactory.getLogger(TreeNodeCodecContext.class);
64 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
65 private static final MethodType TREENODE_TYPE = MethodType.methodType(TreeNode.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<String, AnyxmlNodeCodecContext<?>> anyxmlChild;
70 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
71 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
72 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
73 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
74 private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
75 private final MethodHandle proxyConstructor;
77 private final ConcurrentMap<PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
78 new ConcurrentHashMap<>();
79 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
82 protected TreeNodeCodecContext(final DataContainerCodecPrototype<T> prototype) {
85 this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
86 this.anyxmlChild = factory().getAnyxmlNodes(getBindingClass(), getSchema());
88 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
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 AnyxmlNodeCodecContext<?> anyxml : anyxmlChild.values()) {
102 byMethodBuilder.put(anyxml.getGetter(), anyxml);
103 byYangBuilder.put(anyxml.getDomPathArgument(), anyxml);
106 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
107 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
108 byMethodBuilder.put(childDataObj.getValue(), childProto);
109 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
110 byYangBuilder.put(childProto.getYangArg(), childProto);
111 //TODO: get cases in consideration - finish in patches to come
112 //if (childProto.isChoice()) {
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);
121 if (Augmentable.class.isAssignableFrom(getBindingClass())) {
122 this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
124 this.possibleAugmentations = ImmutableMap.of();
126 reloadAllAugmentations();
128 final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(),
129 new Class[] { getBindingClass(), AugmentationHolder.class });
131 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
132 .asType(TREENODE_TYPE);
133 } catch (NoSuchMethodException | IllegalAccessException e) {
134 throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
138 private void reloadAllAugmentations() {
139 for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
140 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
141 if (augProto != null) {
142 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
143 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
149 @SuppressWarnings("unchecked")
151 public <C extends TreeNode> DataContainerCodecContext<C, ?> streamChild(@Nonnull final Class<C> childClass) {
152 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
153 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
157 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
158 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
159 if (childProto != null) {
162 if (Augmentation.class.isAssignableFrom(childClass)) {
163 return augmentationByClass(childClass);
168 @SuppressWarnings("unchecked")
170 public <C extends TreeNode> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
171 @Nonnull final Class<C> childClass) {
172 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
173 if (childProto != null) {
174 return Optional.of((DataContainerCodecContext<C,?>) childProto.get());
176 return Optional.empty();
181 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final TreeArgument<?> arg,
182 final List<PathArgument> builder) {
184 final Class<? extends TreeNode> argType = (Class<? extends TreeNode>) arg.getType();
185 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
186 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
187 ctxProto = augmentationByClass(argType);
189 final DataContainerCodecContext<?, ?> context =
190 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
191 //TODO: get cases in consideration - finish in patches to come
192 // if (context instanceof ChoiceNodeCodecContext) {
193 context.addYangPathArgument(arg, builder);
198 @SuppressWarnings("unchecked")
200 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
201 final NodeContextSupplier childSupplier;
202 if (arg instanceof NodeIdentifierWithPredicates) {
203 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
204 } else if (arg instanceof AugmentationIdentifier) {
205 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
207 childSupplier = byYang.get(arg);
210 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
211 "Argument %s is not valid child of %s", arg, getSchema()).get();
214 public final LeafNodeCodecContext<?> getLeafChild(final String name) {
215 final LeafNodeCodecContext<?> value = leafChild.get(name);
216 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
219 public final AnyxmlNodeCodecContext<?> getAnyxmlChild(final String name) {
220 final AnyxmlNodeCodecContext<?> value = anyxmlChild.get(name);
221 return IncorrectNestingException.checkNonNull(value, "Anyxml %s is not valid for %s", name, getBindingClass());
224 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
225 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
226 // Direct instantiation or use in same module in which grouping
228 DataSchemaNode sameName;
230 sameName = getSchema().getDataChildByName(origDef.getQName());
231 } catch (final IllegalArgumentException e) {
234 final DataSchemaNode childSchema;
235 if (sameName != null) {
236 // Exactly same schema node
237 if (origDef.equals(sameName)) {
238 childSchema = sameName;
239 // We check if instantiated node was added via uses
240 // statement and is instantiation of same grouping
241 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
242 childSchema = sameName;
244 // Node has same name, but clearly is different
248 // We are looking for instantiation via uses in other module
249 final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
250 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
251 // We check if it is really instantiated from same
252 // definition as class was derived
253 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
254 childSchema = potential;
259 final DataSchemaNode nonNullChild =
260 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
261 return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
264 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
265 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
266 if (firstTry != null) {
269 if (possibleAugmentations.containsKey(arg)) {
270 reloadAllAugmentations();
271 return byYangAugmented.get(arg);
277 private DataContainerCodecPrototype<?> augmentationByClass(@Nonnull final Class<?> childClass) {
278 final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
279 if (firstTry != null) {
282 reloadAllAugmentations();
283 return augmentationByClassOrEquivalentClass(childClass);
287 private DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
288 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
289 if (childProto != null) {
294 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
295 * using reflection and walk all stream child and compare augmenations classes if they are
298 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
300 @SuppressWarnings("rawtypes")
301 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
302 if (getBindingClass().equals(augTarget)) {
303 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
304 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
305 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
313 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
314 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
315 @SuppressWarnings("rawtypes")
316 final Class augClass;
318 augClass = loader.loadClass(value);
319 } catch (final ClassNotFoundException e) {
320 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
324 @SuppressWarnings("unchecked")
325 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
326 .getResolvedAugmentationSchema(getSchema(), augClass);
327 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
330 @SuppressWarnings("rawtypes")
331 public Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
332 final NodeCodecContext<?> childContext = byMethod.get(method).get();
333 @SuppressWarnings("unchecked")
334 final java.util.Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
335 if (domChild.isPresent()) {
336 return childContext.deserializeObject(domChild.get());
337 } else if (childContext instanceof LeafNodeCodecContext) {
338 return ((LeafNodeCodecContext)childContext).defaultObject();
344 @SuppressWarnings("checkstyle:illegalCatch")
345 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
347 return (D) proxyConstructor.invokeExact((InvocationHandler) new LazyTreeNode<>(this, node));
348 } catch (final Throwable e) {
349 throw Throwables.propagate(e);
353 @SuppressWarnings("unchecked")
354 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
355 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
357 @SuppressWarnings("rawtypes")
358 final Map map = new HashMap<>();
360 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
361 if (childValue instanceof AugmentationNode) {
362 final AugmentationNode augDomNode = (AugmentationNode) childValue;
363 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
364 if (codecProto != null) {
365 final DataContainerCodecContext<?, ?> codec = codecProto.get();
366 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
370 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
371 final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
372 if (augData.isPresent()) {
373 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
379 public Collection<Method> getHashCodeAndEqualsMethods() {
380 return byMethod.keySet();
384 public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
385 Preconditions.checkArgument(getDomPathArgument().equals(arg));
390 public YangInstanceIdentifier.PathArgument serializePathArgument(final TreeArgument arg) {
391 Preconditions.checkArgument(bindingArg().equals(arg));
392 return getDomPathArgument();