bcf269a80fd1ef2f36c593e34023853e02c921ca
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / 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.mdsal.binding.dom.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.mdsal.binding.dom.codec.impl.NodeCodecContext.CodecContextFactory;
28 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
29 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
30 import org.opendaylight.yangtools.concepts.Codec;
31 import org.opendaylight.yangtools.concepts.Immutable;
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.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
55 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable {
67     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
68
69     private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
70     private final Codec<QName, Class<?>> identityCodec;
71     private final BindingNormalizedNodeCodecRegistry registry;
72     private final BindingRuntimeContext context;
73     private final SchemaRootCodecContext<?> root;
74
75     BindingCodecContext(final BindingRuntimeContext context, final BindingNormalizedNodeCodecRegistry registry) {
76         this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
77         this.root = SchemaRootCodecContext.create(this);
78         this.identityCodec = new IdentityCodec(context);
79         this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
80         this.registry = Preconditions.checkNotNull(registry);
81     }
82
83     @Override
84     public BindingRuntimeContext getRuntimeContext() {
85         return context;
86     }
87
88     Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
89         return instanceIdentifierCodec;
90     }
91
92     public Codec<QName, Class<?>> getIdentityCodec() {
93         return identityCodec;
94     }
95
96     @SuppressWarnings({"rawtypes", "unchecked"})
97     @Override
98     public DataObjectSerializer getEventStreamSerializer(final Class<?> type) {
99         return registry.getSerializer((Class) type);
100     }
101
102     public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
103             final NormalizedNodeStreamWriter domWriter) {
104         final List<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
105         final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
106         return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
107     }
108
109     public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
110             final NormalizedNodeStreamWriter domWriter) {
111         return getCodecContextNode(path, null).createWriter(domWriter);
112     }
113
114     BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
115             final NormalizedNodeStreamWriter domWriter) {
116         return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
117     }
118
119     BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
120             final NormalizedNodeStreamWriter domWriter) {
121         return root.getNotification(notification).createWriter(domWriter);
122     }
123
124     public DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
125             final List<YangInstanceIdentifier.PathArgument> builder) {
126         DataContainerCodecContext<?,?> currentNode = root;
127         for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
128             currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
129             Preconditions.checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.", binding);
130         }
131         return currentNode;
132     }
133
134     /**
135      * Multi-purpose utility function. Traverse the codec tree, looking for
136      * the appropriate codec for the specified {@link YangInstanceIdentifier}.
137      * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
138      * into the supplied collection.
139      *
140      * @param dom {@link YangInstanceIdentifier} which is to be translated
141      * @param bindingArguments Collection for traversed path arguments
142      * @return Codec for target node, or @null if the node does not have a
143      *         binding representation (choice, case, leaf).
144      *
145      */
146     @Nullable NodeCodecContext<?> getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
147             final @Nullable Collection<InstanceIdentifier.PathArgument> bindingArguments) {
148         NodeCodecContext<?> currentNode = root;
149         ListNodeCodecContext<?> currentList = null;
150
151         for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
152             Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?,?>,
153                 "Unexpected child of non-container node %s", currentNode);
154             final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?,?>) currentNode;
155             final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
156
157             /*
158              * List representation in YANG Instance Identifier consists of two
159              * arguments: first is list as a whole, second is list as an item so
160              * if it is /list it means list as whole, if it is /list/list - it
161              * is wildcarded and if it is /list/list[key] it is concrete item,
162              * all this variations are expressed in Binding Aware Instance
163              * Identifier as Item or IdentifiableItem
164              */
165             if (currentList != null) {
166                 Preconditions.checkArgument(currentList == nextNode,
167                         "List should be referenced two times in YANG Instance Identifier %s", dom);
168
169                 // We entered list, so now we have all information to emit
170                 // list path using second list argument.
171                 if (bindingArguments != null) {
172                     bindingArguments.add(currentList.getBindingPathArgument(domArg));
173                 }
174                 currentList = null;
175                 currentNode = nextNode;
176             } else if (nextNode instanceof ListNodeCodecContext) {
177                 // We enter list, we do not update current Node yet,
178                 // since we need to verify
179                 currentList = (ListNodeCodecContext<?>) nextNode;
180             } else if (nextNode instanceof ChoiceNodeCodecContext) {
181                 // We do not add path argument for choice, since
182                 // it is not supported by binding instance identifier.
183                 currentNode = nextNode;
184             } else if (nextNode instanceof DataContainerCodecContext<?,?>) {
185                 if (bindingArguments != null) {
186                     bindingArguments.add(((DataContainerCodecContext<?,?>) nextNode).getBindingPathArgument(domArg));
187                 }
188                 currentNode = nextNode;
189             } else if (nextNode instanceof LeafNodeCodecContext) {
190                 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
191                 return null;
192             }
193         }
194
195         // Algorithm ended in list as whole representation
196         // we sill need to emit identifier for list
197         if (currentNode instanceof ChoiceNodeCodecContext) {
198             LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
199             return null;
200         }
201         if (currentNode instanceof CaseNodeCodecContext) {
202             LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
203             return null;
204         }
205
206         if (currentList != null) {
207             if (bindingArguments != null) {
208                 bindingArguments.add(currentList.getBindingPathArgument(null));
209             }
210             return currentList;
211         }
212         return currentNode;
213     }
214
215     NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
216         return root.getNotification(notification);
217     }
218
219     RpcInputCodec<?> getRpcInputCodec(final SchemaPath path) {
220         return root.getRpc(path);
221     }
222
223     @Override
224     public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
225             final DataNodeContainer childSchema) {
226         final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
227         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
228             if (leaf instanceof TypedDataSchemaNode) {
229                 getterToLeafSchema.put(getGetterName(leaf, ((TypedDataSchemaNode) leaf).getType()), leaf);
230             }
231         }
232         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
233     }
234
235     private static String getGetterName(final SchemaNode node, final TypeDefinition<?> typeDef) {
236         final String suffix = BindingMapping.getGetterSuffix(node.getQName());
237         // Bug 8903: If it is a derived type of boolean or empty, not an inner type, then the return type
238         // of method would be the generated type of typedef not build-in types, so here it should be 'get'.
239         if ((typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition)
240                 && (typeDef.getPath().equals(node.getPath()) || typeDef.getBaseType() == null)) {
241             return "is" + suffix;
242         }
243         return "get" + 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                     // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
267                     continue;
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         Preconditions.checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema);
280
281         return getCodec(valueType, ((TypedDataSchemaNode)schema).getType());
282     }
283
284     Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
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 getCodecForBindingClass(valueType, instantiatedType);
299         }
300         return ValueTypeCodec.NOOP_CODEC;
301     }
302
303     @SuppressWarnings("checkstyle:illegalCatch")
304     private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
305         if (typeDef instanceof IdentityrefTypeDefinition) {
306             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, identityCodec);
307         } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
308             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, instanceIdentifierCodec);
309         } else if (typeDef instanceof UnionTypeDefinition) {
310             final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef,
311                 this);
312             try {
313                 return loader.call();
314             } catch (final Exception e) {
315                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
316             }
317         } else if (typeDef instanceof LeafrefTypeDefinition) {
318             final Entry<GeneratedType, Object> typeWithSchema = context.getTypeWithSchema(valueType);
319             final Object schema = typeWithSchema.getValue();
320             Preconditions.checkState(schema instanceof TypeDefinition<?>);
321             return getCodec(valueType, (TypeDefinition<?>) schema);
322         }
323         return ValueTypeCodec.getCodecFor(valueType, typeDef);
324     }
325
326     @Override
327     public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
328             final ListSchemaNode schema) {
329         final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
330                 Identifiable.class);
331         final Map<QName, ValueContext> valueCtx = new HashMap<>();
332         for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
333             final QName name = leaf.getDomPathArgument().getNodeType();
334             valueCtx.put(name, new ValueContext(identifier, leaf));
335         }
336         return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
337     }
338
339     @SuppressWarnings("unchecked")
340     @Override
341     public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
342         // TODO Do we need defensive check here?
343         return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
344     }
345
346     @Override
347     public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
348         return getCodecContextNode(path, null);
349     }
350
351     @Override
352     public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
353         throw new UnsupportedOperationException("Not implemented yet.");
354     }
355 }