Adjust to yangtools-2.0.0 changes
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / md / sal / binding / impl / BindingToNormalizedNodeCodec.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.md.sal.binding.impl;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.cache.CacheBuilder;
14 import com.google.common.cache.CacheLoader;
15 import com.google.common.cache.LoadingCache;
16 import com.google.common.collect.ImmutableBiMap;
17 import java.lang.reflect.Method;
18 import java.util.AbstractMap.SimpleEntry;
19 import java.util.Collection;
20 import java.util.HashSet;
21 import java.util.Iterator;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import java.util.Set;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
28 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
29 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
31 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeFactory;
32 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeNode;
33 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
34 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
35 import org.opendaylight.mdsal.binding.dom.codec.impl.MissingSchemaException;
36 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
37 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
38 import org.opendaylight.yangtools.yang.binding.BindingMapping;
39 import org.opendaylight.yangtools.yang.binding.DataContainer;
40 import org.opendaylight.yangtools.yang.binding.DataObject;
41 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
42 import org.opendaylight.yangtools.yang.binding.Notification;
43 import org.opendaylight.yangtools.yang.binding.RpcService;
44 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
45 import org.opendaylight.yangtools.yang.common.QNameModule;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
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.model.api.ContainerSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.Module;
53 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
54 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
57 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
58 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
59 import org.opendaylight.yangtools.yang.model.api.meta.StatementSource;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 public class BindingToNormalizedNodeCodec
64         implements BindingCodecTreeFactory, BindingNormalizedNodeSerializer, SchemaContextListener, AutoCloseable {
65
66     private static final long WAIT_DURATION_SEC = 5;
67     private static final Logger LOG = LoggerFactory.getLogger(BindingToNormalizedNodeCodec.class);
68
69     private final BindingNormalizedNodeCodecRegistry codecRegistry;
70
71     private final ClassLoadingStrategy classLoadingStrategy;
72     private final FutureSchema futureSchema;
73     private final LoadingCache<InstanceIdentifier<?>, YangInstanceIdentifier> iiCache = CacheBuilder.newBuilder()
74             .softValues().build(new CacheLoader<InstanceIdentifier<?>, YangInstanceIdentifier>() {
75
76                 @Override
77                 public YangInstanceIdentifier load(final InstanceIdentifier<?> key) throws Exception {
78                     return toYangInstanceIdentifierBlocking(key);
79                 }
80
81             });
82
83     private DataNormalizer legacyToNormalized;
84
85     public BindingToNormalizedNodeCodec(final ClassLoadingStrategy classLoadingStrategy,
86             final BindingNormalizedNodeCodecRegistry codecRegistry) {
87         this(classLoadingStrategy, codecRegistry, false);
88
89     }
90
91     public BindingToNormalizedNodeCodec(final ClassLoadingStrategy classLoadingStrategy,
92             final BindingNormalizedNodeCodecRegistry codecRegistry, final boolean waitForSchema) {
93         this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy, "classLoadingStrategy");
94         this.codecRegistry = Preconditions.checkNotNull(codecRegistry, "codecRegistry");
95         this.futureSchema = new FutureSchema(WAIT_DURATION_SEC, TimeUnit.SECONDS, waitForSchema);
96     }
97
98     public YangInstanceIdentifier
99             toYangInstanceIdentifierBlocking(final InstanceIdentifier<? extends DataObject> binding) {
100         try {
101             return this.codecRegistry.toYangInstanceIdentifier(binding);
102         } catch (final MissingSchemaException e) {
103             waitForSchema(decompose(binding), e);
104             return this.codecRegistry.toYangInstanceIdentifier(binding);
105         }
106     }
107
108     /**
109      * Translates supplied Binding Instance Identifier into NormalizedNode
110      * instance identifier.
111      *
112      * @param binding
113      *            Binding Instance Identifier
114      * @return DOM Instance Identifier
115      * @throws IllegalArgumentException
116      *             If supplied Instance Identifier is not valid.
117      */
118     public YangInstanceIdentifier toNormalized(final InstanceIdentifier<? extends DataObject> binding) {
119         return this.codecRegistry.toYangInstanceIdentifier(binding);
120     }
121
122     @Override
123     public YangInstanceIdentifier toYangInstanceIdentifier(final InstanceIdentifier<?> binding) {
124         return this.codecRegistry.toYangInstanceIdentifier(binding);
125     }
126
127     public YangInstanceIdentifier toYangInstanceIdentifierCached(final InstanceIdentifier<?> binding) {
128         return this.iiCache.getUnchecked(binding);
129     }
130
131     @Override
132     public <T extends DataObject> Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
133             final InstanceIdentifier<T> path, final T data) {
134         return this.codecRegistry.toNormalizedNode(path, data);
135     }
136
137     /**
138      * Converts Binding Map.Entry to DOM Map.Entry
139      *
140      * Same as {@link #toNormalizedNode(InstanceIdentifier, DataObject)}.
141      *
142      * @param binding Map Entry with InstanceIdentifier as key and DataObject as value.
143      * @return DOM Map Entry with {@link YangInstanceIdentifier} as key and {@link NormalizedNode}
144      *         as value.
145      */
146     @SuppressWarnings({ "unchecked", "rawtypes" })
147     public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
148             final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding) {
149         return toNormalizedNode((InstanceIdentifier) binding.getKey(), binding.getValue());
150     }
151
152     @Override
153     public Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode(final YangInstanceIdentifier path,
154             final NormalizedNode<?, ?> data) {
155         return this.codecRegistry.fromNormalizedNode(path, data);
156     }
157
158     @Override
159     public Notification fromNormalizedNodeNotification(final SchemaPath path, final ContainerNode data) {
160         return this.codecRegistry.fromNormalizedNodeNotification(path, data);
161     }
162
163     @Override
164     public DataObject fromNormalizedNodeRpcData(final SchemaPath path, final ContainerNode data) {
165         return this.codecRegistry.fromNormalizedNodeRpcData(path, data);
166     }
167
168     @Override
169     public InstanceIdentifier<?> fromYangInstanceIdentifier(final YangInstanceIdentifier dom) {
170         return this.codecRegistry.fromYangInstanceIdentifier(dom);
171     }
172
173     @Override
174     public ContainerNode toNormalizedNodeNotification(final Notification data) {
175         return this.codecRegistry.toNormalizedNodeNotification(data);
176     }
177
178     @Override
179     public ContainerNode toNormalizedNodeRpcData(final DataContainer data) {
180         return this.codecRegistry.toNormalizedNodeRpcData(data);
181     }
182
183     /**
184      *
185      * Returns a Binding-Aware instance identifier from normalized
186      * instance-identifier if it is possible to create representation.
187      *
188      * Returns Optional.absent for cases where target is mixin node except
189      * augmentation.
190      *
191      */
192     public Optional<InstanceIdentifier<? extends DataObject>> toBinding(final YangInstanceIdentifier normalized)
193             throws DeserializationException {
194         try {
195             return Optional.<InstanceIdentifier<? extends DataObject>>fromNullable(
196                     this.codecRegistry.fromYangInstanceIdentifier(normalized));
197         } catch (final IllegalArgumentException e) {
198             return Optional.absent();
199         }
200     }
201
202     public DataNormalizer getDataNormalizer() {
203         return this.legacyToNormalized;
204     }
205
206     public Optional<Entry<InstanceIdentifier<? extends DataObject>, DataObject>> toBinding(
207             @Nonnull final Entry<YangInstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
208             throws DeserializationException {
209         try {
210             /*
211              * This cast is required, due to generics behaviour in openjdk / oracle javac
212              *
213              * InstanceIdentifier has definition InstanceIdentifier<T extends DataObject>,
214              * this means '?' is always  <? extends DataObject>. Eclipse compiler
215              * is able to determine this relationship and treats
216              * Entry<InstanceIdentifier<?>,DataObject> and Entry<InstanceIdentifier<? extends DataObject,DataObject>
217              * as assignable. However openjdk / oracle javac treats this two types
218              * as incompatible and issues a compile error.
219              *
220              * It is safe to  loose generic information and cast it to other generic signature.
221              *
222              */
223             @SuppressWarnings("unchecked")
224             final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding =
225                     Entry.class.cast(this.codecRegistry.fromNormalizedNode(normalized.getKey(), normalized.getValue()));
226             return Optional.fromNullable(binding);
227         } catch (final IllegalArgumentException e) {
228             return Optional.absent();
229         }
230     }
231
232     @Override
233     public void onGlobalContextUpdated(final SchemaContext schemaContext) {
234         this.legacyToNormalized = new DataNormalizer(schemaContext);
235         final BindingRuntimeContext runtimeContext =
236                 BindingRuntimeContext.create(this.classLoadingStrategy, schemaContext);
237         this.codecRegistry.onBindingRuntimeContextUpdated(runtimeContext);
238         this.futureSchema.onRuntimeContextUpdated(runtimeContext);
239     }
240
241     public <T extends DataObject> Function<Optional<NormalizedNode<?, ?>>, Optional<T>>
242             deserializeFunction(final InstanceIdentifier<T> path) {
243         return this.codecRegistry.deserializeFunction(path);
244     }
245
246     /**
247      * Returns an default object according to YANG schema for supplied path.
248      *
249      * @param path DOM Path
250      * @return Node with defaults set on.
251      */
252     public NormalizedNode<?, ?> getDefaultNodeFor(final YangInstanceIdentifier path) {
253         final Iterator<PathArgument> iterator = path.getPathArguments().iterator();
254         DataNormalizationOperation<?> currentOp = this.legacyToNormalized.getRootOperation();
255         while (iterator.hasNext()) {
256             final PathArgument currentArg = iterator.next();
257             try {
258                 currentOp = currentOp.getChild(currentArg);
259             } catch (final DataNormalizationException e) {
260                 throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", path), e);
261             }
262         }
263         return currentOp.createDefault(path.getLastPathArgument());
264     }
265
266     public BindingNormalizedNodeCodecRegistry getCodecRegistry() {
267         return this.codecRegistry;
268     }
269
270     @Override
271     public void close() {
272         // NOOP Intentionally
273     }
274
275     public BindingNormalizedNodeCodecRegistry getCodecFactory() {
276         return this.codecRegistry;
277     }
278
279     // FIXME: This should be probably part of Binding Runtime context
280     public ImmutableBiMap<Method, SchemaPath> getRpcMethodToSchemaPath(final Class<? extends RpcService> key) {
281         final Module module = getModuleBlocking(key);
282         final ImmutableBiMap.Builder<Method, SchemaPath> ret = ImmutableBiMap.<Method, SchemaPath>builder();
283         try {
284             for (final RpcDefinition rpcDef : module.getRpcs()) {
285                 final Method method = findRpcMethod(key, rpcDef);
286                 ret.put(method, rpcDef.getPath());
287             }
288         } catch (final NoSuchMethodException e) {
289             throw new IllegalStateException("Rpc defined in model does not have representation in generated class.", e);
290         }
291         return ret.build();
292     }
293
294     public ImmutableBiMap<Method, RpcDefinition> getRpcMethodToSchema(final Class<? extends RpcService> key) {
295         final Module module = getModuleBlocking(key);
296         final ImmutableBiMap.Builder<Method, RpcDefinition> ret = ImmutableBiMap.builder();
297         try {
298             for (final RpcDefinition rpcDef : module.getRpcs()) {
299                 final Method method = findRpcMethod(key, rpcDef);
300                 ret.put(method, rpcDef);
301             }
302         } catch (final NoSuchMethodException e) {
303             throw new IllegalStateException("Rpc defined in model does not have representation in generated class.", e);
304         }
305         return ret.build();
306     }
307
308     private Module getModuleBlocking(final Class<?> modeledClass) {
309         final QNameModule moduleName = BindingReflections.getQNameModule(modeledClass);
310         Module module = runtimeContext().getSchemaContext().findModule(moduleName).orElse(null);
311         if (module == null && this.futureSchema.waitForSchema(moduleName)) {
312             module = runtimeContext().getSchemaContext().findModule(moduleName).orElse(null);
313         }
314         Preconditions.checkState(module != null, "Schema for %s is not available.", modeledClass);
315         return module;
316     }
317
318     private void waitForSchema(final Collection<Class<?>> binding, final MissingSchemaException e) {
319         LOG.warn("Blocking thread to wait for schema convergence updates for {} {}", this.futureSchema.getDuration(),
320                 this.futureSchema.getUnit());
321         if (this.futureSchema.waitForSchema(binding)) {
322             return;
323         }
324
325         throw e;
326     }
327
328     private Method findRpcMethod(final Class<? extends RpcService> key, final RpcDefinition rpcDef)
329             throws NoSuchMethodException {
330         final String methodName = BindingMapping.getMethodName(rpcDef.getQName());
331         if (rpcDef.getInput() != null && isExplicitStatement(rpcDef.getInput())) {
332             final Class<?> inputClz = runtimeContext().getClassForSchema(rpcDef.getInput());
333             return key.getMethod(methodName, inputClz);
334         }
335         return key.getMethod(methodName);
336     }
337
338     private static boolean isExplicitStatement(final ContainerSchemaNode node) {
339         return node instanceof EffectiveStatement
340                 && ((EffectiveStatement) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;
341     }
342
343     private BindingRuntimeContext runtimeContext() {
344         return this.futureSchema.runtimeContext();
345     }
346
347     @Override
348     public BindingCodecTree create(final BindingRuntimeContext context) {
349         return this.codecRegistry.create(context);
350     }
351
352     @Override
353     public BindingCodecTree create(final SchemaContext context, final Class<?>... bindingClasses) {
354         return this.codecRegistry.create(context, bindingClasses);
355     }
356
357     @Nonnull
358     public Map.Entry<InstanceIdentifier<?>, BindingCodecTreeNode<?>>
359             getSubtreeCodec(final YangInstanceIdentifier domIdentifier) {
360
361         final BindingCodecTree currentCodecTree = this.codecRegistry.getCodecContext();
362         final InstanceIdentifier<?> bindingPath = this.codecRegistry.fromYangInstanceIdentifier(domIdentifier);
363         Preconditions.checkArgument(bindingPath != null);
364         /**
365          * If we are able to deserialize YANG instance identifier, getSubtreeCodec must
366          * return non-null value.
367          */
368         final BindingCodecTreeNode<?> codecContext = currentCodecTree.getSubtreeCodec(bindingPath);
369         return new SimpleEntry<>(bindingPath, codecContext);
370     }
371
372     @SuppressWarnings("unchecked")
373     public Set<Class<? extends Notification>> getNotificationClasses(final Set<SchemaPath> interested) {
374         final Set<Class<? extends Notification>> result = new HashSet<>();
375         final Set<NotificationDefinition> knownNotifications = runtimeContext().getSchemaContext().getNotifications();
376         for (final NotificationDefinition notification : knownNotifications) {
377             if (interested.contains(notification.getPath())) {
378                 try {
379                     result.add((Class<? extends Notification>) runtimeContext().getClassForSchema(notification));
380                 } catch (final IllegalStateException e) {
381                     // Ignore
382                     LOG.warn("Class for {} is currently not known.", notification.getPath(), e);
383                 }
384             }
385         }
386         return result;
387     }
388
389     private static Collection<Class<?>> decompose(final InstanceIdentifier<?> path) {
390         final Set<Class<?>> clazzes = new HashSet<>();
391         for (final InstanceIdentifier.PathArgument arg : path.getPathArguments()) {
392             clazzes.add(arg.getType());
393         }
394         return clazzes;
395     }
396 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.