Separate out single-key Identifiable handling
[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.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 InstanceIdentifierCodec instanceIdentifierCodec;
71     private final IdentityCodec 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 = requireNonNull(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 = requireNonNull(registry);
82     }
83
84     @Override
85     public BindingRuntimeContext getRuntimeContext() {
86         return context;
87     }
88
89     InstanceIdentifierCodec getInstanceIdentifierCodec() {
90         return instanceIdentifierCodec;
91     }
92
93     IdentityCodec 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             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             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                 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 ({})", 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 ({})", dom);
200             return null;
201         }
202         if (currentNode instanceof CaseNodeCodecContext) {
203             LOG.debug("Instance identifier targeting a case is not representable ({})", 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     ActionCodecContext getActionCodec(final Class<? extends Action<?, ?, ?>> action) {
225         return root.getAction(action);
226     }
227
228     @Override
229     public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
230             final DataNodeContainer childSchema) {
231         final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
232         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
233             if (leaf instanceof TypedDataSchemaNode) {
234                 getterToLeafSchema.put(BindingSchemaMapping.getGetterMethodName((TypedDataSchemaNode) leaf), leaf);
235             }
236         }
237         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
238     }
239
240     private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
241             final Map<String, DataSchemaNode> getterToLeafSchema) {
242         final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
243         for (final Method method : parentClass.getMethods()) {
244             if (method.getParameterCount() == 0) {
245                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
246                 final Class<?> valueType;
247                 if (schema instanceof LeafSchemaNode) {
248                     valueType = method.getReturnType();
249                 } else if (schema instanceof LeafListSchemaNode) {
250                     final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
251
252                     if (genericType instanceof Class<?>) {
253                         valueType = (Class<?>) genericType;
254                     } else if (genericType instanceof ParameterizedType) {
255                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
256                     } else {
257                         throw new IllegalStateException("Unexpected return type " + genericType);
258                     }
259                 } else {
260                     // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
261                     continue;
262                 }
263                 final Codec<Object, Object> codec = getCodec(valueType, schema);
264                 final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method,
265                         context.getSchemaContext());
266                 leaves.put(schema.getQName().getLocalName(), leafNode);
267             }
268         }
269         return ImmutableMap.copyOf(leaves);
270     }
271
272     private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
273         checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema);
274         return getCodec(valueType, ((TypedDataSchemaNode)schema).getType());
275     }
276
277     Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
278         if (Class.class.equals(valueType)) {
279             @SuppressWarnings({ "unchecked", "rawtypes" })
280             final Codec<Object, Object> casted = (Codec) identityCodec;
281             return casted;
282         } else if (InstanceIdentifier.class.equals(valueType)) {
283             @SuppressWarnings({ "unchecked", "rawtypes" })
284             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
285             return casted;
286         } else if (Boolean.class.equals(valueType)) {
287             if (instantiatedType instanceof EmptyTypeDefinition) {
288                 return ValueTypeCodec.EMPTY_CODEC;
289             }
290         } else if (BindingReflections.isBindingClass(valueType)) {
291             return getCodecForBindingClass(valueType, instantiatedType);
292         }
293         return ValueTypeCodec.NOOP_CODEC;
294     }
295
296     @SuppressWarnings("checkstyle:illegalCatch")
297     private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
298         if (typeDef instanceof IdentityrefTypeDefinition) {
299             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, identityCodec);
300         } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
301             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, instanceIdentifierCodec);
302         } else if (typeDef instanceof UnionTypeDefinition) {
303             final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef,
304                 this);
305             try {
306                 return loader.call();
307             } catch (final Exception e) {
308                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
309             }
310         } else if (typeDef instanceof LeafrefTypeDefinition) {
311             final Entry<GeneratedType, WithStatus> typeWithSchema = context.getTypeWithSchema(valueType);
312             final WithStatus schema = typeWithSchema.getValue();
313             checkState(schema instanceof TypeDefinition);
314             return getCodec(valueType, (TypeDefinition<?>) schema);
315         }
316         return ValueTypeCodec.getCodecFor(valueType, typeDef);
317     }
318
319     @Override
320     public IdentifiableItemCodec getPathArgumentCodec(final Class<?> listClz, final ListSchemaNode schema) {
321         final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
322                 Identifiable.class);
323         final Map<QName, ValueContext> valueCtx = new HashMap<>();
324         for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
325             final QName name = leaf.getDomPathArgument().getNodeType();
326             valueCtx.put(name, new ValueContext(identifier, leaf));
327         }
328         return IdentifiableItemCodec.of(schema, identifier, listClz, valueCtx);
329     }
330
331     @SuppressWarnings("unchecked")
332     @Override
333     public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
334         // TODO Do we need defensive check here?
335         return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
336     }
337
338     @Override
339     public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
340         return getCodecContextNode(path, null);
341     }
342
343     @Override
344     public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
345         throw new UnsupportedOperationException("Not implemented yet.");
346     }
347 }