Change 'type empty' mapping
[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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.collect.ImmutableMap;
15 import java.lang.reflect.Method;
16 import java.lang.reflect.ParameterizedType;
17 import java.lang.reflect.Type;
18 import java.util.AbstractMap.SimpleEntry;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.LinkedList;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.concurrent.Callable;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeNode;
30 import org.opendaylight.mdsal.binding.dom.codec.impl.NodeCodecContext.CodecContextFactory;
31 import org.opendaylight.mdsal.binding.dom.codec.util.BindingSchemaMapping;
32 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
33 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
34 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
35 import org.opendaylight.yangtools.concepts.Codec;
36 import org.opendaylight.yangtools.concepts.Immutable;
37 import org.opendaylight.yangtools.util.ClassLoaderUtils;
38 import org.opendaylight.yangtools.yang.binding.Action;
39 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
40 import org.opendaylight.yangtools.yang.binding.DataContainer;
41 import org.opendaylight.yangtools.yang.binding.DataObject;
42 import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
43 import org.opendaylight.yangtools.yang.binding.Identifiable;
44 import org.opendaylight.yangtools.yang.binding.Identifier;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.opendaylight.yangtools.yang.binding.Notification;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
50 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
53 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
57 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
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 InstanceIdentifierCodec instanceIdentifierCodec;
70     private final IdentityCodec 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 = requireNonNull(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 = requireNonNull(registry);
81     }
82
83     @Override
84     public BindingRuntimeContext getRuntimeContext() {
85         return context;
86     }
87
88     InstanceIdentifierCodec getInstanceIdentifierCodec() {
89         return instanceIdentifierCodec;
90     }
91
92     IdentityCodec 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             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             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                 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 ({})", 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 ({})", dom);
199             return null;
200         }
201         if (currentNode instanceof CaseNodeCodecContext) {
202             LOG.debug("Instance identifier targeting a case is not representable ({})", 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     ActionCodecContext getActionCodec(final Class<? extends Action<?, ?, ?>> action) {
224         return root.getAction(action);
225     }
226
227     @Override
228     public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
229             final DataNodeContainer childSchema) {
230         final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
231         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
232             if (leaf instanceof TypedDataSchemaNode) {
233                 getterToLeafSchema.put(BindingSchemaMapping.getGetterMethodName((TypedDataSchemaNode) leaf), leaf);
234             }
235         }
236         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
237     }
238
239     private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
240             final Map<String, DataSchemaNode> getterToLeafSchema) {
241         final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
242         for (final Method method : parentClass.getMethods()) {
243             if (method.getParameterCount() == 0) {
244                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
245                 final Class<?> valueType;
246                 if (schema instanceof LeafSchemaNode) {
247                     valueType = method.getReturnType();
248                 } else if (schema instanceof LeafListSchemaNode) {
249                     final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
250
251                     if (genericType instanceof Class<?>) {
252                         valueType = (Class<?>) genericType;
253                     } else if (genericType instanceof ParameterizedType) {
254                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
255                     } else {
256                         throw new IllegalStateException("Unexpected return type " + genericType);
257                     }
258                 } else {
259                     // We do not have schema for leaf, so we will ignore it (e.g. getClass).
260                     continue;
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         checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema);
273         return getCodec(valueType, ((TypedDataSchemaNode)schema).getType());
274     }
275
276     Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
277         if (Class.class.equals(valueType)) {
278             @SuppressWarnings({ "unchecked", "rawtypes" })
279             final Codec<Object, Object> casted = (Codec) identityCodec;
280             return casted;
281         } else if (InstanceIdentifier.class.equals(valueType)) {
282             @SuppressWarnings({ "unchecked", "rawtypes" })
283             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
284             return casted;
285         } else if (BindingReflections.isBindingClass(valueType)) {
286             return getCodecForBindingClass(valueType, instantiatedType);
287         }
288         return ValueTypeCodec.NOOP_CODEC;
289     }
290
291     @SuppressWarnings("checkstyle:illegalCatch")
292     private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
293         if (typeDef instanceof IdentityrefTypeDefinition) {
294             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, identityCodec);
295         } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
296             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, instanceIdentifierCodec);
297         } else if (typeDef instanceof UnionTypeDefinition) {
298             final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef,
299                 this);
300             try {
301                 return loader.call();
302             } catch (final Exception e) {
303                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
304             }
305         } else if (typeDef instanceof LeafrefTypeDefinition) {
306             final Entry<GeneratedType, WithStatus> typeWithSchema = context.getTypeWithSchema(valueType);
307             final WithStatus schema = typeWithSchema.getValue();
308             checkState(schema instanceof TypeDefinition);
309             return getCodec(valueType, (TypeDefinition<?>) schema);
310         }
311         return ValueTypeCodec.getCodecFor(valueType, typeDef);
312     }
313
314     @Override
315     public IdentifiableItemCodec getPathArgumentCodec(final Class<?> listClz, final ListSchemaNode schema) {
316         final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
317                 Identifiable.class);
318         final Map<QName, ValueContext> valueCtx = new HashMap<>();
319         for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
320             final QName name = leaf.getDomPathArgument().getNodeType();
321             valueCtx.put(name, new ValueContext(identifier, leaf));
322         }
323         return IdentifiableItemCodec.of(schema, identifier, listClz, valueCtx);
324     }
325
326     @SuppressWarnings("unchecked")
327     @Override
328     public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
329         // TODO Do we need defensive check here?
330         return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
331     }
332
333     @Override
334     public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
335         return getCodecContextNode(path, null);
336     }
337
338     @Override
339     public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
340         throw new UnsupportedOperationException("Not implemented yet.");
341     }
342 }