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

©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.