BUG-8004: handle implicit RPC input
[mdsal.git] / binding / mdsal-binding-dom-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.mdsal.binding.dom.codec.api.BindingCodecTree;
26 import org.opendaylight.mdsal.binding.dom.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.TypedSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable {
66     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
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, final 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(final 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 List<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 @Nullable 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                 if (bindingArguments != null) {
169                     bindingArguments.add(currentList.getBindingPathArgument(domArg));
170                 }
171                 currentList = null;
172                 currentNode = nextNode;
173             } else if (nextNode instanceof ListNodeCodecContext) {
174                 // We enter list, we do not update current Node yet,
175                 // since we need to verify
176                 currentList = (ListNodeCodecContext<?>) nextNode;
177             } else if (nextNode instanceof ChoiceNodeCodecContext) {
178                 // We do not add path argument for choice, since
179                 // it is not supported by binding instance identifier.
180                 currentNode = nextNode;
181             } else if (nextNode instanceof DataContainerCodecContext<?,?>) {
182                 if (bindingArguments != null) {
183                     bindingArguments.add(((DataContainerCodecContext<?,?>) nextNode).getBindingPathArgument(domArg));
184                 }
185                 currentNode = nextNode;
186             } else if (nextNode instanceof LeafNodeCodecContext) {
187                 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
188                 return null;
189             }
190         }
191
192         // Algorithm ended in list as whole representation
193         // we sill need to emit identifier for list
194         if (currentNode instanceof ChoiceNodeCodecContext) {
195             LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
196             return null;
197         }
198         if (currentNode instanceof CaseNodeCodecContext) {
199             LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
200             return null;
201         }
202
203         if (currentList != null) {
204             if (bindingArguments != null) {
205                 bindingArguments.add(currentList.getBindingPathArgument(null));
206             }
207             return currentList;
208         }
209         return currentNode;
210     }
211
212     NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
213         return root.getNotification(notification);
214     }
215
216     RpcInputCodec<?> getRpcInputCodec(final SchemaPath path) {
217         return root.getRpc(path);
218     }
219
220     @Override
221     public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
222             final DataNodeContainer childSchema) {
223         final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
224         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
225             if (leaf instanceof TypedSchemaNode) {
226                 getterToLeafSchema.put(getGetterName(leaf.getQName(), ((TypedSchemaNode) leaf).getType()), leaf);
227             }
228         }
229         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
230     }
231
232     private static String getGetterName(final QName qName, final TypeDefinition<?> typeDef) {
233         final String suffix = BindingMapping.getGetterSuffix(qName);
234         if (typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) {
235             return "is" + suffix;
236         }
237         return "get" + suffix;
238     }
239
240     private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
241             final Map<String, DataSchemaNode> getterToLeafSchema) {
242         final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
243         for (final Method method : parentClass.getMethods()) {
244             if (method.getParameterTypes().length == 0) {
245                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
246                 final Class<?> valueType;
247                 if (schema instanceof LeafSchemaNode) {
248                     valueType = method.getReturnType();
249                 } else if (schema instanceof LeafListSchemaNode) {
250                     final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
251
252                     if (genericType instanceof Class<?>) {
253                         valueType = (Class<?>) genericType;
254                     } else if (genericType instanceof ParameterizedType) {
255                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
256                     } else {
257                         throw new IllegalStateException("Unexpected return type " + genericType);
258                     }
259                 } else {
260                     continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
261                 }
262                 final Codec<Object, Object> codec = getCodec(valueType, schema);
263                 final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method,
264                         context.getSchemaContext());
265                 leaves.put(schema.getQName().getLocalName(), leafNode);
266             }
267         }
268         return ImmutableMap.copyOf(leaves);
269     }
270
271     private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
272         Preconditions.checkArgument(schema instanceof TypedSchemaNode, "Unsupported leaf node type %s", schema);
273
274         return getCodec(valueType, ((TypedSchemaNode)schema).getType());
275     }
276
277     Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
278         if (Class.class.equals(valueType)) {
279             @SuppressWarnings({ "unchecked", "rawtypes" })
280             final Codec<Object, Object> casted = (Codec) identityCodec;
281             return casted;
282         } else if (InstanceIdentifier.class.equals(valueType)) {
283             @SuppressWarnings({ "unchecked", "rawtypes" })
284             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
285             return casted;
286         } else if (Boolean.class.equals(valueType)) {
287             if (instantiatedType instanceof EmptyTypeDefinition) {
288                 return ValueTypeCodec.EMPTY_CODEC;
289             }
290         } else if (BindingReflections.isBindingClass(valueType)) {
291             return getCodecForBindingClass(valueType, instantiatedType);
292         }
293         return ValueTypeCodec.NOOP_CODEC;
294     }
295
296     private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
297         if (typeDef instanceof IdentityrefTypeDefinition) {
298             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
299         } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
300             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
301         } else if (typeDef instanceof UnionTypeDefinition) {
302             final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef, this);
303             try {
304                 return loader.call();
305             } catch (final Exception e) {
306                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
307             }
308         } else if (typeDef instanceof LeafrefTypeDefinition) {
309             final Entry<GeneratedType, Object> typeWithSchema = context.getTypeWithSchema(valueType);
310             final Object schema = typeWithSchema.getValue();
311             Preconditions.checkState(schema instanceof TypeDefinition<?>);
312             return getCodec(valueType, (TypeDefinition<?>) schema);
313         }
314         return ValueTypeCodec.getCodecFor(valueType, typeDef);
315     }
316
317     @Override
318     public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
319             final ListSchemaNode schema) {
320         final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
321                 Identifiable.class);
322         final Map<QName, ValueContext> valueCtx = new HashMap<>();
323         for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
324             final QName name = leaf.getDomPathArgument().getNodeType();
325             valueCtx.put(name, new ValueContext(identifier, leaf));
326         }
327         return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
328     }
329
330     @SuppressWarnings("unchecked")
331     @Override
332     public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
333         // TODO Do we need defensive check here?
334         return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
335     }
336
337     @Override
338     public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
339         return getCodecContextNode(path, null);
340     }
341
342     @Override
343     public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
344         throw new UnsupportedOperationException("Not implemented yet.");
345     }
346 }