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