Merge "Bug 2864: Fixed (de)serialization of leafrefs"
[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.Method;
13 import java.lang.reflect.ParameterizedType;
14 import java.lang.reflect.Type;
15 import java.util.AbstractMap.SimpleEntry;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.LinkedList;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.concurrent.Callable;
23 import javax.annotation.Nonnull;
24 import javax.annotation.Nullable;
25 import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTree;
26 import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeNode;
27 import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
28 import org.opendaylight.yangtools.concepts.Codec;
29 import org.opendaylight.yangtools.concepts.Immutable;
30 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
31 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
32 import org.opendaylight.yangtools.util.ClassLoaderUtils;
33 import org.opendaylight.yangtools.yang.binding.BindingMapping;
34 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
35 import org.opendaylight.yangtools.yang.binding.DataContainer;
36 import org.opendaylight.yangtools.yang.binding.DataObject;
37 import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
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.Notification;
43 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
54 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable {
65     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
66     static final String GETTER_PREFIX = "get";
67
68     private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
69     private final Codec<QName, Class<?>> identityCodec;
70     private final BindingNormalizedNodeCodecRegistry registry;
71     private final BindingRuntimeContext context;
72     private final SchemaRootCodecContext<?> root;
73
74     BindingCodecContext(final BindingRuntimeContext context, BindingNormalizedNodeCodecRegistry registry) {
75         this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
76         this.root = SchemaRootCodecContext.create(this);
77         this.identityCodec = new IdentityCodec(context);
78         this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
79         this.registry = Preconditions.checkNotNull(registry);
80     }
81
82     @Override
83     public BindingRuntimeContext getRuntimeContext() {
84         return context;
85     }
86
87     Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
88         return instanceIdentifierCodec;
89     }
90
91     public Codec<QName, Class<?>> getIdentityCodec() {
92         return identityCodec;
93     }
94
95     @SuppressWarnings({"rawtypes", "unchecked"})
96     @Override
97     public DataObjectSerializer getEventStreamSerializer(Class<?> type) {
98         return registry.getSerializer((Class) type);
99     }
100
101     public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
102             final NormalizedNodeStreamWriter domWriter) {
103         final LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
104         final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
105         return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
106     }
107
108     public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
109             final NormalizedNodeStreamWriter domWriter) {
110         return getCodecContextNode(path, null).createWriter(domWriter);
111     }
112
113     BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
114             final NormalizedNodeStreamWriter domWriter) {
115         return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
116     }
117
118     BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
119             final NormalizedNodeStreamWriter domWriter) {
120         return root.getNotification(notification).createWriter(domWriter);
121     }
122
123     public DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
124             final List<YangInstanceIdentifier.PathArgument> builder) {
125         DataContainerCodecContext<?,?> currentNode = root;
126         for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
127             currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
128             Preconditions.checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.",binding);
129         }
130         return currentNode;
131     }
132
133     /**
134      * Multi-purpose utility function. Traverse the codec tree, looking for
135      * the appropriate codec for the specified {@link YangInstanceIdentifier}.
136      * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
137      * into the supplied collection.
138      *
139      * @param dom {@link YangInstanceIdentifier} which is to be translated
140      * @param bindingArguments Collection for traversed path arguments
141      * @return Codec for target node, or @null if the node does not have a
142      *         binding representation (choice, case, leaf).
143      *
144      */
145     @Nullable NodeCodecContext<?> getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
146             final @Nonnull Collection<InstanceIdentifier.PathArgument> bindingArguments) {
147         NodeCodecContext<?> currentNode = root;
148         ListNodeCodecContext<?> currentList = null;
149
150         for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
151             Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?,?>, "Unexpected child of non-container node %s", currentNode);
152             final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?,?>) currentNode;
153             final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
154
155             /*
156              * List representation in YANG Instance Identifier consists of two
157              * arguments: first is list as a whole, second is list as an item so
158              * if it is /list it means list as whole, if it is /list/list - it
159              * is wildcarded and if it is /list/list[key] it is concrete item,
160              * all this variations are expressed in Binding Aware Instance
161              * Identifier as Item or IdentifiableItem
162              */
163             if (currentList != null) {
164                 Preconditions.checkArgument(currentList == nextNode, "List should be referenced two times in YANG Instance Identifier %s", dom);
165
166                 // We entered list, so now we have all information to emit
167                 // list path using second list argument.
168                 bindingArguments.add(currentList.getBindingPathArgument(domArg));
169                 currentList = null;
170                 currentNode = nextNode;
171             } else if (nextNode instanceof ListNodeCodecContext) {
172                 // We enter list, we do not update current Node yet,
173                 // since we need to verify
174                 currentList = (ListNodeCodecContext<?>) nextNode;
175             } else if (nextNode instanceof ChoiceNodeCodecContext) {
176                 // We do not add path argument for choice, since
177                 // it is not supported by binding instance identifier.
178                 currentNode = nextNode;
179             } else if (nextNode instanceof DataContainerCodecContext<?,?>) {
180                 bindingArguments.add(((DataContainerCodecContext<?,?>) nextNode).getBindingPathArgument(domArg));
181                 currentNode = nextNode;
182             } else if (nextNode instanceof LeafNodeCodecContext) {
183                 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
184                 return null;
185             }
186         }
187
188         // Algorithm ended in list as whole representation
189         // we sill need to emit identifier for list
190         if (currentNode instanceof ChoiceNodeCodecContext) {
191             LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
192             return null;
193         }
194         if (currentNode instanceof CaseNodeCodecContext) {
195             LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
196             return null;
197         }
198
199         if (currentList != null) {
200             bindingArguments.add(currentList.getBindingPathArgument(null));
201             return currentList;
202         }
203         return currentNode;
204     }
205
206     NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
207         return root.getNotification(notification);
208     }
209
210     ContainerNodeCodecContext<?> getRpcDataContext(final SchemaPath path) {
211         return root.getRpc(path);
212     }
213
214     @Override
215     public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
216             final DataNodeContainer childSchema) {
217         final HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
218         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
219             final TypeDefinition<?> typeDef;
220             if (leaf instanceof LeafSchemaNode) {
221                 typeDef = ((LeafSchemaNode) leaf).getType();
222             } else if (leaf instanceof LeafListSchemaNode) {
223                 typeDef = ((LeafListSchemaNode) leaf).getType();
224             } else {
225                 continue;
226             }
227
228             final String getterName = getGetterName(leaf.getQName(), typeDef);
229             getterToLeafSchema.put(getterName, leaf);
230         }
231         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
232     }
233
234     private String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
235         final String suffix = BindingMapping.getClassName(qName);
236
237         while (typeDef.getBaseType() != null) {
238             typeDef = typeDef.getBaseType();
239         }
240         if (typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) {
241             return "is" + suffix;
242         }
243         return GETTER_PREFIX + suffix;
244     }
245
246     private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
247             final Map<String, DataSchemaNode> getterToLeafSchema) {
248         final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
249         for (final Method method : parentClass.getMethods()) {
250             if (method.getParameterTypes().length == 0) {
251                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
252                 final Class<?> valueType;
253                 if (schema instanceof LeafSchemaNode) {
254                     valueType = method.getReturnType();
255                 } else if (schema instanceof LeafListSchemaNode) {
256                     final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
257
258                     if (genericType instanceof Class<?>) {
259                         valueType = (Class<?>) genericType;
260                     } else if (genericType instanceof ParameterizedType) {
261                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
262                     } else {
263                         throw new IllegalStateException("Unexpected return type " + genericType);
264                     }
265                 } else {
266                     continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
267                 }
268                 final Codec<Object, Object> codec = getCodec(valueType, schema);
269                 final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method);
270                 leaves.put(schema.getQName().getLocalName(), leafNode);
271             }
272         }
273         return ImmutableMap.copyOf(leaves);
274     }
275
276     private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
277         final TypeDefinition<?> instantiatedType;
278         if (schema instanceof LeafSchemaNode) {
279             instantiatedType = ((LeafSchemaNode) schema).getType();
280         } else if (schema instanceof LeafListSchemaNode) {
281             instantiatedType = ((LeafListSchemaNode) schema).getType();
282         } else {
283             throw new IllegalArgumentException("Unsupported leaf node type " + schema.getClass());
284         }
285         if (Class.class.equals(valueType)) {
286             @SuppressWarnings({ "unchecked", "rawtypes" })
287             final Codec<Object, Object> casted = (Codec) identityCodec;
288             return casted;
289         } else if (InstanceIdentifier.class.equals(valueType)) {
290             @SuppressWarnings({ "unchecked", "rawtypes" })
291             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
292             return casted;
293         } else if (Boolean.class.equals(valueType)) {
294             if(instantiatedType instanceof EmptyTypeDefinition) {
295                 return ValueTypeCodec.EMPTY_CODEC;
296             }
297         } else if (BindingReflections.isBindingClass(valueType)) {
298                             return getCodec(valueType, instantiatedType);
299         }
300         return ValueTypeCodec.NOOP_CODEC;
301     }
302
303     private Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
304         @SuppressWarnings("rawtypes")
305         TypeDefinition rootType = instantiatedType;
306         while (rootType.getBaseType() != null) {
307             rootType = rootType.getBaseType();
308         }
309         if (rootType instanceof IdentityrefTypeDefinition) {
310             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
311         } else if (rootType instanceof InstanceIdentifierTypeDefinition) {
312             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
313         } else if (rootType instanceof UnionTypeDefinition) {
314             final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) rootType);
315             try {
316                 return loader.call();
317             } catch (final Exception e) {
318                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
319             }
320         } else if(rootType instanceof LeafrefTypeDefinition) {
321             final Entry<GeneratedType, Object> typeWithSchema = context.getTypeWithSchema(valueType);
322             final Object schema = typeWithSchema.getValue();
323             Preconditions.checkState(schema instanceof TypeDefinition<?>);
324             return getCodec(valueType, (TypeDefinition<?>) schema);
325         }
326         return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
327     }
328
329     @Override
330     public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
331             final ListSchemaNode schema) {
332         final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
333                 Identifiable.class);
334         final Map<QName, ValueContext> valueCtx = new HashMap<>();
335         for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
336             final QName name = leaf.getDomPathArgument().getNodeType();
337             valueCtx.put(name, new ValueContext(identifier, leaf));
338         }
339         return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
340     }
341
342     @SuppressWarnings("unchecked")
343     @Override
344     public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(InstanceIdentifier<T> path) {
345         // TODO Do we need defensive check here?
346         return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
347     }
348
349     @Override
350     public BindingCodecTreeNode<?> getSubtreeCodec(YangInstanceIdentifier path) {
351         return getCodecContextNode(path, null);
352     }
353
354     @Override
355     public BindingCodecTreeNode<?> getSubtreeCodec(SchemaPath path) {
356         throw new UnsupportedOperationException("Not implemented yet.");
357     }
358 }