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 / BindingCodecContext.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.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.ImmutableSortedMap;
13
14 import java.lang.reflect.Constructor;
15 import java.lang.reflect.InvocationTargetException;
16 import java.lang.reflect.Method;
17 import java.lang.reflect.ParameterizedType;
18 import java.lang.reflect.Type;
19 import java.util.AbstractMap.SimpleEntry;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.LinkedList;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.concurrent.Callable;
27
28 import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
29 import org.opendaylight.yangtools.concepts.Codec;
30 import org.opendaylight.yangtools.concepts.Immutable;
31 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
32 import org.opendaylight.yangtools.util.ClassLoaderUtils;
33 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
34 import org.opendaylight.yangtools.yang.binding.BindingMapping;
35 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
36 import org.opendaylight.yangtools.yang.binding.Identifiable;
37 import org.opendaylight.yangtools.yang.binding.Identifier;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
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.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
55
56 class BindingCodecContext implements CodecContextFactory, Immutable {
57
58     private static final String GETTER_PREFIX = "get";
59     private final SchemaRootCodecContext root;
60     private final BindingRuntimeContext context;
61     private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec =
62             new InstanceIdentifierCodec();
63     private final Codec<QName, Class<?>> identityCodec = new IdentityCodec();
64
65     public BindingCodecContext(final BindingRuntimeContext context) {
66         this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
67         this.root = SchemaRootCodecContext.create(this);
68     }
69
70     @Override
71     public BindingRuntimeContext getRuntimeContext() {
72         return context;
73     }
74
75     public Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
76         return instanceIdentifierCodec;
77     }
78
79     public Codec<QName, Class<?>> getIdentityCodec() {
80         return identityCodec;
81     }
82
83     public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
84             final NormalizedNodeStreamWriter domWriter) {
85         LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
86         DataContainerCodecContext<?> codecContext = getCodecContextNode(path, yangArgs);
87         BindingStreamEventWriter writer = new BindingToNormalizedStreamWriter(codecContext, domWriter);
88         return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), writer);
89     }
90
91     public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
92             final NormalizedNodeStreamWriter domWriter) {
93         return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
94     }
95
96     public DataContainerCodecContext<?> getCodecContextNode(final InstanceIdentifier<?> binding,
97             final List<YangInstanceIdentifier.PathArgument> builder) {
98         DataContainerCodecContext<?> currentNode = root;
99         for (InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
100             currentNode = currentNode.getIdentifierChild(bindingArg, builder);
101         }
102         return currentNode;
103     }
104
105     public NodeCodecContext getCodecContextNode(final YangInstanceIdentifier dom,
106             final List<InstanceIdentifier.PathArgument> builder) {
107         NodeCodecContext currentNode = root;
108         ListNodeCodecContext currentList = null;
109         for (YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
110             Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?>);
111             DataContainerCodecContext<?> previous = (DataContainerCodecContext<?>) currentNode;
112             NodeCodecContext nextNode = previous.getYangIdentifierChild(domArg);
113             /*
114              * List representation in YANG Instance Identifier consists of two
115              * arguments: first is list as a whole, second is list as an item so
116              * if it is /list it means list as whole, if it is /list/list - it
117              * is wildcarded and if it is /list/list[key] it is concrete item,
118              * all this variations are expressed in Binding Aware Instance
119              * Identifier as Item or IdentifiableItem
120              */
121             if (currentList != null) {
122
123                 if (currentList == nextNode) {
124
125                     // We entered list, so now we have all information to emit
126                     // list
127                     // path using second list argument.
128                     builder.add(currentList.getBindingPathArgument(domArg));
129                     currentList = null;
130                     currentNode = nextNode;
131                 } else {
132                     throw new IllegalArgumentException(
133                             "List should be referenced two times in YANG Instance Identifier");
134                 }
135             } else if (nextNode instanceof ListNodeCodecContext) {
136                 // We enter list, we do not update current Node yet,
137                 // since we need to verify
138                 currentList = (ListNodeCodecContext) nextNode;
139             } else if (nextNode instanceof ChoiceNodeCodecContext) {
140                 // We do not add path argument for choice, since
141                 // it is not supported by binding instance identifier.
142                 currentNode = nextNode;
143             } else if (nextNode instanceof DataContainerCodecContext<?>) {
144                 builder.add(((DataContainerCodecContext<?>) nextNode).getBindingPathArgument(domArg));
145                 currentNode = nextNode;
146             } else if (nextNode instanceof LeafNodeCodecContext) {
147                 Preconditions.checkArgument(builder == null, "Instance Identifier for leaf is not representable.");
148
149             }
150         }
151         // Algorithm ended in list as whole representation
152         // we sill need to emit identifier for list
153
154         if (builder != null) {
155             Preconditions.checkArgument(!(currentNode instanceof ChoiceNodeCodecContext),
156                     "Instance Identifier for choice is not representable.");
157             Preconditions.checkArgument(!(currentNode instanceof CaseNodeCodecContext),
158                     "Instance Identifier for case is not representable.");
159         }
160         if (currentList != null) {
161             builder.add(currentList.getBindingPathArgument(null));
162             return currentList;
163         }
164         return currentNode;
165     }
166
167     @Override
168     public ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(final Class<?> parentClass,
169             final DataNodeContainer childSchema) {
170         HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
171         for (DataSchemaNode leaf : childSchema.getChildNodes()) {
172             final TypeDefinition<?> typeDef;
173             if (leaf instanceof LeafSchemaNode) {
174                 typeDef = ((LeafSchemaNode) leaf).getType();
175             } else if (leaf instanceof LeafListSchemaNode) {
176                 typeDef = ((LeafListSchemaNode) leaf).getType();
177             } else {
178                 continue;
179             }
180
181             String getterName = getGetterName(leaf.getQName(), typeDef);
182             getterToLeafSchema.put(getterName, leaf);
183         }
184         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
185     }
186
187     private String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
188         String suffix = BindingMapping.getClassName(qName);
189
190         while (typeDef.getBaseType() != null) {
191             typeDef = typeDef.getBaseType();
192         }
193         if (typeDef instanceof BooleanTypeDefinition) {
194             return "is" + suffix;
195         }
196         return GETTER_PREFIX + suffix;
197     }
198
199     private ImmutableMap<String, LeafNodeCodecContext> getLeafNodesUsingReflection(final Class<?> parentClass,
200             final Map<String, DataSchemaNode> getterToLeafSchema) {
201         Map<String, LeafNodeCodecContext> leaves = new HashMap<>();
202         for (Method method : parentClass.getMethods()) {
203             if (method.getParameterTypes().length == 0) {
204                 DataSchemaNode schema = getterToLeafSchema.get(method.getName());
205                 final Class<?> valueType;
206                 if (schema instanceof LeafSchemaNode) {
207                     valueType = method.getReturnType();
208                 } else if (schema instanceof LeafListSchemaNode) {
209                     Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
210
211                     if (genericType instanceof Class<?>) {
212                         valueType = (Class<?>) genericType;
213                     } else if (genericType instanceof ParameterizedType) {
214                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
215                     } else {
216                         throw new IllegalStateException("Unexpected return type " + genericType);
217                     }
218                 } else {
219                     continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
220                 }
221                 Codec<Object, Object> codec = getCodec(valueType, schema);
222                 final LeafNodeCodecContext leafNode = new LeafNodeCodecContext(schema, codec, method);
223                 leaves.put(schema.getQName().getLocalName(), leafNode);
224             }
225         }
226         return ImmutableMap.copyOf(leaves);
227     }
228
229
230
231     private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
232         if (Class.class.equals(valueType)) {
233             @SuppressWarnings({ "unchecked", "rawtypes" })
234             final Codec<Object, Object> casted = (Codec) identityCodec;
235             return casted;
236         } else if (InstanceIdentifier.class.equals(valueType)) {
237             @SuppressWarnings({ "unchecked", "rawtypes" })
238             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
239             return casted;
240         } else if (BindingReflections.isBindingClass(valueType)) {
241             final TypeDefinition<?> instantiatedType;
242             if (schema instanceof LeafSchemaNode) {
243                 instantiatedType = ((LeafSchemaNode) schema).getType();
244             } else if (schema instanceof LeafListSchemaNode) {
245                 instantiatedType = ((LeafListSchemaNode) schema).getType();
246             } else {
247                 instantiatedType = null;
248             }
249             if (instantiatedType != null) {
250                 return getCodec(valueType, instantiatedType);
251             }
252         }
253         return ValueTypeCodec.NOOP_CODEC;
254     }
255
256     private Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
257         @SuppressWarnings("rawtypes")
258         TypeDefinition rootType = instantiatedType;
259         while (rootType.getBaseType() != null) {
260             rootType = rootType.getBaseType();
261         }
262         if (rootType instanceof IdentityrefTypeDefinition) {
263             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
264         } else if (rootType instanceof InstanceIdentifierTypeDefinition) {
265             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
266         } else if (rootType instanceof UnionTypeDefinition) {
267             Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) rootType,
268                     getInstanceIdentifierCodec(), getIdentityCodec());
269             try {
270                 return loader.call();
271             } catch (Exception e) {
272                 throw new IllegalStateException("Unable to load codec for "+valueType,e);
273             }
274         }
275         return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
276     }
277
278     private class InstanceIdentifierCodec implements Codec<YangInstanceIdentifier, InstanceIdentifier<?>> {
279
280         @Override
281         public YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
282             List<YangInstanceIdentifier.PathArgument> domArgs = new LinkedList<>();
283             getCodecContextNode(input, domArgs);
284             return YangInstanceIdentifier.create(domArgs);
285         }
286
287         @Override
288         public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
289             List<InstanceIdentifier.PathArgument> builder = new LinkedList<>();
290             getCodecContextNode(input, builder);
291             return InstanceIdentifier.create(builder);
292         }
293     }
294
295     private class IdentityCodec implements Codec<QName, Class<?>> {
296
297         @Override
298         public Class<?> deserialize(final QName input) {
299             Preconditions.checkArgument(input != null, "Input must not be null.");
300             return context.getIdentityClass(input);
301         }
302
303         @Override
304         public QName serialize(final Class<?> input) {
305             Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
306             return BindingReflections.findQName(input);
307         }
308     }
309
310     private static class ValueContext {
311
312         Method getter;
313         Codec<Object, Object> codec;
314
315         public ValueContext(final Class<?> identifier, final LeafNodeCodecContext leaf) {
316             final String getterName = GETTER_PREFIX
317                     + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
318             try {
319                 getter = identifier.getMethod(getterName);
320             } catch (NoSuchMethodException | SecurityException e) {
321                 throw new IllegalStateException(e);
322             }
323             codec = leaf.getValueCodec();
324         }
325
326         public Object getAndSerialize(final Object obj) {
327             try {
328                 Object value = getter.invoke(obj);
329                 Preconditions.checkArgument(value != null,
330                         "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
331                         getter.getDeclaringClass(), getter.getName(), obj);
332                 return codec.serialize(value);
333             } catch (IllegalAccessException | InvocationTargetException e) {
334                 throw new IllegalArgumentException(e);
335             }
336         }
337
338         public Object deserialize(final Object obj) {
339             return codec.deserialize(obj);
340         }
341
342     }
343
344     private class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
345
346         private final ImmutableSortedMap<QName, ValueContext> keyValueContexts;
347         private final ListSchemaNode schema;
348         private final Constructor<? extends Identifier<?>> constructor;
349         private final Class<?> identifiable;
350
351         public IdentifiableItemCodec(final ListSchemaNode schema, final Class<? extends Identifier<?>> keyClass,
352                 final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
353             this.schema = schema;
354             this.identifiable = identifiable;
355             this.keyValueContexts = ImmutableSortedMap.copyOf(keyValueContexts);
356             this.constructor = getConstructor(keyClass);
357         }
358
359         @Override
360         public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
361             ArrayList<Object> bindingValues = new ArrayList<>();
362
363             for(QName key: schema.getKeyDefinition()) {
364                 Object yangValue = input.getKeyValues().get(key);
365                 bindingValues.add(keyValueContexts.get(key).deserialize(yangValue));
366             }
367             try {
368                 final Identifier<?> identifier = constructor.newInstance(bindingValues.toArray());
369                 @SuppressWarnings({ "rawtypes", "unchecked" })
370                 final IdentifiableItem identifiableItem = new IdentifiableItem(identifiable, identifier);
371                 return identifiableItem;
372             } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
373                 throw new IllegalStateException(e);
374             }
375         }
376
377         @Override
378         public NodeIdentifierWithPredicates serialize(final IdentifiableItem<?, ?> input) {
379             Object value = input.getKey();
380
381             Map<QName, Object> values = new HashMap<>();
382             for (Entry<QName, ValueContext> valueCtx : keyValueContexts.entrySet()) {
383                 values.put(valueCtx.getKey(), valueCtx.getValue().getAndSerialize(value));
384             }
385             return new NodeIdentifierWithPredicates(schema.getQName(), values);
386         }
387
388     }
389
390     @SuppressWarnings("unchecked")
391     private static Constructor<? extends Identifier<?>> getConstructor(final Class<? extends Identifier<?>> clazz) {
392         for (@SuppressWarnings("rawtypes") Constructor constr : clazz.getConstructors()) {
393             Class<?>[] parameters = constr.getParameterTypes();
394             if (!clazz.equals(parameters[0])) {
395                 // It is not copy constructor;
396                 return constr;
397             }
398         }
399         throw new IllegalArgumentException("Supplied class " + clazz + "does not have required constructor.");
400     }
401
402     @Override
403     public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
404             final ListSchemaNode schema) {
405         Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
406                 Identifiable.class);
407         Map<QName, ValueContext> valueCtx = new HashMap<>();
408         for (LeafNodeCodecContext leaf : getLeafNodes(identifier, schema).values()) {
409             QName name = leaf.getDomPathArgument().getNodeType();
410             valueCtx.put(name, new ValueContext(identifier, leaf));
411         }
412         return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
413     }
414
415 }