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