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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableSortedMap;
15 import java.lang.invoke.MethodHandle;
16 import java.lang.invoke.MethodHandles;
17 import java.lang.invoke.MethodType;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Proxy;
21 import java.util.Collection;
22 import java.util.Comparator;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.Map.Entry;
27 import java.util.SortedMap;
28 import java.util.TreeMap;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
34 import org.opendaylight.mdsal.binding.model.api.Type;
35 import org.opendaylight.yangtools.yang.binding.Augmentable;
36 import org.opendaylight.yangtools.yang.binding.Augmentation;
37 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
47 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
52 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer>
58 extends DataContainerCodecContext<D, T> {
59 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
60 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
61 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
62 private static final Comparator<Method> METHOD_BY_ALPHABET = (o1, o2) -> o1.getName().compareTo(o2.getName());
64 private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
65 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
66 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
67 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
68 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
69 private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
70 private final MethodHandle proxyConstructor;
72 private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
73 new ConcurrentHashMap<>();
74 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
76 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
79 this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
81 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
83 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
84 final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
85 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
86 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
88 // Adds leaves to mapping
89 for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
90 byMethodBuilder.put(leaf.getGetter(), leaf);
91 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
94 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
95 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
96 byMethodBuilder.put(childDataObj.getValue(), childProto);
97 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
98 byYangBuilder.put(childProto.getYangArg(), childProto);
99 if (childProto.isChoice()) {
100 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
101 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
102 byBindingArgClassBuilder.put(cazeChild, childProto);
106 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
107 this.byYang = ImmutableMap.copyOf(byYangBuilder);
108 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
109 byBindingArgClassBuilder.putAll(byStreamClass);
110 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
113 if (Augmentable.class.isAssignableFrom(getBindingClass())) {
114 this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
116 this.possibleAugmentations = ImmutableMap.of();
118 reloadAllAugmentations();
120 final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), getBindingClass(),
121 AugmentationHolder.class);
123 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
124 .asType(DATAOBJECT_TYPE);
125 } catch (NoSuchMethodException | IllegalAccessException e) {
126 throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
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);
140 @SuppressWarnings("unchecked")
142 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
143 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
144 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
148 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
149 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
150 if (childProto != null) {
153 if (Augmentation.class.isAssignableFrom(childClass)) {
154 return augmentationByClass(childClass);
159 @SuppressWarnings("unchecked")
161 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
162 final Class<C> childClass) {
163 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
164 if (childProto != null) {
165 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
167 return Optional.absent();
171 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
172 final List<YangInstanceIdentifier.PathArgument> builder) {
174 final Class<? extends DataObject> argType = arg.getType();
175 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
176 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
177 ctxProto = augmentationByClass(argType);
179 final DataContainerCodecContext<?, ?> context =
180 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
181 if (context instanceof ChoiceNodeCodecContext) {
182 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
183 final DataContainerCodecContext<?, ?> caze = choice.getCazeByChildClass(arg.getType());
184 choice.addYangPathArgument(arg, builder);
185 caze.addYangPathArgument(arg, builder);
186 return caze.bindingPathArgumentChild(arg, builder);
188 context.addYangPathArgument(arg, builder);
192 @SuppressWarnings("unchecked")
194 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
195 final NodeContextSupplier childSupplier;
196 if (arg instanceof NodeIdentifierWithPredicates) {
197 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
198 } else if (arg instanceof AugmentationIdentifier) {
199 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
201 childSupplier = byYang.get(arg);
204 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
205 "Argument %s is not valid child of %s", arg, getSchema()).get();
208 protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
209 final LeafNodeCodecContext<?> value = leafChild.get(name);
210 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
213 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
214 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
215 // Direct instantiation or use in same module in which grouping
217 DataSchemaNode sameName;
219 sameName = getSchema().getDataChildByName(origDef.getQName());
220 } catch (final IllegalArgumentException e) {
223 final DataSchemaNode childSchema;
224 if (sameName != null) {
225 // Exactly same schema node
226 if (origDef.equals(sameName)) {
227 childSchema = sameName;
228 // We check if instantiated node was added via uses
229 // statement and is instantiation of same grouping
230 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
231 childSchema = sameName;
233 // Node has same name, but clearly is different
237 // We are looking for instantiation via uses in other module
238 final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
239 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
240 // We check if it is really instantiated from same
241 // definition as class was derived
242 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
243 childSchema = potential;
248 final DataSchemaNode nonNullChild =
249 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
250 return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
253 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
254 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
255 if (firstTry != null) {
258 if (possibleAugmentations.containsKey(arg)) {
259 reloadAllAugmentations();
260 return byYangAugmented.get(arg);
266 private DataContainerCodecPrototype<?> augmentationByClass(@Nonnull final Class<?> childClass) {
267 final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
268 if (firstTry != null) {
271 reloadAllAugmentations();
272 return augmentationByClassOrEquivalentClass(childClass);
276 private DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
277 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
278 if (childProto != null) {
283 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
284 * using reflection and walk all stream child and compare augmenations classes if they are
287 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
289 @SuppressWarnings("rawtypes")
290 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
291 if (getBindingClass().equals(augTarget)) {
292 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
293 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
294 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
302 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
303 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
304 @SuppressWarnings("rawtypes")
305 final Class augClass;
307 augClass = loader.loadClass(value);
308 } catch (final ClassNotFoundException e) {
309 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
313 @SuppressWarnings("unchecked")
314 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
315 .getResolvedAugmentationSchema(getSchema(), augClass);
316 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
319 @SuppressWarnings("rawtypes")
320 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
321 final NodeCodecContext<?> childContext = byMethod.get(method).get();
322 @SuppressWarnings("unchecked")
323 final java.util.Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
324 if (domChild.isPresent()) {
325 return childContext.deserializeObject(domChild.get());
326 } else if (childContext instanceof LeafNodeCodecContext) {
327 return ((LeafNodeCodecContext)childContext).defaultObject();
333 @SuppressWarnings("checkstyle:illegalCatch")
334 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
336 return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
337 } catch (final Throwable e) {
338 Throwables.throwIfUnchecked(e);
339 throw new RuntimeException(e);
343 @SuppressWarnings("unchecked")
344 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
345 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
347 @SuppressWarnings("rawtypes")
348 final Map map = new HashMap<>();
350 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
351 if (childValue instanceof AugmentationNode) {
352 final AugmentationNode augDomNode = (AugmentationNode) childValue;
353 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
354 if (codecProto != null) {
355 final DataContainerCodecContext<?, ?> codec = codecProto.get();
356 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
360 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
361 final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
362 if (augData.isPresent()) {
363 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
369 Collection<Method> getHashCodeAndEqualsMethods() {
370 return byMethod.keySet();
374 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
375 Preconditions.checkArgument(getDomPathArgument().equals(arg));
380 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
381 Preconditions.checkArgument(bindingArg().equals(arg));
382 return getDomPathArgument();