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