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