dfef41afc0aedd37bac71784384be0b3e816db95
[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
13 import java.lang.reflect.Constructor;
14 import java.lang.reflect.InvocationTargetException;
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.ArrayList;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.LinkedHashMap;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.concurrent.Callable;
28
29 import javax.annotation.Nonnull;
30 import javax.annotation.Nullable;
31
32 import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
33 import org.opendaylight.yangtools.concepts.Codec;
34 import org.opendaylight.yangtools.concepts.Immutable;
35 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
36 import org.opendaylight.yangtools.util.ClassLoaderUtils;
37 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
38 import org.opendaylight.yangtools.yang.binding.BindingMapping;
39 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
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.util.BindingReflections;
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.LeafListSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
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.IdentityrefTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 class BindingCodecContext implements CodecContextFactory, Immutable {
63     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
64     private static final String GETTER_PREFIX = "get";
65
66     private final SchemaRootCodecContext root;
67     private final BindingRuntimeContext context;
68     private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec =
69             new InstanceIdentifierCodec();
70     private final Codec<QName, Class<?>> identityCodec = new IdentityCodec();
71
72     public BindingCodecContext(final BindingRuntimeContext context) {
73         this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
74         this.root = SchemaRootCodecContext.create(this);
75     }
76
77     @Override
78     public BindingRuntimeContext getRuntimeContext() {
79         return context;
80     }
81
82     Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
83         return instanceIdentifierCodec;
84     }
85
86     public Codec<QName, Class<?>> getIdentityCodec() {
87         return identityCodec;
88     }
89
90     public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
91             final NormalizedNodeStreamWriter domWriter) {
92         LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
93         DataContainerCodecContext<?> codecContext = getCodecContextNode(path, yangArgs);
94         BindingStreamEventWriter writer = new BindingToNormalizedStreamWriter(codecContext, domWriter);
95         return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), writer);
96     }
97
98     public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
99             final NormalizedNodeStreamWriter domWriter) {
100         return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
101     }
102
103     public DataContainerCodecContext<?> getCodecContextNode(final InstanceIdentifier<?> binding,
104             final List<YangInstanceIdentifier.PathArgument> builder) {
105         DataContainerCodecContext<?> currentNode = root;
106         for (InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
107             currentNode = currentNode.getIdentifierChild(bindingArg, builder);
108         }
109         return currentNode;
110     }
111
112     /**
113      * Multi-purpose utility function. Traverse the codec tree, looking for
114      * the appropriate codec for the specified {@link YangInstanceIdentifier}.
115      * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
116      * into the supplied collection.
117      *
118      * @param dom {@link YangInstanceIdentifier} which is to be translated
119      * @param bindingArguments Collection for traversed path arguments
120      * @return Codec for target node, or @null if the node does not have a
121      *         binding representation (choice, case, leaf).
122      */
123     @Nullable NodeCodecContext getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
124             final @Nonnull Collection<InstanceIdentifier.PathArgument> bindingArguments) {
125         NodeCodecContext currentNode = root;
126         ListNodeCodecContext currentList = null;
127
128         for (YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
129             Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?>, "Unexpected child of non-container node %s", currentNode);
130             final DataContainerCodecContext<?> previous = (DataContainerCodecContext<?>) currentNode;
131             final NodeCodecContext nextNode = previous.getYangIdentifierChild(domArg);
132
133             /*
134              * List representation in YANG Instance Identifier consists of two
135              * arguments: first is list as a whole, second is list as an item so
136              * if it is /list it means list as whole, if it is /list/list - it
137              * is wildcarded and if it is /list/list[key] it is concrete item,
138              * all this variations are expressed in Binding Aware Instance
139              * Identifier as Item or IdentifiableItem
140              */
141             if (currentList != null) {
142                 Preconditions.checkArgument(currentList == nextNode, "List should be referenced two times in YANG Instance Identifier %s", dom);
143
144                 // We entered list, so now we have all information to emit
145                 // list path using second list argument.
146                 bindingArguments.add(currentList.getBindingPathArgument(domArg));
147                 currentList = null;
148                 currentNode = nextNode;
149             } else if (nextNode instanceof ListNodeCodecContext) {
150                 // We enter list, we do not update current Node yet,
151                 // since we need to verify
152                 currentList = (ListNodeCodecContext) nextNode;
153             } else if (nextNode instanceof ChoiceNodeCodecContext) {
154                 // We do not add path argument for choice, since
155                 // it is not supported by binding instance identifier.
156                 currentNode = nextNode;
157             } else if (nextNode instanceof DataContainerCodecContext<?>) {
158                 bindingArguments.add(((DataContainerCodecContext<?>) nextNode).getBindingPathArgument(domArg));
159                 currentNode = nextNode;
160             } else if (nextNode instanceof LeafNodeCodecContext) {
161                 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
162                 return null;
163             }
164         }
165
166         // Algorithm ended in list as whole representation
167         // we sill need to emit identifier for list
168         if (currentNode instanceof ChoiceNodeCodecContext) {
169             LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
170             return null;
171         }
172         if (currentNode instanceof CaseNodeCodecContext) {
173             LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
174             return null;
175         }
176
177         if (currentList != null) {
178             bindingArguments.add(currentList.getBindingPathArgument(null));
179             return currentList;
180         }
181         return currentNode;
182     }
183
184     @Override
185     public ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(final Class<?> parentClass,
186             final DataNodeContainer childSchema) {
187         HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
188         for (DataSchemaNode leaf : childSchema.getChildNodes()) {
189             final TypeDefinition<?> typeDef;
190             if (leaf instanceof LeafSchemaNode) {
191                 typeDef = ((LeafSchemaNode) leaf).getType();
192             } else if (leaf instanceof LeafListSchemaNode) {
193                 typeDef = ((LeafListSchemaNode) leaf).getType();
194             } else {
195                 continue;
196             }
197
198             String getterName = getGetterName(leaf.getQName(), typeDef);
199             getterToLeafSchema.put(getterName, leaf);
200         }
201         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
202     }
203
204     private String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
205         String suffix = BindingMapping.getClassName(qName);
206
207         while (typeDef.getBaseType() != null) {
208             typeDef = typeDef.getBaseType();
209         }
210         if (typeDef instanceof BooleanTypeDefinition) {
211             return "is" + suffix;
212         }
213         return GETTER_PREFIX + suffix;
214     }
215
216     private ImmutableMap<String, LeafNodeCodecContext> getLeafNodesUsingReflection(final Class<?> parentClass,
217             final Map<String, DataSchemaNode> getterToLeafSchema) {
218         Map<String, LeafNodeCodecContext> leaves = new HashMap<>();
219         for (Method method : parentClass.getMethods()) {
220             if (method.getParameterTypes().length == 0) {
221                 DataSchemaNode schema = getterToLeafSchema.get(method.getName());
222                 final Class<?> valueType;
223                 if (schema instanceof LeafSchemaNode) {
224                     valueType = method.getReturnType();
225                 } else if (schema instanceof LeafListSchemaNode) {
226                     Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
227
228                     if (genericType instanceof Class<?>) {
229                         valueType = (Class<?>) genericType;
230                     } else if (genericType instanceof ParameterizedType) {
231                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
232                     } else {
233                         throw new IllegalStateException("Unexpected return type " + genericType);
234                     }
235                 } else {
236                     continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
237                 }
238                 Codec<Object, Object> codec = getCodec(valueType, schema);
239                 final LeafNodeCodecContext leafNode = new LeafNodeCodecContext(schema, codec, method);
240                 leaves.put(schema.getQName().getLocalName(), leafNode);
241             }
242         }
243         return ImmutableMap.copyOf(leaves);
244     }
245
246
247
248     private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
249         if (Class.class.equals(valueType)) {
250             @SuppressWarnings({ "unchecked", "rawtypes" })
251             final Codec<Object, Object> casted = (Codec) identityCodec;
252             return casted;
253         } else if (InstanceIdentifier.class.equals(valueType)) {
254             @SuppressWarnings({ "unchecked", "rawtypes" })
255             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
256             return casted;
257         } else if (BindingReflections.isBindingClass(valueType)) {
258             final TypeDefinition<?> instantiatedType;
259             if (schema instanceof LeafSchemaNode) {
260                 instantiatedType = ((LeafSchemaNode) schema).getType();
261             } else if (schema instanceof LeafListSchemaNode) {
262                 instantiatedType = ((LeafListSchemaNode) schema).getType();
263             } else {
264                 instantiatedType = null;
265             }
266             if (instantiatedType != null) {
267                 return getCodec(valueType, instantiatedType);
268             }
269         }
270         return ValueTypeCodec.NOOP_CODEC;
271     }
272
273     private Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
274         @SuppressWarnings("rawtypes")
275         TypeDefinition rootType = instantiatedType;
276         while (rootType.getBaseType() != null) {
277             rootType = rootType.getBaseType();
278         }
279         if (rootType instanceof IdentityrefTypeDefinition) {
280             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
281         } else if (rootType instanceof InstanceIdentifierTypeDefinition) {
282             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
283         } else if (rootType instanceof UnionTypeDefinition) {
284             Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) rootType);
285             try {
286                 return loader.call();
287             } catch (Exception e) {
288                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
289             }
290         }
291         return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
292     }
293
294     private class InstanceIdentifierCodec implements Codec<YangInstanceIdentifier, InstanceIdentifier<?>> {
295
296         @Override
297         public YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
298             List<YangInstanceIdentifier.PathArgument> domArgs = new ArrayList<>();
299             getCodecContextNode(input, domArgs);
300             return YangInstanceIdentifier.create(domArgs);
301         }
302
303         @Override
304         public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
305             final List<InstanceIdentifier.PathArgument> builder = new ArrayList<>();
306             final NodeCodecContext codec = getCodecContextNode(input, builder);
307             return codec == null ? null : InstanceIdentifier.create(builder);
308         }
309     }
310
311     private class IdentityCodec implements Codec<QName, Class<?>> {
312
313         @Override
314         public Class<?> deserialize(final QName input) {
315             Preconditions.checkArgument(input != null, "Input must not be null.");
316             return context.getIdentityClass(input);
317         }
318
319         @Override
320         public QName serialize(final Class<?> input) {
321             Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
322             return BindingReflections.findQName(input);
323         }
324     }
325
326     private static class ValueContext {
327
328         Method getter;
329         Codec<Object, Object> codec;
330
331         public ValueContext(final Class<?> identifier, final LeafNodeCodecContext leaf) {
332             final String getterName = GETTER_PREFIX
333                     + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
334             try {
335                 getter = identifier.getMethod(getterName);
336             } catch (NoSuchMethodException | SecurityException e) {
337                 throw new IllegalStateException(e);
338             }
339             codec = leaf.getValueCodec();
340         }
341
342         public Object getAndSerialize(final Object obj) {
343             try {
344                 Object value = getter.invoke(obj);
345                 Preconditions.checkArgument(value != null,
346                         "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
347                         getter.getDeclaringClass(), getter.getName(), obj);
348                 return codec.serialize(value);
349             } catch (IllegalAccessException | InvocationTargetException e) {
350                 throw new IllegalArgumentException(e);
351             }
352         }
353
354         public Object deserialize(final Object obj) {
355             return codec.deserialize(obj);
356         }
357
358     }
359
360     private static class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
361
362         private final Map<QName, ValueContext> keyValueContexts;
363         private final ListSchemaNode schema;
364         private final Constructor<? extends Identifier<?>> constructor;
365         private final Class<?> identifiable;
366
367         public IdentifiableItemCodec(final ListSchemaNode schema, final Class<? extends Identifier<?>> keyClass,
368                 final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
369             this.schema = schema;
370             this.identifiable = identifiable;
371             this.constructor = getConstructor(keyClass);
372
373             /*
374              * We need to re-index to make sure we instantiate nodes in the order in which
375              * they are defined.
376              */
377             final Map<QName, ValueContext> keys = new LinkedHashMap<>();
378             for (QName qname : schema.getKeyDefinition()) {
379                 keys.put(qname, keyValueContexts.get(qname));
380             }
381             this.keyValueContexts = ImmutableMap.copyOf(keys);
382         }
383
384         @Override
385         public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
386             final Collection<QName> keys = schema.getKeyDefinition();
387             final ArrayList<Object> bindingValues = new ArrayList<>(keys.size());
388             for (QName key : keys) {
389                 Object yangValue = input.getKeyValues().get(key);
390                 bindingValues.add(keyValueContexts.get(key).deserialize(yangValue));
391             }
392
393             final Identifier<?> identifier;
394             try {
395                 identifier = constructor.newInstance(bindingValues.toArray());
396             } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
397                 throw new IllegalStateException(String.format("Failed to instantiate key class %s", constructor.getDeclaringClass()), e);
398             }
399
400             @SuppressWarnings({ "rawtypes", "unchecked" })
401             final IdentifiableItem identifiableItem = new IdentifiableItem(identifiable, identifier);
402             return identifiableItem;
403         }
404
405         @Override
406         public NodeIdentifierWithPredicates serialize(final IdentifiableItem<?, ?> input) {
407             Object value = input.getKey();
408
409             Map<QName, Object> values = new LinkedHashMap<>();
410             for (Entry<QName, ValueContext> valueCtx : keyValueContexts.entrySet()) {
411                 values.put(valueCtx.getKey(), valueCtx.getValue().getAndSerialize(value));
412             }
413             return new NodeIdentifierWithPredicates(schema.getQName(), values);
414         }
415     }
416
417     @SuppressWarnings("unchecked")
418     private static Constructor<? extends Identifier<?>> getConstructor(final Class<? extends Identifier<?>> clazz) {
419         for (@SuppressWarnings("rawtypes") Constructor constr : clazz.getConstructors()) {
420             Class<?>[] parameters = constr.getParameterTypes();
421             if (!clazz.equals(parameters[0])) {
422                 // It is not copy constructor;
423                 return constr;
424             }
425         }
426         throw new IllegalArgumentException("Supplied class " + clazz + "does not have required constructor.");
427     }
428
429     @Override
430     public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
431             final ListSchemaNode schema) {
432         Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
433                 Identifiable.class);
434         Map<QName, ValueContext> valueCtx = new HashMap<>();
435         for (LeafNodeCodecContext leaf : getLeafNodes(identifier, schema).values()) {
436             QName name = leaf.getDomPathArgument().getNodeType();
437             valueCtx.put(name, new ValueContext(identifier, leaf));
438         }
439         return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
440     }
441
442 }