Fix checkstyle in mdsal-binding-dom-codec
[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.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.TypedSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable {
66     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
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<?,?>,
152                 "Unexpected child of non-container node %s", currentNode);
153             final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?,?>) currentNode;
154             final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
155
156             /*
157              * List representation in YANG Instance Identifier consists of two
158              * arguments: first is list as a whole, second is list as an item so
159              * if it is /list it means list as whole, if it is /list/list - it
160              * is wildcarded and if it is /list/list[key] it is concrete item,
161              * all this variations are expressed in Binding Aware Instance
162              * Identifier as Item or IdentifiableItem
163              */
164             if (currentList != null) {
165                 Preconditions.checkArgument(currentList == nextNode,
166                         "List should be referenced two times in YANG Instance Identifier %s", dom);
167
168                 // We entered list, so now we have all information to emit
169                 // list path using second list argument.
170                 if (bindingArguments != null) {
171                     bindingArguments.add(currentList.getBindingPathArgument(domArg));
172                 }
173                 currentList = null;
174                 currentNode = nextNode;
175             } else if (nextNode instanceof ListNodeCodecContext) {
176                 // We enter list, we do not update current Node yet,
177                 // since we need to verify
178                 currentList = (ListNodeCodecContext<?>) nextNode;
179             } else if (nextNode instanceof ChoiceNodeCodecContext) {
180                 // We do not add path argument for choice, since
181                 // it is not supported by binding instance identifier.
182                 currentNode = nextNode;
183             } else if (nextNode instanceof DataContainerCodecContext<?,?>) {
184                 if (bindingArguments != null) {
185                     bindingArguments.add(((DataContainerCodecContext<?,?>) nextNode).getBindingPathArgument(domArg));
186                 }
187                 currentNode = nextNode;
188             } else if (nextNode instanceof LeafNodeCodecContext) {
189                 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
190                 return null;
191             }
192         }
193
194         // Algorithm ended in list as whole representation
195         // we sill need to emit identifier for list
196         if (currentNode instanceof ChoiceNodeCodecContext) {
197             LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
198             return null;
199         }
200         if (currentNode instanceof CaseNodeCodecContext) {
201             LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
202             return null;
203         }
204
205         if (currentList != null) {
206             if (bindingArguments != null) {
207                 bindingArguments.add(currentList.getBindingPathArgument(null));
208             }
209             return currentList;
210         }
211         return currentNode;
212     }
213
214     NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
215         return root.getNotification(notification);
216     }
217
218     RpcInputCodec<?> getRpcInputCodec(final SchemaPath path) {
219         return root.getRpc(path);
220     }
221
222     @Override
223     public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
224             final DataNodeContainer childSchema) {
225         final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
226         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
227             if (leaf instanceof TypedSchemaNode) {
228                 getterToLeafSchema.put(getGetterName(leaf.getQName(), ((TypedSchemaNode) leaf).getType()), leaf);
229             }
230         }
231         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
232     }
233
234     private static String getGetterName(final QName qname, final TypeDefinition<?> typeDef) {
235         final String suffix = BindingMapping.getGetterSuffix(qname);
236         if (typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) {
237             return "is" + suffix;
238         }
239         return "get" + suffix;
240     }
241
242     private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
243             final Map<String, DataSchemaNode> getterToLeafSchema) {
244         final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
245         for (final Method method : parentClass.getMethods()) {
246             if (method.getParameterTypes().length == 0) {
247                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
248                 final Class<?> valueType;
249                 if (schema instanceof LeafSchemaNode) {
250                     valueType = method.getReturnType();
251                 } else if (schema instanceof LeafListSchemaNode) {
252                     final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
253
254                     if (genericType instanceof Class<?>) {
255                         valueType = (Class<?>) genericType;
256                     } else if (genericType instanceof ParameterizedType) {
257                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
258                     } else {
259                         throw new IllegalStateException("Unexpected return type " + genericType);
260                     }
261                 } else {
262                     // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
263                     continue;
264                 }
265                 final Codec<Object, Object> codec = getCodec(valueType, schema);
266                 final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method,
267                         context.getSchemaContext());
268                 leaves.put(schema.getQName().getLocalName(), leafNode);
269             }
270         }
271         return ImmutableMap.copyOf(leaves);
272     }
273
274     private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
275         Preconditions.checkArgument(schema instanceof TypedSchemaNode, "Unsupported leaf node type %s", schema);
276
277         return getCodec(valueType, ((TypedSchemaNode)schema).getType());
278     }
279
280     Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
281         if (Class.class.equals(valueType)) {
282             @SuppressWarnings({ "unchecked", "rawtypes" })
283             final Codec<Object, Object> casted = (Codec) identityCodec;
284             return casted;
285         } else if (InstanceIdentifier.class.equals(valueType)) {
286             @SuppressWarnings({ "unchecked", "rawtypes" })
287             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
288             return casted;
289         } else if (Boolean.class.equals(valueType)) {
290             if (instantiatedType instanceof EmptyTypeDefinition) {
291                 return ValueTypeCodec.EMPTY_CODEC;
292             }
293         } else if (BindingReflections.isBindingClass(valueType)) {
294             return getCodecForBindingClass(valueType, instantiatedType);
295         }
296         return ValueTypeCodec.NOOP_CODEC;
297     }
298
299     @SuppressWarnings("checkstyle:illegalCatch")
300     private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
301         if (typeDef instanceof IdentityrefTypeDefinition) {
302             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
303         } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
304             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
305         } else if (typeDef instanceof UnionTypeDefinition) {
306             final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef,
307                 this);
308             try {
309                 return loader.call();
310             } catch (final Exception e) {
311                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
312             }
313         } else if (typeDef instanceof LeafrefTypeDefinition) {
314             final Entry<GeneratedType, Object> typeWithSchema = context.getTypeWithSchema(valueType);
315             final Object schema = typeWithSchema.getValue();
316             Preconditions.checkState(schema instanceof TypeDefinition<?>);
317             return getCodec(valueType, (TypeDefinition<?>) schema);
318         }
319         return ValueTypeCodec.getCodecFor(valueType, typeDef);
320     }
321
322     @Override
323     public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
324             final ListSchemaNode schema) {
325         final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
326                 Identifiable.class);
327         final Map<QName, ValueContext> valueCtx = new HashMap<>();
328         for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
329             final QName name = leaf.getDomPathArgument().getNodeType();
330             valueCtx.put(name, new ValueContext(identifier, leaf));
331         }
332         return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
333     }
334
335     @SuppressWarnings("unchecked")
336     @Override
337     public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
338         // TODO Do we need defensive check here?
339         return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
340     }
341
342     @Override
343     public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
344         return getCodecContextNode(path, null);
345     }
346
347     @Override
348     public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
349         throw new UnsupportedOperationException("Not implemented yet.");
350     }
351 }