Binding codec v2 - fix anyxml #2
[mdsal.git] / binding2 / mdsal-binding2-dom-codec / src / main / java / org / opendaylight / mdsal / binding / javav2 / dom / codec / impl / context / base / BindingCodecContext.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.javav2.dom.codec.impl.context.base;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import java.lang.reflect.Method;
14 import java.lang.reflect.ParameterizedType;
15 import java.lang.reflect.Type;
16 import java.util.AbstractMap.SimpleEntry;
17 import java.util.Collection;
18 import java.util.HashMap;
19 import java.util.LinkedList;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import java.util.concurrent.Callable;
24 import javax.annotation.Nonnull;
25 import javax.annotation.Nullable;
26 import javax.xml.transform.dom.DOMSource;
27 import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeCodec;
28 import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec;
29 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.AnyxmlCodec;
30 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
31 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.IdentifiableItemCodec;
32 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.IdentityCodec;
33 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.InstanceIdentifierCodec;
34 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.OperationInputCodec;
35 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.UnionTypeCodec;
36 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.CaseNodeCodecContext;
37 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ChoiceNodeCodecContext;
38 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ListNodeCodecContext;
39 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.NotificationCodecContext;
40 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.SchemaRootCodecContext;
41 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ValueContext;
42 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.NodeCodecContext.CodecContextFactory;
43 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.value.ValueTypeCodec;
44 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier;
45 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer;
46 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType;
47 import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext;
48 import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections;
49 import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem;
50 import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier;
51 import org.opendaylight.mdsal.binding.javav2.spec.base.Instantiable;
52 import org.opendaylight.mdsal.binding.javav2.spec.base.Notification;
53 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument;
54 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
55 import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingStreamEventWriter;
56 import org.opendaylight.mdsal.binding.javav2.spec.runtime.TreeNodeSerializer;
57 import org.opendaylight.yangtools.concepts.Codec;
58 import org.opendaylight.yangtools.concepts.Identifiable;
59 import org.opendaylight.yangtools.concepts.Identifier;
60 import org.opendaylight.yangtools.concepts.Immutable;
61 import org.opendaylight.yangtools.util.ClassLoaderUtils;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
65 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
66 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
67 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
72 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82 import org.w3c.dom.Document;
83
84 /**
85  * Binding codec context for holding runtime part and codecs.
86  */
87 @Beta
88 public final class BindingCodecContext implements CodecContextFactory, BindingTreeCodec, Immutable {
89
90     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
91
92     private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
93     private final Codec<QName, Class<?>> identityCodec;
94     private final Codec<DOMSource, Document> anyxmlCodec;
95     private final BindingNormalizedNodeCodecRegistry registry;
96     private final BindingRuntimeContext context;
97     private final SchemaRootCodecContext<?> root;
98
99     /**
100      * Prepare runtime context and codec registry.
101      *
102      * @param context
103      *            - runtime context
104      * @param registry
105      *            - binding normalized node codec registry
106      */
107     public BindingCodecContext(final BindingRuntimeContext context, final BindingNormalizedNodeCodecRegistry registry) {
108         this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
109         this.root = SchemaRootCodecContext.create(this);
110         this.identityCodec = new IdentityCodec(context);
111         this.anyxmlCodec = new AnyxmlCodec(context);
112         this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
113         this.registry = Preconditions.checkNotNull(registry);
114     }
115
116     @Override
117     public BindingRuntimeContext getRuntimeContext() {
118         return context;
119     }
120
121     /**
122      * Get instance identifier codec.
123      *
124      * @return instance identifier codec
125      */
126     public Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
127         return instanceIdentifierCodec;
128     }
129
130     /**
131      * Get identity codec.
132      *
133      * @return identity codec
134      */
135     public Codec<QName, Class<?>> getIdentityCodec() {
136         return identityCodec;
137     }
138
139     /**
140      * Get anyxml codec.
141      *
142      * @return anyxml codec
143      */
144     public Codec<DOMSource, Document> getAnyxmlCodec() {
145         return anyxmlCodec;
146     }
147
148     @SuppressWarnings({ "rawtypes", "unchecked" })
149     @Override
150     public TreeNodeSerializer getEventStreamSerializer(final Class<?> type) {
151         return registry.getSerializer((Class) type);
152     }
153
154     /**
155      * Prepare specific writer for binding path.
156      *
157      * @param path
158      *            - binding path
159      * @param domWriter
160      *            - DOM writer
161      * @return entry of DOM path and writer
162      */
163     public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
164             final NormalizedNodeStreamWriter domWriter) {
165         final List<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
166         final DataContainerCodecContext<?, ?> codecContext = getCodecContextNode(path, yangArgs);
167         return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
168     }
169
170     /**
171      * Prepare specific writer for binding path without DOM identifier.
172      *
173      * @param path
174      *            - binding path
175      * @param domWriter
176      *            - DOM writer
177      * @return stream event writer for binding path
178      */
179     public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
180             final NormalizedNodeStreamWriter domWriter) {
181         return getCodecContextNode(path, null).createWriter(domWriter);
182     }
183
184     /**
185      * Prepare specific writer for operations.
186      *
187      * @param operationInputOrOutput
188      *            - binding data
189      * @param domWriter
190      *            - DOM writer
191      * @return stream event writer for operation
192      */
193     public BindingStreamEventWriter newOperationWriter(final Class<? extends Instantiable<?>> operationInputOrOutput,
194             final NormalizedNodeStreamWriter domWriter) {
195         return root.getOperation(operationInputOrOutput).createWriter(domWriter);
196     }
197
198     @SuppressWarnings("rawtypes")
199     public BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
200             final NormalizedNodeStreamWriter domWriter) {
201         return root.getNotification(notification).createWriter(domWriter);
202     }
203
204     /**
205      * Prepare context from Binding and DOM path.
206      *
207      * @param binding
208      *            - binding path
209      * @param builder
210      *            - DOM path
211      *
212      * @return context for path
213      */
214     public DataContainerCodecContext<?, ?> getCodecContextNode(final InstanceIdentifier<?> binding,
215             final List<YangInstanceIdentifier.PathArgument> builder) {
216         DataContainerCodecContext<?, ?> currentNode = root;
217         for (final TreeArgument<?> bindingArg : binding.getPathArguments()) {
218             currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
219             Preconditions.checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.", binding);
220         }
221         return currentNode;
222     }
223
224     /**
225      * Multi-purpose utility function. Traverse the codec tree, looking for the appropriate codec for the
226      * specified {@link YangInstanceIdentifier}. As a side-effect, gather all traversed binding
227      * {@link TreeArgument} into the supplied collection.
228      *
229      * @param dom
230      *            {@link YangInstanceIdentifier} which is to be translated
231      * @param bindingArguments
232      *            Collection for traversed path arguments
233      * @return Codec for target node, or @null if the node does not have a binding representation (choice,
234      *         case, leaf).
235      *
236      */
237     @Nullable
238     public NodeCodecContext<?> getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
239             final @Nullable Collection<TreeArgument<?>> bindingArguments) {
240         NodeCodecContext<?> currentNode = root;
241         ListNodeCodecContext<?> currentList = null;
242
243         for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
244             Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?, ?>,
245                     "Unexpected child of non-container node %s", currentNode);
246             final DataContainerCodecContext<?, ?> previous = (DataContainerCodecContext<?, ?>) currentNode;
247             final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
248
249             /*
250              * List representation in YANG Instance Identifier consists of two arguments: first is list as a
251              * whole, second is list as an item so if it is /list it means list as whole, if it is /list/list
252              * - it is wildcarded and if it is /list/list[key] it is concrete item, all this variations are
253              * expressed in Binding Aware Instance Identifier as Item or IdentifiableItem
254              */
255             if (currentList != null) {
256                 Preconditions.checkArgument(currentList == nextNode,
257                         "List should be referenced two times in YANG Instance Identifier %s", dom);
258
259                 // We entered list, so now we have all information to emit
260                 // list path using second list argument.
261                 if (bindingArguments != null) {
262                     bindingArguments.add(currentList.getBindingPathArgument(domArg));
263                 }
264                 currentList = null;
265                 currentNode = nextNode;
266             } else if (nextNode instanceof ListNodeCodecContext) {
267                 // We enter list, we do not update current Node yet,
268                 // since we need to verify
269                 currentList = (ListNodeCodecContext<?>) nextNode;
270             } else if (nextNode instanceof ChoiceNodeCodecContext) {
271                 // We do not add path argument for choice, since
272                 // it is not supported by binding instance identifier.
273                 currentNode = nextNode;
274             } else if (nextNode instanceof DataContainerCodecContext<?, ?>) {
275                 if (bindingArguments != null) {
276                     bindingArguments.add(((DataContainerCodecContext<?, ?>) nextNode).getBindingPathArgument(domArg));
277                 }
278                 currentNode = nextNode;
279             } else if (nextNode instanceof LeafNodeCodecContext) {
280                 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
281                 return null;
282             }
283         }
284
285         // Algorithm ended in list as whole representation
286         // we sill need to emit identifier for list
287         if (currentNode instanceof ChoiceNodeCodecContext) {
288             LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
289             return null;
290         }
291         if (currentNode instanceof CaseNodeCodecContext) {
292             LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
293             return null;
294         }
295
296         if (currentList != null) {
297             if (bindingArguments != null) {
298                 bindingArguments.add(currentList.getBindingPathArgument(null));
299             }
300             return currentList;
301         }
302         return currentNode;
303     }
304
305     /**
306      * Get notification codec according to notification schema path.
307      *
308      * @param notification
309      *            - schema path of notification
310      * @return notification codec context
311      */
312     public NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
313         return root.getNotification(notification);
314     }
315
316     /**
317      * Get operation input codec.
318      *
319      * @param path
320      *            - path of input data of operation
321      * @return operation input codec
322      */
323     public OperationInputCodec<?> getOperationInputCodec(final SchemaPath path) {
324         return root.getOperation(path);
325     }
326
327     @Override
328     public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
329             final DataNodeContainer childSchema) {
330         final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
331         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
332             if (leaf instanceof TypedDataSchemaNode) {
333                 getterToLeafSchema.put(getGetterName(leaf.getQName(), ((TypedDataSchemaNode) leaf).getType()), leaf);
334             }
335         }
336         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
337     }
338
339     private static String getGetterName(final QName qname, final TypeDefinition<?> typeDef) {
340         final String suffix =
341                 JavaIdentifierNormalizer.normalizeSpecificIdentifier(qname.getLocalName(), JavaIdentifier.CLASS);
342         if (typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) {
343             return "is" + suffix;
344         }
345         return "get" + suffix;
346     }
347
348     private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
349             final Map<String, DataSchemaNode> getterToLeafSchema) {
350         final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
351         for (final Method method : parentClass.getMethods()) {
352             if (method.getParameterTypes().length == 0) {
353                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
354                 final Class<?> valueType;
355                 if (schema instanceof LeafSchemaNode) {
356                     valueType = method.getReturnType();
357                 } else if (schema instanceof LeafListSchemaNode) {
358                     final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
359
360                     if (genericType instanceof Class<?>) {
361                         valueType = (Class<?>) genericType;
362                     } else if (genericType instanceof ParameterizedType) {
363                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
364                     } else {
365                         throw new IllegalStateException("Unexpected return type " + genericType);
366                     }
367                 } else {
368                     continue; // We do not have schema for leaf, so we will ignore it (eg. getClass,
369                               // getImplementedInterface).
370                 }
371                 final Codec<Object, Object> codec = getCodec(valueType, schema);
372                 final LeafNodeCodecContext<?> leafNode =
373                         new LeafNodeCodecContext<>(schema, codec, method, context.getSchemaContext());
374                 leaves.put(schema.getQName().getLocalName(), leafNode);
375             }
376         }
377         return ImmutableMap.copyOf(leaves);
378     }
379
380     private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
381         Preconditions.checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema);
382
383         return getCodec(valueType, ((TypedDataSchemaNode) schema).getType());
384     }
385
386     /**
387      * Get specific codec for binding class by type.
388      *
389      * @param valueType
390      *            - binding class
391      * @param instantiatedType
392      *            - type definition
393      * @return specific codec
394      */
395     public Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
396         if (Class.class.equals(valueType)) {
397             @SuppressWarnings({ "unchecked", "rawtypes" })
398             final Codec<Object, Object> casted = (Codec) identityCodec;
399             return casted;
400         } else if (InstanceIdentifier.class.equals(valueType)) {
401             @SuppressWarnings({ "unchecked", "rawtypes" })
402             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
403             return casted;
404         } else if (Boolean.class.equals(valueType)) {
405             if (instantiatedType instanceof EmptyTypeDefinition) {
406                 return ValueTypeCodec.EMPTY_CODEC;
407             }
408         } else if (BindingReflections.isBindingClass(valueType)) {
409             return getCodecForBindingClass(valueType, instantiatedType);
410         }
411         return ValueTypeCodec.NOOP_CODEC;
412     }
413
414     @SuppressWarnings("checkstyle:IllegalCatch")
415     private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
416         if (typeDef instanceof IdentityrefTypeDefinition) {
417             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
418         } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
419             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
420         } else if (typeDef instanceof UnionTypeDefinition) {
421             final Callable<UnionTypeCodec> loader =
422                     UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef, this);
423             try {
424                 return loader.call();
425             } catch (final Exception e) {
426                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
427             }
428         } else if (typeDef instanceof LeafrefTypeDefinition) {
429             final Entry<GeneratedType, Object> typeWithSchema = context.getTypeWithSchema(valueType);
430             final Object schema = typeWithSchema.getValue();
431             Preconditions.checkState(schema instanceof TypeDefinition<?>);
432             return getCodec(valueType, (TypeDefinition<?>) schema);
433         }
434         return ValueTypeCodec.getCodecFor(valueType, typeDef);
435     }
436
437     @Override
438     public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
439             final ListSchemaNode schema) {
440         final Class<? extends Identifier> identifier =
441                 ClassLoaderUtils.findFirstGenericArgument(listClz, Identifiable.class);
442         final Map<QName, ValueContext> valueCtx = new HashMap<>();
443         for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
444             final QName name = leaf.getDomPathArgument().getNodeType();
445             valueCtx.put(name, new ValueContext(identifier, leaf));
446         }
447         return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
448     }
449
450     @SuppressWarnings("unchecked")
451     @Nullable
452     @Override
453     public <T extends TreeNode> BindingTreeNodeCodec<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
454         return (BindingTreeNodeCodec<T>) getCodecContextNode(path, null);
455     }
456
457     @Nullable
458     @Override
459     public BindingTreeNodeCodec<?> getSubtreeCodec(final YangInstanceIdentifier path) {
460         return getCodecContextNode(path, null);
461     }
462
463     @Nullable
464     @Override
465     public BindingTreeNodeCodec<?> getSubtreeCodec(final SchemaPath path) {
466         throw new UnsupportedOperationException("Not implemented yet.");
467     }
468 }