Split out codecs from BindingCodecContext
[yangtools.git] / code-generator / binding-data-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.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
26 import org.opendaylight.yangtools.concepts.Codec;
27 import org.opendaylight.yangtools.concepts.Immutable;
28 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
29 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
30 import org.opendaylight.yangtools.util.ClassLoaderUtils;
31 import org.opendaylight.yangtools.yang.binding.BindingMapping;
32 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
33 import org.opendaylight.yangtools.yang.binding.DataContainer;
34 import org.opendaylight.yangtools.yang.binding.Identifiable;
35 import org.opendaylight.yangtools.yang.binding.Identifier;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
38 import org.opendaylight.yangtools.yang.binding.Notification;
39 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
43 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
50 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 final class BindingCodecContext implements CodecContextFactory, Immutable {
61     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
62     static final String GETTER_PREFIX = "get";
63
64     private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
65     private final Codec<QName, Class<?>> identityCodec;
66     private final BindingRuntimeContext context;
67     private final SchemaRootCodecContext root;
68
69     public BindingCodecContext(final BindingRuntimeContext context) {
70         this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
71         this.root = SchemaRootCodecContext.create(this);
72         this.identityCodec = new IdentityCodec(context);
73         this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
74     }
75
76     @Override
77     public BindingRuntimeContext getRuntimeContext() {
78         return context;
79     }
80
81     Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
82         return instanceIdentifierCodec;
83     }
84
85     public Codec<QName, Class<?>> getIdentityCodec() {
86         return identityCodec;
87     }
88
89     public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
90             final NormalizedNodeStreamWriter domWriter) {
91         final LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
92         final DataContainerCodecContext<?> codecContext = getCodecContextNode(path, yangArgs);
93         final BindingStreamEventWriter writer = new BindingToNormalizedStreamWriter(codecContext, domWriter);
94         return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), writer);
95     }
96
97     public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
98             final NormalizedNodeStreamWriter domWriter) {
99         return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
100     }
101
102     BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
103             final NormalizedNodeStreamWriter domWriter) {
104         final NodeCodecContext schema = root.getRpc(rpcInputOrOutput);
105         return new BindingToNormalizedStreamWriter(schema, domWriter);
106     }
107
108     BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
109             final NormalizedNodeStreamWriter domWriter) {
110         final NodeCodecContext schema = root.getNotification(notification);
111         return new BindingToNormalizedStreamWriter(schema, domWriter);
112     }
113
114     public DataContainerCodecContext<?> getCodecContextNode(final InstanceIdentifier<?> binding,
115             final List<YangInstanceIdentifier.PathArgument> builder) {
116         DataContainerCodecContext<?> currentNode = root;
117         for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
118             currentNode = currentNode.getIdentifierChild(bindingArg, builder);
119         }
120         return currentNode;
121     }
122
123     /**
124      * Multi-purpose utility function. Traverse the codec tree, looking for
125      * the appropriate codec for the specified {@link YangInstanceIdentifier}.
126      * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
127      * into the supplied collection.
128      *
129      * @param dom {@link YangInstanceIdentifier} which is to be translated
130      * @param bindingArguments Collection for traversed path arguments
131      * @return Codec for target node, or @null if the node does not have a
132      *         binding representation (choice, case, leaf).
133      */
134     @Nullable NodeCodecContext getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
135             final @Nonnull Collection<InstanceIdentifier.PathArgument> bindingArguments) {
136         NodeCodecContext currentNode = root;
137         ListNodeCodecContext currentList = null;
138
139         for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
140             Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?>, "Unexpected child of non-container node %s", currentNode);
141             final DataContainerCodecContext<?> previous = (DataContainerCodecContext<?>) currentNode;
142             final NodeCodecContext nextNode = previous.getYangIdentifierChild(domArg);
143
144             /*
145              * List representation in YANG Instance Identifier consists of two
146              * arguments: first is list as a whole, second is list as an item so
147              * if it is /list it means list as whole, if it is /list/list - it
148              * is wildcarded and if it is /list/list[key] it is concrete item,
149              * all this variations are expressed in Binding Aware Instance
150              * Identifier as Item or IdentifiableItem
151              */
152             if (currentList != null) {
153                 Preconditions.checkArgument(currentList == nextNode, "List should be referenced two times in YANG Instance Identifier %s", dom);
154
155                 // We entered list, so now we have all information to emit
156                 // list path using second list argument.
157                 bindingArguments.add(currentList.getBindingPathArgument(domArg));
158                 currentList = null;
159                 currentNode = nextNode;
160             } else if (nextNode instanceof ListNodeCodecContext) {
161                 // We enter list, we do not update current Node yet,
162                 // since we need to verify
163                 currentList = (ListNodeCodecContext) nextNode;
164             } else if (nextNode instanceof ChoiceNodeCodecContext) {
165                 // We do not add path argument for choice, since
166                 // it is not supported by binding instance identifier.
167                 currentNode = nextNode;
168             } else if (nextNode instanceof DataContainerCodecContext<?>) {
169                 bindingArguments.add(((DataContainerCodecContext<?>) nextNode).getBindingPathArgument(domArg));
170                 currentNode = nextNode;
171             } else if (nextNode instanceof LeafNodeCodecContext) {
172                 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
173                 return null;
174             }
175         }
176
177         // Algorithm ended in list as whole representation
178         // we sill need to emit identifier for list
179         if (currentNode instanceof ChoiceNodeCodecContext) {
180             LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
181             return null;
182         }
183         if (currentNode instanceof CaseNodeCodecContext) {
184             LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
185             return null;
186         }
187
188         if (currentList != null) {
189             bindingArguments.add(currentList.getBindingPathArgument(null));
190             return currentList;
191         }
192         return currentNode;
193     }
194
195     NotificationCodecContext getNotificationContext(final SchemaPath notification) {
196         return root.getNotification(notification);
197     }
198
199     ContainerNodeCodecContext getRpcDataContext(final SchemaPath path) {
200         return root.getRpc(path);
201     }
202
203     @Override
204     public ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(final Class<?> parentClass,
205             final DataNodeContainer childSchema) {
206         final HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
207         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
208             final TypeDefinition<?> typeDef;
209             if (leaf instanceof LeafSchemaNode) {
210                 typeDef = ((LeafSchemaNode) leaf).getType();
211             } else if (leaf instanceof LeafListSchemaNode) {
212                 typeDef = ((LeafListSchemaNode) leaf).getType();
213             } else {
214                 continue;
215             }
216
217             final String getterName = getGetterName(leaf.getQName(), typeDef);
218             getterToLeafSchema.put(getterName, leaf);
219         }
220         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
221     }
222
223     private String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
224         final String suffix = BindingMapping.getClassName(qName);
225
226         while (typeDef.getBaseType() != null) {
227             typeDef = typeDef.getBaseType();
228         }
229         if (typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) {
230             return "is" + suffix;
231         }
232         return GETTER_PREFIX + suffix;
233     }
234
235     private ImmutableMap<String, LeafNodeCodecContext> getLeafNodesUsingReflection(final Class<?> parentClass,
236             final Map<String, DataSchemaNode> getterToLeafSchema) {
237         final Map<String, LeafNodeCodecContext> leaves = new HashMap<>();
238         for (final Method method : parentClass.getMethods()) {
239             if (method.getParameterTypes().length == 0) {
240                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
241                 final Class<?> valueType;
242                 if (schema instanceof LeafSchemaNode) {
243                     valueType = method.getReturnType();
244                 } else if (schema instanceof LeafListSchemaNode) {
245                     final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
246
247                     if (genericType instanceof Class<?>) {
248                         valueType = (Class<?>) genericType;
249                     } else if (genericType instanceof ParameterizedType) {
250                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
251                     } else {
252                         throw new IllegalStateException("Unexpected return type " + genericType);
253                     }
254                 } else {
255                     continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
256                 }
257                 final Codec<Object, Object> codec = getCodec(valueType, schema);
258                 final LeafNodeCodecContext leafNode = new LeafNodeCodecContext(schema, codec, method);
259                 leaves.put(schema.getQName().getLocalName(), leafNode);
260             }
261         }
262         return ImmutableMap.copyOf(leaves);
263     }
264
265     private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
266         final TypeDefinition<?> instantiatedType;
267         if (schema instanceof LeafSchemaNode) {
268             instantiatedType = ((LeafSchemaNode) schema).getType();
269         } else if (schema instanceof LeafListSchemaNode) {
270             instantiatedType = ((LeafListSchemaNode) schema).getType();
271         } else {
272             throw new IllegalArgumentException("Unsupported leaf node type " + schema.getClass());
273         }
274         if (Class.class.equals(valueType)) {
275             @SuppressWarnings({ "unchecked", "rawtypes" })
276             final Codec<Object, Object> casted = (Codec) identityCodec;
277             return casted;
278         } else if (InstanceIdentifier.class.equals(valueType)) {
279             @SuppressWarnings({ "unchecked", "rawtypes" })
280             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
281             return casted;
282         } else if (Boolean.class.equals(valueType)) {
283             if(instantiatedType instanceof EmptyTypeDefinition) {
284                 return ValueTypeCodec.EMPTY_CODEC;
285             }
286         } else if (BindingReflections.isBindingClass(valueType)) {
287                             return getCodec(valueType, instantiatedType);
288         }
289         return ValueTypeCodec.NOOP_CODEC;
290     }
291
292     private Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
293         @SuppressWarnings("rawtypes")
294         TypeDefinition rootType = instantiatedType;
295         while (rootType.getBaseType() != null) {
296             rootType = rootType.getBaseType();
297         }
298         if (rootType instanceof IdentityrefTypeDefinition) {
299             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
300         } else if (rootType instanceof InstanceIdentifierTypeDefinition) {
301             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
302         } else if (rootType instanceof UnionTypeDefinition) {
303             final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) rootType);
304             try {
305                 return loader.call();
306             } catch (final Exception e) {
307                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
308             }
309         } else if(rootType instanceof LeafrefTypeDefinition) {
310             final Entry<GeneratedType, Object> typeWithSchema = context.getTypeWithSchema(valueType);
311             final Object schema = typeWithSchema.getValue();
312             Preconditions.checkState(schema instanceof TypeDefinition<?>);
313             return getCodec(valueType, (TypeDefinition<?>) schema);
314         }
315         return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
316     }
317
318     @Override
319     public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
320             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 new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
329     }
330 }