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 org.opendaylight.yangtools.yang.binding.AugmentationHolder;
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.MethodHandles.Lookup;
20 import java.lang.invoke.MethodType;
21 import java.lang.reflect.InvocationHandler;
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Proxy;
24 import java.util.Collection;
25 import java.util.Comparator;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.SortedMap;
31 import java.util.TreeMap;
32 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
33 import org.opendaylight.yangtools.sal.binding.model.api.Type;
34 import org.opendaylight.yangtools.yang.binding.Augmentable;
35 import org.opendaylight.yangtools.yang.binding.Augmentation;
36 import org.opendaylight.yangtools.yang.binding.DataObject;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
38 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 abstract class DataObjectCodecContext<D extends DataObject,T extends DataNodeContainer> extends DataContainerCodecContext<D,T> {
55 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
56 private static final Lookup LOOKUP = MethodHandles.publicLookup();
57 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
58 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
59 private static final Comparator<Method> METHOD_BY_ALPHABET = new Comparator<Method>() {
61 public int compare(final Method o1, final Method o2) {
62 return o1.getName().compareTo(o2.getName());
66 private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
67 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
68 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
69 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
70 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
71 private final MethodHandle proxyConstructor;
73 protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
76 this.leafChild = factory().getLeafNodes(getBindingClass(), schema());
78 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
80 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
81 final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
82 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
83 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
85 // Adds leaves to mapping
86 for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
87 byMethodBuilder.put(leaf.getGetter(), leaf);
88 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
91 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
92 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
93 byMethodBuilder.put(childDataObj.getValue(), childProto);
94 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
95 byYangBuilder.put(childProto.getYangArg(), childProto);
96 if (childProto.isChoice()) {
97 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
98 for(final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
99 byBindingArgClassBuilder.put(cazeChild, childProto);
103 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
104 if (Augmentable.class.isAssignableFrom(getBindingClass())) {
105 final ImmutableMap<AugmentationIdentifier, Type> augmentations = factory().getRuntimeContext()
106 .getAvailableAugmentationTypes(schema());
107 for (final Entry<AugmentationIdentifier, Type> augment : augmentations.entrySet()) {
108 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
109 if (augProto != null) {
110 byYangBuilder.put(augProto.getYangArg(), augProto);
111 byStreamClassBuilder.put(augProto.getBindingClass(), augProto);
116 this.byYang = ImmutableMap.copyOf(byYangBuilder);
117 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
118 byBindingArgClassBuilder.putAll(byStreamClass);
119 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
121 final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), new Class[] { getBindingClass(), AugmentationHolder.class });
123 proxyConstructor = LOOKUP.findConstructor(proxyClass, CONSTRUCTOR_TYPE).asType(DATAOBJECT_TYPE);
124 } catch (NoSuchMethodException | IllegalAccessException e) {
125 throw new IllegalStateException("Failed to find contructor for class " + proxyClass);
130 @SuppressWarnings("unchecked")
132 public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass) {
133 DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
134 if (childProto != null) {
135 return (DataContainerCodecContext<DV,?>) childProto.get();
138 if (Augmentation.class.isAssignableFrom(childClass)) {
140 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
141 * using reflection and walk all stream child and compare augmenations classes
142 * if they are equivalent.
144 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
146 @SuppressWarnings("rawtypes")
147 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
148 if ((getBindingClass().equals(augTarget))) {
149 for (final DataContainerCodecPrototype<?> realChild : byStreamClass.values()) {
150 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
151 && BindingReflections.isSubstitutionFor(childClass,realChild.getBindingClass())) {
152 childProto = realChild;
158 Preconditions.checkArgument(childProto != null, " Child %s is not valid child.",childClass);
159 return (DataContainerCodecContext<DV, ?>) childProto.get();
163 @SuppressWarnings("unchecked")
165 public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
166 final Class<DV> childClass) {
167 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
168 if(childProto != null) {
169 return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV,?>) childProto.get());
171 return Optional.absent();
175 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
176 final List<YangInstanceIdentifier.PathArgument> builder) {
178 final Class<? extends DataObject> argType = arg.getType();
179 final DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
180 if(ctxProto != null) {
181 final DataContainerCodecContext<?,?> context = ctxProto.get();
182 if(context instanceof ChoiceNodeCodecContext) {
183 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
184 final DataContainerCodecContext<?,?> caze = choice.getCazeByChildClass(arg.getType());
186 choice.addYangPathArgument(arg, builder);
187 caze.addYangPathArgument(arg, builder);
188 return caze.bindingPathArgumentChild(arg, builder);
192 context.addYangPathArgument(arg, builder);
195 // Argument is not valid child.
199 @SuppressWarnings("unchecked")
201 public NodeCodecContext<D> yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg) {
202 if(arg instanceof NodeIdentifierWithPredicates) {
203 arg = new NodeIdentifier(arg.getNodeType());
205 final NodeContextSupplier childSupplier = byYang.get(arg);
206 Preconditions.checkArgument(childSupplier != null, "Argument %s is not valid child of %s", arg, schema());
207 return (NodeCodecContext<D>) childSupplier.get();
210 protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
211 final LeafNodeCodecContext<?> value = leafChild.get(name);
212 Preconditions.checkArgument(value != null, "Leaf %s is not valid for %s", name, getBindingClass());
216 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
217 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
218 // Direct instantiation or use in same module in which grouping
220 DataSchemaNode sameName;
222 sameName = schema().getDataChildByName(origDef.getQName());
223 } catch (final IllegalArgumentException e) {
226 final DataSchemaNode childSchema;
227 if (sameName != null) {
228 // Exactly same schema node
229 if (origDef.equals(sameName)) {
230 childSchema = sameName;
231 // We check if instantiated node was added via uses
232 // statement and is instantiation of same grouping
233 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
234 childSchema = sameName;
236 // Node has same name, but clearly is different
240 // We are looking for instantiation via uses in other module
241 final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
242 final DataSchemaNode potential = schema().getDataChildByName(instantiedName);
243 // We check if it is really instantiated from same
244 // definition as class was derived
245 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
246 childSchema = potential;
251 Preconditions.checkArgument(childSchema != null, "Node %s does not have child named %s", schema(), childClass);
252 return DataContainerCodecPrototype.from(childClass, childSchema, factory());
255 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
256 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
257 @SuppressWarnings("rawtypes")
258 final Class augClass;
260 augClass = loader.loadClass(value);
261 } catch (final ClassNotFoundException e) {
262 LOG.warn("Failed to load augmentation prototype for {}", value, e);
266 @SuppressWarnings("unchecked")
267 final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
268 .getResolvedAugmentationSchema(schema(), augClass);
269 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
272 @SuppressWarnings("rawtypes")
273 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
274 final NodeCodecContext<?> childContext = byMethod.get(method).get();
275 @SuppressWarnings("unchecked")
276 final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
277 if (domChild.isPresent()) {
278 return childContext.deserializeObject(domChild.get());
283 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
285 return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
286 } catch (final Throwable e) {
287 throw Throwables.propagate(e);
291 @SuppressWarnings("unchecked")
292 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
293 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
295 @SuppressWarnings("rawtypes")
296 final Map map = new HashMap<>();
298 for(final DataContainerCodecPrototype<?> value : byStreamClass.values()) {
299 if(Augmentation.class.isAssignableFrom(value.getBindingClass())) {
300 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
301 if(augData.isPresent()) {
302 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
309 public Collection<Method> getHashCodeAndEqualsMethods() {
310 // FIXME: Sort method in same order as in hashCode for generated class.
311 return byMethod.keySet();
315 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
316 Preconditions.checkArgument(getDomPathArgument().equals(arg));
321 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
322 Preconditions.checkArgument(bindingArg().equals(arg));
323 return getDomPathArgument();