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