Binding2 - Implement RpcActionProviderService
[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     /**
369      * Resolve method with definition of specific RPC as binding object.
370      *
371      * @param key
372      *            - RPC as binding object
373      * @return map of method with definition of specific RPC
374      */
375     public ImmutableBiMap<Method, OperationDefinition> getRPCMethodToSchema(final Class<?> key) {
376         final Module module = getModuleBlocking(key);
377         final ImmutableBiMap.Builder<Method, OperationDefinition> ret = ImmutableBiMap.builder();
378         try {
379             for (final RpcDefinition rpcDef : module.getRpcs()) {
380                 final Method method = runtimeContext.findOperationMethod(key, rpcDef);
381                 ret.put(method, rpcDef);
382             }
383         } catch (final NoSuchMethodException e) {
384             throw new IllegalStateException("RPC defined in model does not have representation in generated class.", e);
385         }
386         return ret.build();
387     }
388
389     /**
390      * Resolve method with definition of specific action as binding object.
391      *
392      * @param key
393      *            - action as binding object
394      * @return map of method with definition of specific action
395      */
396     public ImmutableBiMap<Method, OperationDefinition> getActionMethodToSchema(final Class<?> key) {
397         final Module module = getModuleBlocking(key);
398         final ImmutableBiMap.Builder<Method, OperationDefinition> ret = ImmutableBiMap.builder();
399         try {
400             for (final ActionDefinition actionDefinition : runtimeContext.getSchemaContext().getActions()) {
401                 final QName qName = actionDefinition.getQName();
402                 if (qName.getModule().equals(module.getQNameModule())) {
403                     final Method method = runtimeContext.findOperationMethod(key, actionDefinition);
404                     ret.put(method, actionDefinition);
405                 }
406             }
407         } catch (final NoSuchMethodException e) {
408             throw new IllegalStateException("Action defined in model does not have representation in generated class.",
409                     e);
410         }
411         return ret.build();
412     }
413
414     private Module getModuleBlocking(final Class<?> modeledClass) {
415         final QNameModule moduleName = BindingReflections.getQNameModule(modeledClass);
416         BindingRuntimeContext localRuntimeContext = runtimeContext;
417         Module module = localRuntimeContext == null ? null
418                 : localRuntimeContext.getSchemaContext().findModule(moduleName).get();
419         if (module == null && futureSchema != null && futureSchema.waitForSchema(moduleName)) {
420             localRuntimeContext = runtimeContext;
421             Preconditions.checkState(localRuntimeContext != null, "BindingRuntimeContext is not available.");
422             module = localRuntimeContext.getSchemaContext().findModule(moduleName).get();
423         }
424         Preconditions.checkState(module != null, "Schema for %s is not available.", modeledClass);
425         return module;
426     }
427
428     private void waitForSchema(final Collection<Class<?>> binding, final MissingSchemaException exception) {
429         if (futureSchema != null) {
430             LOG.warn("Blocking thread to wait for schema convergence updates for {} {}", futureSchema.getDuration(),
431                     futureSchema.getUnit());
432             if (!futureSchema.waitForSchema(binding)) {
433                 return;
434             }
435         }
436         throw exception;
437     }
438
439     @Override
440     public BindingTreeCodec create(final BindingRuntimeContext context) {
441         return codecRegistry.create(context);
442     }
443
444     @Override
445     public BindingTreeCodec create(final SchemaContext context, final Class<?>... bindingClasses) {
446         return codecRegistry.create(context, bindingClasses);
447     }
448
449     /**
450      * Get subtree codec of DOM identifier.
451      *
452      * @param domIdentifier
453      *            - DOM identifier
454      * @return codec for subtree
455      */
456     @Nonnull
457     public Map.Entry<InstanceIdentifier<?>, BindingTreeNodeCodec<?>>
458             getSubtreeCodec(final YangInstanceIdentifier domIdentifier) {
459
460         final BindingTreeCodec currentCodecTree = codecRegistry.getCodecContext();
461         final InstanceIdentifier<?> bindingPath = codecRegistry.fromYangInstanceIdentifier(domIdentifier);
462         checkArgument(bindingPath != null);
463         /**
464          * If we are able to deserialize YANG instance identifier, getSubtreeCodec must return non-null value.
465          */
466         final BindingTreeNodeCodec<?> codecContext = currentCodecTree.getSubtreeCodec(bindingPath);
467         return new SimpleEntry<>(bindingPath, codecContext);
468     }
469
470     /**
471      * Get specific notification classes as Binding objects.
472      *
473      * @param interested
474      *            - set of specific notifications paths
475      * @return notification as Binding objects according to input set of their DOM paths
476      */
477     @SuppressWarnings({ "unchecked", "rawtypes" })
478     public Set<Class<? extends Notification>> getNotificationClasses(final Set<SchemaPath> interested) {
479         final Set<Class<? extends Notification>> result = new HashSet<>();
480         final Set<NotificationDefinition> knownNotifications = runtimeContext.getSchemaContext().getNotifications();
481         for (final NotificationDefinition notification : knownNotifications) {
482             if (interested.contains(notification.getPath())) {
483                 try {
484                     result.add((Class<? extends Notification>) runtimeContext.getClassForSchema(notification));
485                 } catch (final IllegalStateException e) {
486                     // Ignore
487                     LOG.warn("Class for {} is currently not known.", notification.getPath(), e);
488                 }
489             }
490         }
491         return result;
492     }
493
494     private static Collection<Class<?>> decompose(final InstanceIdentifier<?> path) {
495         final Set<Class<?>> clazzes = new HashSet<>();
496         for (final TreeArgument<?> arg : path.getPathArguments()) {
497             clazzes.add(arg.getType());
498         }
499         return clazzes;
500     }
501
502     /**
503      * Resolve DOM object on specific DOM identifier.
504      *
505      * @param parentPath
506      *            - DOM identifier
507      * @return DOM object
508      */
509     public NormalizedNode<?, ?> instanceIdentifierToNode(final YangInstanceIdentifier parentPath) {
510         return ImmutableNodes.fromInstanceId(runtimeContext.getSchemaContext(), parentPath);
511     }
512
513     /**
514      * Get default DOM object on path for list.
515      *
516      * @param parentMapPath
517      *            - path
518      * @return specific DOM object
519      */
520     public NormalizedNode<?, ?> getDefaultNodeFor(final YangInstanceIdentifier parentMapPath) {
521         final BindingTreeNodeCodec<?> mapCodec = codecRegistry.getCodecContext().getSubtreeCodec(parentMapPath);
522         final Object schema = mapCodec.getSchema();
523         if (schema instanceof ListSchemaNode) {
524             final ListSchemaNode castedSchema = (ListSchemaNode) schema;
525             if (castedSchema.isUserOrdered()) {
526                 return Builders.orderedMapBuilder(castedSchema).build();
527             } else {
528                 return Builders.mapBuilder(castedSchema).build();
529             }
530         }
531         throw new IllegalArgumentException("Path does not point to list schema node");
532     }
533
534     /**
535      * Binding subtree identifiers to DOM subtree identifiers.
536      *
537      * @param subtrees
538      *            - binding subtree
539      * @return DOM subtree
540      */
541     public Collection<DOMDataTreeIdentifier>
542             toDOMDataTreeIdentifiers(final Collection<DataTreeIdentifier<?>> subtrees) {
543         final Set<DOMDataTreeIdentifier> ret = new HashSet<>(subtrees.size());
544
545         for (final DataTreeIdentifier<?> subtree : subtrees) {
546             ret.add(toDOMDataTreeIdentifier(subtree));
547         }
548         return ret;
549     }
550
551     //FIXME: avoid the duplication of the function above.
552     public <P extends TreeNode> Set<DOMDataTreeIdentifier>
553             toDOMDataTreeIdentifiers(final Set<DataTreeIdentifier<P>> subtrees) {
554         final Set<DOMDataTreeIdentifier> ret = new HashSet<>(subtrees.size());
555
556         for (final DataTreeIdentifier<?> subtree : subtrees) {
557             ret.add(toDOMDataTreeIdentifier(subtree));
558         }
559         return ret;
560     }
561
562     /**
563      * Create new DOM data tree identifier from Binding data tree identifier.
564      *
565      * @param path
566      *            - binding data tree identifier
567      * @return DOM data tree identifier
568      */
569     public DOMDataTreeIdentifier toDOMDataTreeIdentifier(final DataTreeIdentifier<?> path) {
570         final YangInstanceIdentifier domPath = toYangInstanceIdentifierBlocking(path.getRootIdentifier());
571         return new DOMDataTreeIdentifier(path.getDatastoreType(), domPath);
572     }
573 }
574