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.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Throwables;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableSortedMap;
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.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.AugmentationSchema;
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 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<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<PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
77 new ConcurrentHashMap<>();
78 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
81 protected TreeNodeCodecContext(final DataContainerCodecPrototype<T> prototype) {
84 this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
86 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
88 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
89 final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
90 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
91 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
93 // Adds leaves to mapping
94 for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
95 byMethodBuilder.put(leaf.getGetter(), leaf);
96 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
99 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
100 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
101 byMethodBuilder.put(childDataObj.getValue(), childProto);
102 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
103 byYangBuilder.put(childProto.getYangArg(), childProto);
104 //TODO: get cases in consideration - finish in patches to come
105 //if (childProto.isChoice()) {
107 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
108 this.byYang = ImmutableMap.copyOf(byYangBuilder);
109 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
110 byBindingArgClassBuilder.putAll(byStreamClass);
111 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
114 if (Augmentable.class.isAssignableFrom(getBindingClass())) {
115 this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
117 this.possibleAugmentations = ImmutableMap.of();
119 reloadAllAugmentations();
121 final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), new Class[] { getBindingClass(), AugmentationHolder.class });
123 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
124 .asType(TREENODE_TYPE);
125 } catch (NoSuchMethodException | IllegalAccessException e) {
126 throw new IllegalStateException("Failed to find contructor for class " + proxyClass);
130 private void reloadAllAugmentations() {
131 for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
132 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
133 if (augProto != null) {
134 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
135 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
141 @SuppressWarnings("unchecked")
143 public <DV extends TreeNode> DataContainerCodecContext<DV, ?> streamChild(@Nonnull final Class<DV> childClass) {
144 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
145 return (DataContainerCodecContext<DV, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
149 private final DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
150 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
151 if (childProto != null) {
154 if (Augmentation.class.isAssignableFrom(childClass)) {
155 return augmentationByClass(childClass);
160 @SuppressWarnings("unchecked")
162 public <DV extends TreeNode> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
163 @Nonnull final Class<DV> childClass) {
164 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
165 if (childProto != null) {
166 return Optional.of((DataContainerCodecContext<DV,?>) childProto.get());
168 return Optional.absent();
173 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final TreeArgument<?> arg,
174 final List<PathArgument> builder) {
176 final Class<? extends TreeNode> argType = (Class<? extends TreeNode>) arg.getType();
177 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
178 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
179 ctxProto = augmentationByClass(argType);
181 final DataContainerCodecContext<?, ?> context =
182 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
183 //TODO: get cases in consideration - finish in patches to come
184 // if (context instanceof ChoiceNodeCodecContext) {
185 context.addYangPathArgument(arg, builder);
190 @SuppressWarnings("unchecked")
192 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
193 final NodeContextSupplier childSupplier;
194 if (arg instanceof NodeIdentifierWithPredicates) {
195 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
196 } else if (arg instanceof AugmentationIdentifier) {
197 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
199 childSupplier = byYang.get(arg);
202 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
203 "Argument %s is not valid child of %s", arg, getSchema()).get();
206 protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
207 final LeafNodeCodecContext<?> value = leafChild.get(name);
208 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
211 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
212 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
213 // Direct instantiation or use in same module in which grouping
215 DataSchemaNode sameName;
217 sameName = getSchema().getDataChildByName(origDef.getQName());
218 } catch (final IllegalArgumentException e) {
221 final DataSchemaNode childSchema;
222 if (sameName != null) {
223 // Exactly same schema node
224 if (origDef.equals(sameName)) {
225 childSchema = sameName;
226 // We check if instantiated node was added via uses
227 // statement and is instantiation of same grouping
228 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
229 childSchema = sameName;
231 // Node has same name, but clearly is different
235 // We are looking for instantiation via uses in other module
236 final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
237 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
238 // We check if it is really instantiated from same
239 // definition as class was derived
240 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
241 childSchema = potential;
246 final DataSchemaNode nonNullChild =
247 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
248 return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
251 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
252 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
253 if (firstTry != null) {
256 if (possibleAugmentations.containsKey(arg)) {
257 reloadAllAugmentations();
258 return byYangAugmented.get(arg);
264 private DataContainerCodecPrototype<?> augmentationByClass(@Nonnull final Class<?> childClass) {
265 final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
266 if (firstTry != null) {
269 reloadAllAugmentations();
270 return augmentationByClassOrEquivalentClass(childClass);
274 private final DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
275 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
276 if (childProto != null) {
281 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
282 * using reflection and walk all stream child and compare augmenations classes if they are
285 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
287 @SuppressWarnings("rawtypes")
288 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
289 if ((getBindingClass().equals(augTarget))) {
290 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
291 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
292 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
300 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
301 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
302 @SuppressWarnings("rawtypes")
303 final Class augClass;
305 augClass = loader.loadClass(value);
306 } catch (final ClassNotFoundException e) {
307 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
311 @SuppressWarnings("unchecked")
312 final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
313 .getResolvedAugmentationSchema(getSchema(), augClass);
314 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
317 @SuppressWarnings("rawtypes")
318 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
319 final NodeCodecContext<?> childContext = byMethod.get(method).get();
320 @SuppressWarnings("unchecked")
321 final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
322 if (domChild.isPresent()) {
323 return childContext.deserializeObject(domChild.get());
324 } else if (childContext instanceof LeafNodeCodecContext) {
325 return ((LeafNodeCodecContext)childContext).defaultObject();
331 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
333 return (D) proxyConstructor.invokeExact((InvocationHandler) new LazyTreeNode<>(this, node));
334 } catch (final Throwable e) {
335 throw Throwables.propagate(e);
339 @SuppressWarnings("unchecked")
340 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
341 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
343 @SuppressWarnings("rawtypes")
344 final Map map = new HashMap<>();
346 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
347 if (childValue instanceof AugmentationNode) {
348 final AugmentationNode augDomNode = (AugmentationNode) childValue;
349 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
350 if (codecProto != null) {
351 final DataContainerCodecContext<?, ?> codec = codecProto.get();
352 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
356 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
357 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
358 if (augData.isPresent()) {
359 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
365 public Collection<Method> getHashCodeAndEqualsMethods() {
366 return byMethod.keySet();
370 public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
371 Preconditions.checkArgument(getDomPathArgument().equals(arg));
376 public YangInstanceIdentifier.PathArgument serializePathArgument(final TreeArgument arg) {
377 Preconditions.checkArgument(bindingArg().equals(arg));
378 return getDomPathArgument();