Merge "BUG-869: added proper handling of nullable parameter"
[yangtools.git] / code-generator / binding-data-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / DataObjectCodecContext.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.binding.data.codec.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import java.lang.reflect.Method;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
20 import org.opendaylight.yangtools.sal.binding.model.api.Type;
21 import org.opendaylight.yangtools.yang.binding.Augmentable;
22 import org.opendaylight.yangtools.yang.binding.Augmentation;
23 import org.opendaylight.yangtools.yang.binding.DataObject;
24 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
25 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
34 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
35 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataContainerCodecContext<T> {
42     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
43
44     private final ImmutableMap<String, LeafNodeCodecContext> leafChild;
45     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
46     private final ImmutableMap<Method, NodeContextSupplier> byMethod;
47     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
48     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
49     protected final Method augmentationGetter;
50
51     protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
52         super(prototype);
53
54         this.leafChild = factory().getLeafNodes(bindingClass(), schema());
55
56         Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass());
57
58         Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
59         Map<Method, NodeContextSupplier> byMethodBuilder = new HashMap<>();
60         Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
61         Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
62
63         // Adds leaves to mapping
64         for (LeafNodeCodecContext leaf : leafChild.values()) {
65             byMethodBuilder.put(leaf.getGetter(), leaf);
66             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
67         }
68
69         for (Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
70             DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
71             byMethodBuilder.put(childDataObj.getValue(), childProto);
72             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
73             byYangBuilder.put(childProto.getYangArg(), childProto);
74             if (childProto.isChoice()) {
75                 ChoiceNodeCodecContext choice = (ChoiceNodeCodecContext) childProto.get();
76                 for(Class<?> cazeChild : choice.getCaseChildrenClasses()) {
77                     byBindingArgClassBuilder.put(cazeChild, childProto);
78                 }
79             }
80         }
81         this.byMethod = ImmutableMap.copyOf(byMethodBuilder);
82         if (Augmentable.class.isAssignableFrom(bindingClass())) {
83             try {
84                 augmentationGetter = bindingClass().getMethod("getAugmentation", Class.class);
85             } catch (NoSuchMethodException | SecurityException e) {
86                throw new IllegalStateException("Could not get required method.",e);
87             }
88             ImmutableMap<AugmentationIdentifier, Type> augmentations = factory().getRuntimeContext()
89                     .getAvailableAugmentationTypes(schema());
90             for (Entry<AugmentationIdentifier, Type> augment : augmentations.entrySet()) {
91                 DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
92                 if (augProto != null) {
93                     byYangBuilder.put(augProto.getYangArg(), augProto);
94                     byStreamClassBuilder.put(augProto.getBindingClass(), augProto);
95                 }
96             }
97         } else {
98             augmentationGetter = null;
99         }
100
101         this.byYang = ImmutableMap.copyOf(byYangBuilder);
102         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
103         byBindingArgClassBuilder.putAll(byStreamClass);
104         this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
105     }
106
107     @Override
108     protected DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) {
109         DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
110         if (childProto != null) {
111             return childProto.get();
112         }
113
114         if (Augmentation.class.isAssignableFrom(childClass))  {
115             /*
116              * It is potentially mismatched valid augmentation - we look up equivalent augmentation
117              * using reflection and walk all stream child and compare augmenations classes
118              * if they are equivalent.
119              *
120              * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
121              */
122             Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
123             if ((bindingClass().equals(augTarget))) {
124                 for (DataContainerCodecPrototype<?> realChild : byStreamClass.values()) {
125                     if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
126                             && BindingReflections.isSubstitutionFor(childClass,realChild.getBindingClass())) {
127                         childProto = realChild;
128                         break;
129                     }
130                 }
131             }
132         }
133         Preconditions.checkArgument(childProto != null, " Child %s is not valid child.",childClass);
134         return childProto.get();
135     }
136
137     @Override
138     protected Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass) {
139         DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
140         if(childProto != null) {
141             return Optional.<DataContainerCodecContext<?>>of(childProto.get());
142         }
143         return Optional.absent();
144     }
145
146     @Override
147     protected DataContainerCodecContext<?> getIdentifierChild(final InstanceIdentifier.PathArgument arg,
148             final List<YangInstanceIdentifier.PathArgument> builder) {
149
150         Class<? extends DataObject> argType = arg.getType();
151         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
152         Preconditions.checkArgument(ctxProto != null,"Invalid child");
153
154         DataContainerCodecContext<?> context = ctxProto.get();
155         if(context instanceof ChoiceNodeCodecContext) {
156             ChoiceNodeCodecContext casted = (ChoiceNodeCodecContext) context;
157             casted.addYangPathArgument(arg, builder);
158             DataContainerCodecContext<?> caze = casted.getCazeByChildClass(arg.getType());
159             caze.addYangPathArgument(arg, builder);
160             return caze.getIdentifierChild(arg, builder);
161         }
162         context.addYangPathArgument(arg, builder);
163         return context;
164     }
165
166     @Override
167     protected NodeCodecContext getYangIdentifierChild(YangInstanceIdentifier.PathArgument arg) {
168         if(arg instanceof NodeIdentifierWithPredicates) {
169             arg = new NodeIdentifier(arg.getNodeType());
170         }
171         NodeContextSupplier childSupplier = byYang.get(arg);
172         Preconditions.checkArgument(childSupplier != null, "Argument %s is not valid child of %s", arg, schema());
173         return childSupplier.get();
174     }
175
176     protected final LeafNodeCodecContext getLeafChild(final String name) {
177         final LeafNodeCodecContext value = leafChild.get(name);
178         Preconditions.checkArgument(value != null, "Leaf %s is not valid for %s", name, bindingClass());
179         return value;
180     }
181
182     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
183         DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
184         // Direct instantiation or use in same module in which grouping
185         // was defined.
186         DataSchemaNode sameName;
187         try {
188             sameName = schema().getDataChildByName(origDef.getQName());
189         } catch (IllegalArgumentException e) {
190             sameName = null;
191         }
192         final DataSchemaNode childSchema;
193         if (sameName != null) {
194             // Exactly same schema node
195             if (origDef.equals(sameName)) {
196                 childSchema = sameName;
197                 // We check if instantiated node was added via uses
198                 // statement and is instantiation of same grouping
199             } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
200                 childSchema = sameName;
201             } else {
202                 // Node has same name, but clearly is different
203                 childSchema = null;
204             }
205         } else {
206             // We are looking for instantiation via uses in other module
207             QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
208             DataSchemaNode potential = schema().getDataChildByName(instantiedName);
209             // We check if it is really instantiated from same
210             // definition as class was derived
211             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
212                 childSchema = potential;
213             } else {
214                 childSchema = null;
215             }
216         }
217         Preconditions.checkArgument(childSchema != null, "Node %s does not have child named %s", schema(), childClass);
218         return DataContainerCodecPrototype.from(childClass, childSchema, factory());
219     }
220
221     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
222         ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
223         @SuppressWarnings("rawtypes")
224         final Class augClass;
225         try {
226             augClass = loader.loadClass(value);
227         } catch (ClassNotFoundException e) {
228             LOG.warn("Failed to load augmentation prototype for {}", value, e);
229             return null;
230         }
231
232         Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
233                 .getResolvedAugmentationSchema(schema(), augClass);
234         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
235     }
236
237     @SuppressWarnings("rawtypes")
238     Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
239         NodeCodecContext childContext = byMethod.get(method).get();
240         Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
241         if (domChild.isPresent()) {
242             return childContext.dataFromNormalizedNode(domChild.get());
243         }
244         return null;
245     }
246
247     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
248             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
249
250         @SuppressWarnings("rawtypes")
251         Map map = new HashMap<>();
252
253         for(DataContainerCodecPrototype<?> value : byStreamClass.values()) {
254             if(Augmentation.class.isAssignableFrom(value.getBindingClass())) {
255                 Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
256                 if(augData.isPresent()) {
257                     map.put(value.getBindingClass(), value.get().dataFromNormalizedNode(augData.get()));
258                 }
259             }
260         }
261         return map;
262     }
263
264     public Collection<Method> getHashCodeAndEqualsMethods() {
265         // FIXME: Sort method in same order as in hashCode for generated class.
266         return byMethod.keySet();
267     }
268
269 }