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.yangtools.binding.data.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.AugmentationSchema;
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> extends DataContainerCodecContext<D,T> {
58 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
59 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
60 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
61 private static final Comparator<Method> METHOD_BY_ALPHABET = (o1, o2) -> o1.getName().compareTo(o2.getName());
63 private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
64 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
65 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
66 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
67 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
68 private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
69 private final MethodHandle proxyConstructor;
71 private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
72 new ConcurrentHashMap<>();
73 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
76 protected 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(), new Class[] { getBindingClass(), AugmentationHolder.class });
122 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
123 .asType(DATAOBJECT_TYPE);
124 } catch (NoSuchMethodException | IllegalAccessException e) {
125 throw new IllegalStateException("Failed to find contructor for class " + proxyClass);
129 private void reloadAllAugmentations() {
130 for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
131 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
132 if (augProto != null) {
133 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
134 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
139 @SuppressWarnings("unchecked")
141 public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass) {
142 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
143 return (DataContainerCodecContext<DV, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
147 private final DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
148 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
149 if (childProto != null) {
152 if (Augmentation.class.isAssignableFrom(childClass)) {
153 return augmentationByClass(childClass);
158 @SuppressWarnings("unchecked")
160 public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
161 final Class<DV> childClass) {
162 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
163 if (childProto != null) {
164 return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV,?>) childProto.get());
166 return Optional.absent();
170 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
171 final List<YangInstanceIdentifier.PathArgument> builder) {
173 final Class<? extends DataObject> argType = arg.getType();
174 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
175 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
176 ctxProto = augmentationByClass(argType);
178 final DataContainerCodecContext<?, ?> context =
179 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
180 if (context instanceof ChoiceNodeCodecContext) {
181 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
182 final DataContainerCodecContext<?, ?> caze = choice.getCazeByChildClass(arg.getType());
183 choice.addYangPathArgument(arg, builder);
184 caze.addYangPathArgument(arg, builder);
185 return caze.bindingPathArgumentChild(arg, builder);
187 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 protected 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 final 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 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 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
334 return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
335 } catch (final Throwable e) {
336 throw Throwables.propagate(e);
340 @SuppressWarnings("unchecked")
341 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
342 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
344 @SuppressWarnings("rawtypes")
345 final Map map = new HashMap<>();
347 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
348 if (childValue instanceof AugmentationNode) {
349 final AugmentationNode augDomNode = (AugmentationNode) childValue;
350 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
351 if (codecProto != null) {
352 final DataContainerCodecContext<?, ?> codec = codecProto.get();
353 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
357 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
358 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
359 if (augData.isPresent()) {
360 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
366 public Collection<Method> getHashCodeAndEqualsMethods() {
367 return byMethod.keySet();
371 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
372 Preconditions.checkArgument(getDomPathArgument().equals(arg));
377 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
378 Preconditions.checkArgument(bindingArg().equals(arg));
379 return getDomPathArgument();