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