2 * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.javav2.dom.codec.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
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;
23 import java.util.Map.Entry;
24 import java.util.Optional;
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;
66 * Codec for serialize/deserialize Binding and DOM data.
69 public final class BindingToNormalizedNodeCodec
70 implements BindingTreeCodecFactory, BindingNormalizedNodeSerializer, SchemaContextListener, AutoCloseable {
72 private static final long WAIT_DURATION_SEC = 5;
73 private static final Logger LOG = LoggerFactory.getLogger(BindingToNormalizedNodeCodec.class);
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>() {
82 public YangInstanceIdentifier load(@Nonnull final InstanceIdentifier<?> key) throws Exception {
83 return toYangInstanceIdentifierBlocking(key);
88 private volatile BindingRuntimeContext runtimeContext;
91 * Init class without waiting for schema.
93 * @param classLoadingStrategy
95 * @param codecRegistry
98 public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy,
99 final BindingNormalizedNodeCodecRegistry codecRegistry) {
100 this(classLoadingStrategy, codecRegistry, false);
104 * Init class with waiting for schema.
106 * @param classLoadingStrategy
108 * @param codecRegistry
110 * @param waitForSchema
111 * - boolean of waiting for schema
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;
121 * Translates supplied Binding Instance Identifier into NormalizedNode instance identifier with waiting
125 * - Binding Instance Identifier
126 * @return DOM Instance Identifier
128 public YangInstanceIdentifier toYangInstanceIdentifierBlocking(
129 final InstanceIdentifier<? extends TreeNode> binding) {
131 return codecRegistry.toYangInstanceIdentifier(binding);
132 } catch (final MissingSchemaException e) {
133 waitForSchema(decompose(binding), e);
134 return codecRegistry.toYangInstanceIdentifier(binding);
139 * Translates supplied Binding Instance Identifier into NormalizedNode instance identifier.
142 * - Binding Instance Identifier
143 * @return DOM Instance Identifier
144 * @throws IllegalArgumentException
145 * If supplied Instance Identifier is not valid.
147 public YangInstanceIdentifier toNormalized(final InstanceIdentifier<? extends TreeNode> binding) {
148 return codecRegistry.toYangInstanceIdentifier(binding);
153 public YangInstanceIdentifier toYangInstanceIdentifier(@Nonnull final InstanceIdentifier<?> binding) {
154 return codecRegistry.toYangInstanceIdentifier(binding);
158 * Get cached DOM identifier of Binding identifier.
161 * - binding identifier
162 * @return DOM identifier
164 public YangInstanceIdentifier toYangInstanceIdentifierCached(final InstanceIdentifier<?> binding) {
165 return iiCache.getUnchecked(binding);
170 public <T extends TreeNode> Entry<YangInstanceIdentifier, NormalizedNode<?, ?>>
171 toNormalizedNode(final InstanceIdentifier<T> path, final T data) {
173 return codecRegistry.toNormalizedNode(path, data);
174 } catch (final MissingSchemaException e) {
175 waitForSchema(decompose(path), e);
176 return codecRegistry.toNormalizedNode(path, data);
181 * Converts Binding Map.Entry to DOM Map.Entry.
184 * Same as {@link #toNormalizedNode(InstanceIdentifier, TreeNode)}.
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.
190 @SuppressWarnings({ "unchecked", "rawtypes" })
192 public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>>
193 toNormalizedNode(final Entry<InstanceIdentifier<? extends TreeNode>, TreeNode> binding) {
194 return toNormalizedNode((InstanceIdentifier) binding.getKey(), binding.getValue());
199 public Entry<InstanceIdentifier<?>, TreeNode> fromNormalizedNode(@Nonnull final YangInstanceIdentifier path,
200 final NormalizedNode<?, ?> data) {
201 return codecRegistry.fromNormalizedNode(path, data);
204 @SuppressWarnings({ "rawtypes", "unchecked" })
207 public Notification fromNormalizedNodeNotification(@Nonnull final SchemaPath path,
208 @Nonnull final ContainerNode data) {
209 return codecRegistry.fromNormalizedNodeNotification(path, data);
214 public TreeNode fromNormalizedNodeOperationData(@Nonnull final SchemaPath path, @Nonnull final ContainerNode data) {
215 return codecRegistry.fromNormalizedNodeOperationData(path, data);
220 public InstanceIdentifier<?> fromYangInstanceIdentifier(@Nonnull final YangInstanceIdentifier dom) {
221 return codecRegistry.fromYangInstanceIdentifier(dom);
224 @SuppressWarnings("rawtypes")
227 public ContainerNode toNormalizedNodeNotification(@Nonnull final Notification data) {
228 return codecRegistry.toNormalizedNodeNotification(data);
233 public ContainerNode toNormalizedNodeOperationData(@Nonnull final TreeNode data) {
234 return codecRegistry.toNormalizedNodeOperationData(data);
238 * Returns a Binding-Aware instance identifier from normalized instance-identifier if it is possible to
239 * create representation.
242 * Returns Optional.empty for cases where target is mixin node except augmentation.
245 public Optional<InstanceIdentifier<? extends TreeNode>> toBinding(final YangInstanceIdentifier normalized)
246 throws DeserializationException {
248 return Optional.ofNullable(codecRegistry.fromYangInstanceIdentifier(normalized));
249 } catch (final IllegalArgumentException e) {
250 return Optional.empty();
259 * @return Binding object
260 * @throws DeserializationException
261 * If fail to deserialize
263 @SuppressWarnings("unchecked")
264 public Optional<Entry<InstanceIdentifier<? extends TreeNode>, TreeNode>>
265 toBinding(@Nonnull final Entry<YangInstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
266 throws DeserializationException {
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();
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);
286 * Prepare deserialize function of Binding identifier to DOM.
289 * - Binding identifier
290 * @return DOM function
292 public <T extends TreeNode> Function<Optional<NormalizedNode<?, ?>>, Optional<T>>
293 deserializeFunction(final InstanceIdentifier<T> path) {
294 return codecRegistry.deserializeFunction(path);
298 * Get codec registry.
300 * @return codec registry
302 public BindingNormalizedNodeCodecRegistry getCodecRegistry() {
303 return codecRegistry;
307 public void close() {
308 // NOOP Intentionally
314 * @return codec factory
316 public BindingNormalizedNodeCodecRegistry getCodecFactory() {
317 return codecRegistry;
321 * Resolve method with path of specific RPC as binding object.
324 * - RPC as binding object
325 * @return map of method with path of specific RPC
328 public ImmutableBiMap<Method, SchemaPath> getRPCMethodToSchemaPath(final Class<?> key) {
329 final Module module = getModuleBlocking(key);
330 final ImmutableBiMap.Builder<Method, SchemaPath> ret = ImmutableBiMap.builder();
332 for (final RpcDefinition rpcDef : module.getRpcs()) {
333 final Method method = runtimeContext.findOperationMethod(key, rpcDef);
334 ret.put(method, rpcDef.getPath());
336 } catch (final NoSuchMethodException e) {
337 throw new IllegalStateException("RPC defined in model does not have representation in generated class.", e);
343 * Get Action schema path.
346 * - Action implementation class type
347 * @return schema path of Action
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();
356 * Get RPC schema path.
359 * - RPC implementation class type
360 * @return schema path of RPC
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();
369 * Resolve method with definition of specific RPC as binding object.
372 * - RPC as binding object
373 * @return map of method with definition of specific RPC
375 public ImmutableBiMap<Method, OperationDefinition> getRPCMethodToSchema(final Class<?> key) {
376 final Module module = getModuleBlocking(key);
377 final ImmutableBiMap.Builder<Method, OperationDefinition> ret = ImmutableBiMap.builder();
379 for (final RpcDefinition rpcDef : module.getRpcs()) {
380 final Method method = runtimeContext.findOperationMethod(key, rpcDef);
381 ret.put(method, rpcDef);
383 } catch (final NoSuchMethodException e) {
384 throw new IllegalStateException("RPC defined in model does not have representation in generated class.", e);
390 * Resolve method with definition of specific action as binding object.
393 * - action as binding object
394 * @return map of method with definition of specific action
396 public ImmutableBiMap<Method, OperationDefinition> getActionMethodToSchema(final Class<?> key) {
397 final Module module = getModuleBlocking(key);
398 final ImmutableBiMap.Builder<Method, OperationDefinition> ret = ImmutableBiMap.builder();
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);
407 } catch (final NoSuchMethodException e) {
408 throw new IllegalStateException("Action defined in model does not have representation in generated class.",
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();
424 Preconditions.checkState(module != null, "Schema for %s is not available.", modeledClass);
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)) {
440 public BindingTreeCodec create(final BindingRuntimeContext context) {
441 return codecRegistry.create(context);
445 public BindingTreeCodec create(final SchemaContext context, final Class<?>... bindingClasses) {
446 return codecRegistry.create(context, bindingClasses);
450 * Get subtree codec of DOM identifier.
452 * @param domIdentifier
454 * @return codec for subtree
457 public Map.Entry<InstanceIdentifier<?>, BindingTreeNodeCodec<?>>
458 getSubtreeCodec(final YangInstanceIdentifier domIdentifier) {
460 final BindingTreeCodec currentCodecTree = codecRegistry.getCodecContext();
461 final InstanceIdentifier<?> bindingPath = codecRegistry.fromYangInstanceIdentifier(domIdentifier);
462 checkArgument(bindingPath != null);
464 * If we are able to deserialize YANG instance identifier, getSubtreeCodec must return non-null value.
466 final BindingTreeNodeCodec<?> codecContext = currentCodecTree.getSubtreeCodec(bindingPath);
467 return new SimpleEntry<>(bindingPath, codecContext);
471 * Get specific notification classes as Binding objects.
474 * - set of specific notifications paths
475 * @return notification as Binding objects according to input set of their DOM paths
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())) {
484 result.add((Class<? extends Notification>) runtimeContext.getClassForSchema(notification));
485 } catch (final IllegalStateException e) {
487 LOG.warn("Class for {} is currently not known.", notification.getPath(), e);
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());
503 * Resolve DOM object on specific DOM identifier.
509 public NormalizedNode<?, ?> instanceIdentifierToNode(final YangInstanceIdentifier parentPath) {
510 return ImmutableNodes.fromInstanceId(runtimeContext.getSchemaContext(), parentPath);
514 * Get default DOM object on path for list.
516 * @param parentMapPath
518 * @return specific DOM object
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();
528 return Builders.mapBuilder(castedSchema).build();
531 throw new IllegalArgumentException("Path does not point to list schema node");
535 * Binding subtree identifiers to DOM subtree identifiers.
539 * @return DOM subtree
541 public Collection<DOMDataTreeIdentifier>
542 toDOMDataTreeIdentifiers(final Collection<DataTreeIdentifier<?>> subtrees) {
543 final Set<DOMDataTreeIdentifier> ret = new HashSet<>(subtrees.size());
545 for (final DataTreeIdentifier<?> subtree : subtrees) {
546 ret.add(toDOMDataTreeIdentifier(subtree));
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());
556 for (final DataTreeIdentifier<?> subtree : subtrees) {
557 ret.add(toDOMDataTreeIdentifier(subtree));
563 * Create new DOM data tree identifier from Binding data tree identifier.
566 * - binding data tree identifier
567 * @return DOM data tree identifier
569 public DOMDataTreeIdentifier toDOMDataTreeIdentifier(final DataTreeIdentifier<?> path) {
570 final YangInstanceIdentifier domPath = toYangInstanceIdentifierBlocking(path.getRootIdentifier());
571 return new DOMDataTreeIdentifier(path.getDatastoreType(), domPath);