Binding2 - Add yang and tests
[mdsal.git] / binding2 / mdsal-binding2-dom-codec / src / main / java / org / opendaylight / mdsal / binding / javav2 / dom / codec / impl / BindingToNormalizedNodeCodec.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;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Preconditions;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.collect.ImmutableBiMap;
18 import java.lang.reflect.Method;
19 import java.util.AbstractMap.SimpleEntry;
20 import java.util.Collection;
21 import java.util.HashSet;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import java.util.Optional;
25 import java.util.Set;
26 import java.util.concurrent.TimeUnit;
27 import java.util.function.Function;
28 import javax.annotation.Nonnull;
29 import javax.annotation.Nullable;
30 import org.opendaylight.mdsal.binding.javav2.api.DataTreeIdentifier;
31 import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeCodec;
32 import org.opendaylight.mdsal.binding.javav2.dom.codec.api.BindingTreeNodeCodec;
33 import org.opendaylight.mdsal.binding.javav2.dom.codec.api.factory.BindingTreeCodecFactory;
34 import org.opendaylight.mdsal.binding.javav2.dom.codec.api.serializer.BindingNormalizedNodeSerializer;
35 import org.opendaylight.mdsal.binding.javav2.generator.impl.GeneratedClassLoadingStrategy;
36 import org.opendaylight.mdsal.binding.javav2.runtime.context.BindingRuntimeContext;
37 import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections;
38 import org.opendaylight.mdsal.binding.javav2.spec.base.Action;
39 import org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier;
40 import org.opendaylight.mdsal.binding.javav2.spec.base.Notification;
41 import org.opendaylight.mdsal.binding.javav2.spec.base.Rpc;
42 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeArgument;
43 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.common.QNameModule;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
50 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
51 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
52 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
53 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
54 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
57 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
58 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
61 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 /**
66  * Codec for serialize/deserialize Binding and DOM data.
67  */
68 @Beta
69 public final class BindingToNormalizedNodeCodec
70         implements BindingTreeCodecFactory, BindingNormalizedNodeSerializer, SchemaContextListener, AutoCloseable {
71
72     private static final long WAIT_DURATION_SEC = 5;
73     private static final Logger LOG = LoggerFactory.getLogger(BindingToNormalizedNodeCodec.class);
74
75     private final BindingNormalizedNodeCodecRegistry codecRegistry;
76     private final GeneratedClassLoadingStrategy classLoadingStrategy;
77     private final FutureSchema futureSchema;
78     private final LoadingCache<InstanceIdentifier<?>, YangInstanceIdentifier> iiCache = CacheBuilder.newBuilder()
79             .softValues().build(new CacheLoader<InstanceIdentifier<?>, YangInstanceIdentifier>() {
80
81                 @Override
82                 public YangInstanceIdentifier load(@Nonnull final InstanceIdentifier<?> key) throws Exception {
83                     return toYangInstanceIdentifierBlocking(key);
84                 }
85
86             });
87
88     private volatile BindingRuntimeContext runtimeContext;
89
90     /**
91      * Init class without waiting for schema.
92      *
93      * @param classLoadingStrategy
94      *            - class loader
95      * @param codecRegistry
96      *            - codec registry
97      */
98     public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy,
99             final BindingNormalizedNodeCodecRegistry codecRegistry) {
100         this(classLoadingStrategy, codecRegistry, false);
101     }
102
103     /**
104      * Init class with waiting for schema.
105      *
106      * @param classLoadingStrategy
107      *            - class loader
108      * @param codecRegistry
109      *            - codec registry
110      * @param waitForSchema
111      *            - boolean of waiting for schema
112      */
113     public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy,
114             final BindingNormalizedNodeCodecRegistry codecRegistry, final boolean waitForSchema) {
115         this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy, "classLoadingStrategy");
116         this.codecRegistry = Preconditions.checkNotNull(codecRegistry, "codecRegistry");
117         this.futureSchema = waitForSchema ? new FutureSchema(WAIT_DURATION_SEC, TimeUnit.SECONDS) : null;
118     }
119
120     /**
121      * Translates supplied Binding Instance Identifier into NormalizedNode instance identifier with waiting
122      * for schema.
123      *
124      * @param binding
125      *            - Binding Instance Identifier
126      * @return DOM Instance Identifier
127      */
128     public YangInstanceIdentifier toYangInstanceIdentifierBlocking(
129             final InstanceIdentifier<? extends TreeNode> binding) {
130         try {
131             return codecRegistry.toYangInstanceIdentifier(binding);
132         } catch (final MissingSchemaException e) {
133             waitForSchema(decompose(binding), e);
134             return codecRegistry.toYangInstanceIdentifier(binding);
135         }
136     }
137
138     /**
139      * Translates supplied Binding Instance Identifier into NormalizedNode instance identifier.
140      *
141      * @param binding
142      *            - Binding Instance Identifier
143      * @return DOM Instance Identifier
144      * @throws IllegalArgumentException
145      *             If supplied Instance Identifier is not valid.
146      */
147     public YangInstanceIdentifier toNormalized(final InstanceIdentifier<? extends TreeNode> binding) {
148         return codecRegistry.toYangInstanceIdentifier(binding);
149     }
150
151     @Nullable
152     @Override
153     public YangInstanceIdentifier toYangInstanceIdentifier(@Nonnull final InstanceIdentifier<?> binding) {
154         return codecRegistry.toYangInstanceIdentifier(binding);
155     }
156
157     /**
158      * Get cached DOM identifier of Binding identifier.
159      *
160      * @param binding
161      *            - binding identifier
162      * @return DOM identifier
163      */
164     public YangInstanceIdentifier toYangInstanceIdentifierCached(final InstanceIdentifier<?> binding) {
165         return iiCache.getUnchecked(binding);
166     }
167
168     @Nullable
169     @Override
170     public <T extends TreeNode> Entry<YangInstanceIdentifier, NormalizedNode<?, ?>>
171             toNormalizedNode(final InstanceIdentifier<T> path, final T data) {
172         try {
173             return codecRegistry.toNormalizedNode(path, data);
174         } catch (final MissingSchemaException e) {
175             waitForSchema(decompose(path), e);
176             return codecRegistry.toNormalizedNode(path, data);
177         }
178     }
179
180     /**
181      * Converts Binding Map.Entry to DOM Map.Entry.
182      *
183      * <p>
184      * Same as {@link #toNormalizedNode(InstanceIdentifier, TreeNode)}.
185      *
186      * @param binding
187      *            Map Entry with InstanceIdentifier as key and DataObject as value.
188      * @return DOM Map Entry with {@link YangInstanceIdentifier} as key and {@link NormalizedNode} as value.
189      */
190     @SuppressWarnings({ "unchecked", "rawtypes" })
191     @Nullable
192     public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>>
193             toNormalizedNode(final Entry<InstanceIdentifier<? extends TreeNode>, TreeNode> binding) {
194         return toNormalizedNode((InstanceIdentifier) binding.getKey(), binding.getValue());
195     }
196
197     @Nullable
198     @Override
199     public Entry<InstanceIdentifier<?>, TreeNode> fromNormalizedNode(@Nonnull final YangInstanceIdentifier path,
200             final NormalizedNode<?, ?> data) {
201         return codecRegistry.fromNormalizedNode(path, data);
202     }
203
204     @SuppressWarnings({ "rawtypes", "unchecked" })
205     @Nullable
206     @Override
207     public Notification fromNormalizedNodeNotification(@Nonnull final SchemaPath path,
208             @Nonnull final ContainerNode data) {
209         return codecRegistry.fromNormalizedNodeNotification(path, data);
210     }
211
212     @Nullable
213     @Override
214     public TreeNode fromNormalizedNodeOperationData(@Nonnull final SchemaPath path, @Nonnull final ContainerNode data) {
215         return codecRegistry.fromNormalizedNodeOperationData(path, data);
216     }
217
218     @Nullable
219     @Override
220     public InstanceIdentifier<?> fromYangInstanceIdentifier(@Nonnull final YangInstanceIdentifier dom) {
221         return codecRegistry.fromYangInstanceIdentifier(dom);
222     }
223
224     @SuppressWarnings("rawtypes")
225     @Nonnull
226     @Override
227     public ContainerNode toNormalizedNodeNotification(@Nonnull final Notification data) {
228         return codecRegistry.toNormalizedNodeNotification(data);
229     }
230
231     @Nonnull
232     @Override
233     public ContainerNode toNormalizedNodeOperationData(@Nonnull final TreeNode data) {
234         return codecRegistry.toNormalizedNodeOperationData(data);
235     }
236
237     /**
238      * Returns a Binding-Aware instance identifier from normalized instance-identifier if it is possible to
239      * create representation.
240      *
241      * <p>
242      * Returns Optional.empty for cases where target is mixin node except augmentation.
243      *
244      */
245     public Optional<InstanceIdentifier<? extends TreeNode>> toBinding(final YangInstanceIdentifier normalized)
246             throws DeserializationException {
247         try {
248             return Optional.ofNullable(codecRegistry.fromYangInstanceIdentifier(normalized));
249         } catch (final IllegalArgumentException e) {
250             return Optional.empty();
251         }
252     }
253
254     /**
255      * DOM to Binding.
256      *
257      * @param normalized
258      *            - DOM object
259      * @return Binding object
260      * @throws DeserializationException
261      *            If fail to deserialize
262      */
263     @SuppressWarnings("unchecked")
264     public Optional<Entry<InstanceIdentifier<? extends TreeNode>, TreeNode>>
265             toBinding(@Nonnull final Entry<YangInstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
266                     throws DeserializationException {
267         try {
268             final Entry<InstanceIdentifier<? extends TreeNode>, TreeNode> binding =
269                     Entry.class.cast(codecRegistry.fromNormalizedNode(normalized.getKey(), normalized.getValue()));
270             return Optional.ofNullable(binding);
271         } catch (final IllegalArgumentException e) {
272             return Optional.empty();
273         }
274     }
275
276     @Override
277     public void onGlobalContextUpdated(final SchemaContext arg0) {
278         runtimeContext = BindingRuntimeContext.create(classLoadingStrategy, arg0);
279         codecRegistry.onBindingRuntimeContextUpdated(runtimeContext);
280         if (futureSchema != null) {
281             futureSchema.onRuntimeContextUpdated(runtimeContext);
282         }
283     }
284
285     /**
286      * Prepare deserialize function of Binding identifier to DOM.
287      *
288      * @param path
289      *            - Binding identifier
290      * @return DOM function
291      */
292     public <T extends TreeNode> Function<Optional<NormalizedNode<?, ?>>, Optional<T>>
293             deserializeFunction(final InstanceIdentifier<T> path) {
294         return codecRegistry.deserializeFunction(path);
295     }
296
297     /**
298      * Get codec registry.
299      *
300      * @return codec registry
301      */
302     public BindingNormalizedNodeCodecRegistry getCodecRegistry() {
303         return codecRegistry;
304     }
305
306     @Override
307     public void close() {
308         // NOOP Intentionally
309     }
310
311     /**
312      * Get codec factory.
313      *
314      * @return codec factory
315      */
316     public BindingNormalizedNodeCodecRegistry getCodecFactory() {
317         return codecRegistry;
318     }
319
320     /**
321      * Resolve method with path of specific RPC as binding object.
322      *
323      * @param key
324      *            - RPC as binding object
325      * @return map of method with path of specific RPC
326      */
327     @Deprecated
328     public ImmutableBiMap<Method, SchemaPath> getRPCMethodToSchemaPath(final Class<?> key) {
329         final Module module = getModuleBlocking(key);
330         final ImmutableBiMap.Builder<Method, SchemaPath> ret = ImmutableBiMap.builder();
331         try {
332             for (final RpcDefinition rpcDef : module.getRpcs()) {
333                 final Method method = runtimeContext.findOperationMethod(key, rpcDef);
334                 ret.put(method, rpcDef.getPath());
335             }
336         } catch (final NoSuchMethodException e) {
337             throw new IllegalStateException("RPC defined in model does not have representation in generated class.", e);
338         }
339         return ret.build();
340     }
341
342     /**
343      * Get Action schema path.
344      *
345      * @param type
346      *            - Action implementation class type
347      * @return schema path of Action
348      */
349     public SchemaPath getActionPath(final Class<? extends Action<?, ?, ?, ?>> type) {
350         final ActionDefinition schema = runtimeContext.getActionDefinition(type);
351         checkArgument(schema != null, "Failed to find schema for %s", type);
352         return schema.getPath();
353     }
354
355     /**
356      * Get RPC schema path.
357      *
358      * @param type
359      *            - RPC implementation class type
360      * @return schema path of RPC
361      */
362     public SchemaPath getRpcPath(final Class<? extends Rpc<?, ?>> type) {
363         final RpcDefinition schema = runtimeContext.getRpcDefinition(type);
364         checkArgument(schema != null, "Failed to find schema for %s", type);
365         return schema.getPath();
366     }
367
368     public RpcDefinition getRpcDefinition(final Class<? extends Rpc<?, ?>> type) {
369         final RpcDefinition schema = runtimeContext.getRpcDefinition(type);
370         checkArgument(schema != null, "Failed to find schema for %s", type);
371         return schema;
372     }
373
374     /**
375      * Resolve method with definition of specific RPC as binding object.
376      *
377      * @param key
378      *            - RPC as binding object
379      * @return map of method with definition of specific RPC
380      */
381     public ImmutableBiMap<Method, OperationDefinition> getRPCMethodToSchema(final Class<?> key) {
382         final Module module = getModuleBlocking(key);
383         final ImmutableBiMap.Builder<Method, OperationDefinition> ret = ImmutableBiMap.builder();
384         try {
385             for (final RpcDefinition rpcDef : module.getRpcs()) {
386                 final Method method = runtimeContext.findOperationMethod(key, rpcDef);
387                 ret.put(method, rpcDef);
388             }
389         } catch (final NoSuchMethodException e) {
390             throw new IllegalStateException("RPC defined in model does not have representation in generated class.", e);
391         }
392         return ret.build();
393     }
394
395     /**
396      * Resolve method with definition of specific action as binding object.
397      *
398      * @param key
399      *            - action as binding object
400      * @return map of method with definition of specific action
401      */
402     public ImmutableBiMap<Method, OperationDefinition> getActionMethodToSchema(final Class<?> key) {
403         final Module module = getModuleBlocking(key);
404         final ImmutableBiMap.Builder<Method, OperationDefinition> ret = ImmutableBiMap.builder();
405         try {
406             for (final ActionDefinition actionDefinition : runtimeContext.getSchemaContext().getActions()) {
407                 final QName qName = actionDefinition.getQName();
408                 if (qName.getModule().equals(module.getQNameModule())) {
409                     final Method method = runtimeContext.findOperationMethod(key, actionDefinition);
410                     ret.put(method, actionDefinition);
411                 }
412             }
413         } catch (final NoSuchMethodException e) {
414             throw new IllegalStateException("Action defined in model does not have representation in generated class.",
415                     e);
416         }
417         return ret.build();
418     }
419
420     private Module getModuleBlocking(final Class<?> modeledClass) {
421         final QNameModule moduleName = BindingReflections.getQNameModule(modeledClass);
422         BindingRuntimeContext localRuntimeContext = runtimeContext;
423         Module module = localRuntimeContext == null ? null
424                 : localRuntimeContext.getSchemaContext().findModule(moduleName).get();
425         if (module == null && futureSchema != null && futureSchema.waitForSchema(moduleName)) {
426             localRuntimeContext = runtimeContext;
427             Preconditions.checkState(localRuntimeContext != null, "BindingRuntimeContext is not available.");
428             module = localRuntimeContext.getSchemaContext().findModule(moduleName).get();
429         }
430         Preconditions.checkState(module != null, "Schema for %s is not available.", modeledClass);
431         return module;
432     }
433
434     private void waitForSchema(final Collection<Class<?>> binding, final MissingSchemaException exception) {
435         if (futureSchema != null) {
436             LOG.warn("Blocking thread to wait for schema convergence updates for {} {}", futureSchema.getDuration(),
437                     futureSchema.getUnit());
438             if (!futureSchema.waitForSchema(binding)) {
439                 return;
440             }
441         }
442         throw exception;
443     }
444
445     @Override
446     public BindingTreeCodec create(final BindingRuntimeContext context) {
447         return codecRegistry.create(context);
448     }
449
450     @Override
451     public BindingTreeCodec create(final SchemaContext context, final Class<?>... bindingClasses) {
452         return codecRegistry.create(context, bindingClasses);
453     }
454
455     /**
456      * Get subtree codec of DOM identifier.
457      *
458      * @param domIdentifier
459      *            - DOM identifier
460      * @return codec for subtree
461      */
462     @Nonnull
463     public Map.Entry<InstanceIdentifier<?>, BindingTreeNodeCodec<?>>
464             getSubtreeCodec(final YangInstanceIdentifier domIdentifier) {
465
466         final BindingTreeCodec currentCodecTree = codecRegistry.getCodecContext();
467         final InstanceIdentifier<?> bindingPath = codecRegistry.fromYangInstanceIdentifier(domIdentifier);
468         checkArgument(bindingPath != null);
469         /**
470          * If we are able to deserialize YANG instance identifier, getSubtreeCodec must return non-null value.
471          */
472         final BindingTreeNodeCodec<?> codecContext = currentCodecTree.getSubtreeCodec(bindingPath);
473         return new SimpleEntry<>(bindingPath, codecContext);
474     }
475
476     /**
477      * Get specific notification classes as Binding objects.
478      *
479      * @param interested
480      *            - set of specific notifications paths
481      * @return notification as Binding objects according to input set of their DOM paths
482      */
483     @SuppressWarnings({ "unchecked", "rawtypes" })
484     public Set<Class<? extends Notification>> getNotificationClasses(final Set<SchemaPath> interested) {
485         final Set<Class<? extends Notification>> result = new HashSet<>();
486         final Set<NotificationDefinition> knownNotifications = runtimeContext.getSchemaContext().getNotifications();
487         for (final NotificationDefinition notification : knownNotifications) {
488             if (interested.contains(notification.getPath())) {
489                 try {
490                     result.add((Class<? extends Notification>) runtimeContext.getClassForSchema(notification));
491                 } catch (final IllegalStateException e) {
492                     // Ignore
493                     LOG.warn("Class for {} is currently not known.", notification.getPath(), e);
494                 }
495             }
496         }
497         return result;
498     }
499
500     private static Collection<Class<?>> decompose(final InstanceIdentifier<?> path) {
501         final Set<Class<?>> clazzes = new HashSet<>();
502         for (final TreeArgument<?> arg : path.getPathArguments()) {
503             clazzes.add(arg.getType());
504         }
505         return clazzes;
506     }
507
508     /**
509      * Resolve DOM object on specific DOM identifier.
510      *
511      * @param parentPath
512      *            - DOM identifier
513      * @return DOM object
514      */
515     public NormalizedNode<?, ?> instanceIdentifierToNode(final YangInstanceIdentifier parentPath) {
516         return ImmutableNodes.fromInstanceId(runtimeContext.getSchemaContext(), parentPath);
517     }
518
519     /**
520      * Get default DOM object on path for list.
521      *
522      * @param parentMapPath
523      *            - path
524      * @return specific DOM object
525      */
526     public NormalizedNode<?, ?> getDefaultNodeFor(final YangInstanceIdentifier parentMapPath) {
527         final BindingTreeNodeCodec<?> mapCodec = codecRegistry.getCodecContext().getSubtreeCodec(parentMapPath);
528         final Object schema = mapCodec.getSchema();
529         if (schema instanceof ListSchemaNode) {
530             final ListSchemaNode castedSchema = (ListSchemaNode) schema;
531             if (castedSchema.isUserOrdered()) {
532                 return Builders.orderedMapBuilder(castedSchema).build();
533             } else {
534                 return Builders.mapBuilder(castedSchema).build();
535             }
536         }
537         throw new IllegalArgumentException("Path does not point to list schema node");
538     }
539
540     /**
541      * Binding subtree identifiers to DOM subtree identifiers.
542      *
543      * @param subtrees
544      *            - binding subtree
545      * @return DOM subtree
546      */
547     public Collection<DOMDataTreeIdentifier>
548             toDOMDataTreeIdentifiers(final Collection<DataTreeIdentifier<?>> subtrees) {
549         final Set<DOMDataTreeIdentifier> ret = new HashSet<>(subtrees.size());
550
551         for (final DataTreeIdentifier<?> subtree : subtrees) {
552             ret.add(toDOMDataTreeIdentifier(subtree));
553         }
554         return ret;
555     }
556
557     //FIXME: avoid the duplication of the function above.
558     public <P extends TreeNode> Set<DOMDataTreeIdentifier>
559             toDOMDataTreeIdentifiers(final Set<DataTreeIdentifier<P>> subtrees) {
560         final Set<DOMDataTreeIdentifier> ret = new HashSet<>(subtrees.size());
561
562         for (final DataTreeIdentifier<?> subtree : subtrees) {
563             ret.add(toDOMDataTreeIdentifier(subtree));
564         }
565         return ret;
566     }
567
568     /**
569      * Create new DOM data tree identifier from Binding data tree identifier.
570      *
571      * @param path
572      *            - binding data tree identifier
573      * @return DOM data tree identifier
574      */
575     public DOMDataTreeIdentifier toDOMDataTreeIdentifier(final DataTreeIdentifier<?> path) {
576         final YangInstanceIdentifier domPath = toYangInstanceIdentifierBlocking(path.getRootIdentifier());
577         return new DOMDataTreeIdentifier(path.getDatastoreType(), domPath);
578     }
579 }
580