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

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