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 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<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(),
122 new Class[] { getBindingClass(), AugmentationHolder.class });
124 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
125 .asType(TREENODE_TYPE);
126 } catch (NoSuchMethodException | IllegalAccessException e) {
127 throw new IllegalStateException("Failed to find contructor for class " + proxyClass);
131 private void reloadAllAugmentations() {
132 for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
133 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
134 if (augProto != null) {
135 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
136 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
142 @SuppressWarnings("unchecked")
144 public <C extends TreeNode> DataContainerCodecContext<C, ?> streamChild(@Nonnull final Class<C> childClass) {
145 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
146 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
150 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
151 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
152 if (childProto != null) {
155 if (Augmentation.class.isAssignableFrom(childClass)) {
156 return augmentationByClass(childClass);
161 @SuppressWarnings("unchecked")
163 public <C extends TreeNode> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
164 @Nonnull final Class<C> childClass) {
165 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
166 if (childProto != null) {
167 return Optional.of((DataContainerCodecContext<C,?>) childProto.get());
169 return Optional.absent();
174 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final TreeArgument<?> arg,
175 final List<PathArgument> builder) {
177 final Class<? extends TreeNode> argType = (Class<? extends TreeNode>) arg.getType();
178 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
179 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
180 ctxProto = augmentationByClass(argType);
182 final DataContainerCodecContext<?, ?> context =
183 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
184 //TODO: get cases in consideration - finish in patches to come
185 // if (context instanceof ChoiceNodeCodecContext) {
186 context.addYangPathArgument(arg, builder);
191 @SuppressWarnings("unchecked")
193 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
194 final NodeContextSupplier childSupplier;
195 if (arg instanceof NodeIdentifierWithPredicates) {
196 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
197 } else if (arg instanceof AugmentationIdentifier) {
198 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
200 childSupplier = byYang.get(arg);
203 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
204 "Argument %s is not valid child of %s", arg, getSchema()).get();
207 public final LeafNodeCodecContext<?> getLeafChild(final String name) {
208 final LeafNodeCodecContext<?> value = leafChild.get(name);
209 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
212 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
213 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
214 // Direct instantiation or use in same module in which grouping
216 DataSchemaNode sameName;
218 sameName = getSchema().getDataChildByName(origDef.getQName());
219 } catch (final IllegalArgumentException e) {
222 final DataSchemaNode childSchema;
223 if (sameName != null) {
224 // Exactly same schema node
225 if (origDef.equals(sameName)) {
226 childSchema = sameName;
227 // We check if instantiated node was added via uses
228 // statement and is instantiation of same grouping
229 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
230 childSchema = sameName;
232 // Node has same name, but clearly is different
236 // We are looking for instantiation via uses in other module
237 final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
238 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
239 // We check if it is really instantiated from same
240 // definition as class was derived
241 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
242 childSchema = potential;
247 final DataSchemaNode nonNullChild =
248 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
249 return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
252 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
253 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
254 if (firstTry != null) {
257 if (possibleAugmentations.containsKey(arg)) {
258 reloadAllAugmentations();
259 return byYangAugmented.get(arg);
265 private DataContainerCodecPrototype<?> augmentationByClass(@Nonnull final Class<?> childClass) {
266 final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
267 if (firstTry != null) {
270 reloadAllAugmentations();
271 return augmentationByClassOrEquivalentClass(childClass);
275 private DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
276 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
277 if (childProto != null) {
282 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
283 * using reflection and walk all stream child and compare augmenations classes if they are
286 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
288 @SuppressWarnings("rawtypes")
289 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
290 if ((getBindingClass().equals(augTarget))) {
291 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
292 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
293 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
301 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
302 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
303 @SuppressWarnings("rawtypes")
304 final Class augClass;
306 augClass = loader.loadClass(value);
307 } catch (final ClassNotFoundException e) {
308 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
312 @SuppressWarnings("unchecked")
313 final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
314 .getResolvedAugmentationSchema(getSchema(), augClass);
315 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
318 @SuppressWarnings("rawtypes")
319 public Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
320 final NodeCodecContext<?> childContext = byMethod.get(method).get();
321 @SuppressWarnings("unchecked")
322 final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
323 if (domChild.isPresent()) {
324 return childContext.deserializeObject(domChild.get());
325 } else if (childContext instanceof LeafNodeCodecContext) {
326 return ((LeafNodeCodecContext)childContext).defaultObject();
332 @SuppressWarnings("checkstyle:illegalCatch")
333 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
335 return (D) proxyConstructor.invokeExact((InvocationHandler) new LazyTreeNode<>(this, node));
336 } catch (final Throwable e) {
337 throw Throwables.propagate(e);
341 @SuppressWarnings("unchecked")
342 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
343 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
345 @SuppressWarnings("rawtypes")
346 final Map map = new HashMap<>();
348 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
349 if (childValue instanceof AugmentationNode) {
350 final AugmentationNode augDomNode = (AugmentationNode) childValue;
351 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
352 if (codecProto != null) {
353 final DataContainerCodecContext<?, ?> codec = codecProto.get();
354 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
358 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
359 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
360 if (augData.isPresent()) {
361 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
367 public Collection<Method> getHashCodeAndEqualsMethods() {
368 return byMethod.keySet();
372 public TreeArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
373 Preconditions.checkArgument(getDomPathArgument().equals(arg));
378 public YangInstanceIdentifier.PathArgument serializePathArgument(final TreeArgument arg) {
379 Preconditions.checkArgument(bindingArg().equals(arg));
380 return getDomPathArgument();