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