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