Bug 3135 - Fixed support for InterestListener
[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.collect.ImmutableBiMap;
14 import java.lang.reflect.Method;
15 import java.util.AbstractMap.SimpleEntry;
16 import java.util.HashSet;
17 import java.util.Iterator;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import java.util.Set;
21 import javax.annotation.Nonnull;
22 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
23 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
24 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
25 import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTree;
26 import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeFactory;
27 import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeNode;
28 import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
29 import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
30 import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
31 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
32 import org.opendaylight.yangtools.yang.binding.BindingMapping;
33 import org.opendaylight.yangtools.yang.binding.DataContainer;
34 import org.opendaylight.yangtools.yang.binding.DataObject;
35 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
36 import org.opendaylight.yangtools.yang.binding.Notification;
37 import org.opendaylight.yangtools.yang.binding.RpcService;
38 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
39 import org.opendaylight.yangtools.yang.common.QNameModule;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
42 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
47 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51
52 public class BindingToNormalizedNodeCodec implements BindingCodecTreeFactory, BindingNormalizedNodeSerializer, SchemaContextListener, AutoCloseable {
53
54     private final BindingNormalizedNodeCodecRegistry codecRegistry;
55     private DataNormalizer legacyToNormalized;
56     private final GeneratedClassLoadingStrategy classLoadingStrategy;
57     private BindingRuntimeContext runtimeContext;
58
59     public BindingToNormalizedNodeCodec(final GeneratedClassLoadingStrategy classLoadingStrategy,
60             final BindingNormalizedNodeCodecRegistry codecRegistry) {
61         this.classLoadingStrategy = classLoadingStrategy;
62         this.codecRegistry = codecRegistry;
63
64     }
65
66     public YangInstanceIdentifier toNormalized(final InstanceIdentifier<? extends DataObject> binding) {
67         return codecRegistry.toYangInstanceIdentifier(binding);
68     }
69
70     @Override
71     public YangInstanceIdentifier toYangInstanceIdentifier(final InstanceIdentifier<?> binding) {
72         return codecRegistry.toYangInstanceIdentifier(binding);
73     }
74
75     @Override
76     public <T extends DataObject> Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
77             final InstanceIdentifier<T> path, final T data) {
78         return codecRegistry.toNormalizedNode(path, data);
79     }
80
81     @SuppressWarnings({"unchecked", "rawtypes"})
82     public Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
83             final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding) {
84         return toNormalizedNode((InstanceIdentifier) binding.getKey(),binding.getValue());
85     }
86
87     @Override
88     public Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode(final YangInstanceIdentifier path,
89             final NormalizedNode<?, ?> data) {
90         return codecRegistry.fromNormalizedNode(path, data);
91     }
92
93     @Override
94     public Notification fromNormalizedNodeNotification(final SchemaPath path, final ContainerNode data) {
95         return codecRegistry.fromNormalizedNodeNotification(path, data);
96     }
97
98     @Override
99     public DataObject fromNormalizedNodeRpcData(final SchemaPath path, final ContainerNode data) {
100         return codecRegistry.fromNormalizedNodeRpcData(path, data);
101     }
102
103     @Override
104     public InstanceIdentifier<?> fromYangInstanceIdentifier(final YangInstanceIdentifier dom) {
105         return codecRegistry.fromYangInstanceIdentifier(dom);
106     }
107
108     @Override
109     public ContainerNode toNormalizedNodeNotification(final Notification data) {
110         return codecRegistry.toNormalizedNodeNotification(data);
111     }
112
113     @Override
114     public ContainerNode toNormalizedNodeRpcData(final DataContainer data) {
115         return codecRegistry.toNormalizedNodeRpcData(data);
116     }
117
118     /**
119      *
120      * Returns a Binding-Aware instance identifier from normalized
121      * instance-identifier if it is possible to create representation.
122      *
123      * Returns Optional.absent for cases where target is mixin node except
124      * augmentation.
125      *
126      */
127     public Optional<InstanceIdentifier<? extends DataObject>> toBinding(final YangInstanceIdentifier normalized)
128                     throws DeserializationException {
129         try {
130             return Optional.<InstanceIdentifier<? extends DataObject>>fromNullable(codecRegistry.fromYangInstanceIdentifier(normalized));
131         } catch (final IllegalArgumentException e) {
132             return Optional.absent();
133         }
134     }
135
136     public DataNormalizer getDataNormalizer() {
137         return legacyToNormalized;
138     }
139
140     public Optional<Entry<InstanceIdentifier<? extends DataObject>, DataObject>> toBinding(
141             final @Nonnull Entry<YangInstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
142                     throws DeserializationException {
143         try {
144             /*
145              * This cast is required, due to generics behaviour in openjdk / oracle javac
146              *
147              * InstanceIdentifier has definition InstanceIdentifier<T extends DataObject>,
148              * this means '?' is always  <? extends DataObject>. Eclipse compiler
149              * is able to determine this relationship and treats
150              * Entry<InstanceIdentifier<?>,DataObject> and Entry<InstanceIdentifier<? extends DataObject,DataObject>
151              * as assignable. However openjdk / oracle javac treats this two types
152              * as incompatible and issues a compile error.
153              *
154              * It is safe to  loose generic information and cast it to other generic signature.
155              *
156              */
157             @SuppressWarnings({ "unchecked", "rawtypes" })
158             final Entry<InstanceIdentifier<? extends DataObject>, DataObject> binding = Entry.class.cast(codecRegistry.fromNormalizedNode(normalized.getKey(), normalized.getValue()));
159             return Optional.fromNullable(binding);
160         } catch (final IllegalArgumentException e) {
161             return Optional.absent();
162         }
163     }
164
165     @Override
166     public void onGlobalContextUpdated(final SchemaContext arg0) {
167         legacyToNormalized = new DataNormalizer (arg0);
168         runtimeContext = BindingRuntimeContext.create(classLoadingStrategy, arg0);
169         codecRegistry.onBindingRuntimeContextUpdated(runtimeContext);
170     }
171
172     public <T extends DataObject> Function<Optional<NormalizedNode<?, ?>>, Optional<T>>  deserializeFunction(final InstanceIdentifier<T> path) {
173         return codecRegistry.deserializeFunction(path);
174     }
175
176     /**
177      * Returns an default object according to YANG schema for supplied path.
178      *
179      * @param path DOM Path
180      * @return Node with defaults set on.
181      */
182     public NormalizedNode<?, ?> getDefaultNodeFor(final YangInstanceIdentifier path) {
183         final Iterator<PathArgument> iterator = path.getPathArguments().iterator();
184         DataNormalizationOperation<?> currentOp = legacyToNormalized.getRootOperation();
185         while (iterator.hasNext()) {
186             final PathArgument currentArg = iterator.next();
187             try {
188                 currentOp = currentOp.getChild(currentArg);
189             } catch (final DataNormalizationException e) {
190                 throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", path), e);
191             }
192         }
193         return currentOp.createDefault(path.getLastPathArgument());
194     }
195
196     public BindingNormalizedNodeCodecRegistry getCodecRegistry() {
197         return codecRegistry;
198     }
199
200     @Override
201     public void close() {
202         // NOOP Intentionally
203     }
204
205     public BindingNormalizedNodeCodecRegistry getCodecFactory() {
206         return codecRegistry;
207     }
208
209     // FIXME: This should be probably part of Binding Runtime context
210     public ImmutableBiMap<Method, SchemaPath> getRpcMethodToSchemaPath(final Class<? extends RpcService> key) {
211         final QNameModule moduleName = BindingReflections.getQNameModule(key);
212         final Module module = runtimeContext.getSchemaContext().findModuleByNamespaceAndRevision(moduleName.getNamespace(), moduleName.getRevision());
213         final ImmutableBiMap.Builder<Method, SchemaPath> ret = ImmutableBiMap.<Method, SchemaPath>builder();
214         try {
215             for (final RpcDefinition rpcDef : module.getRpcs()) {
216                 final Method method = findRpcMethod(key, rpcDef);
217                 ret.put(method, rpcDef.getPath());
218             }
219         } catch (final NoSuchMethodException e) {
220             throw new IllegalStateException("Rpc defined in model does not have representation in generated class.", e);
221         }
222         return ret.build();
223     }
224
225     private Method findRpcMethod(final Class<? extends RpcService> key, final RpcDefinition rpcDef) throws NoSuchMethodException {
226         final String methodName = BindingMapping.getMethodName(rpcDef.getQName());
227         if(rpcDef.getInput() != null) {
228             final Class<?> inputClz = runtimeContext.getClassForSchema(rpcDef.getInput());
229             return key.getMethod(methodName, inputClz);
230         }
231         return key.getMethod(methodName);
232     }
233
234     @Override
235     public BindingCodecTree create(final BindingRuntimeContext context) {
236         return codecRegistry.create(context);
237     }
238
239     @Override
240     public BindingCodecTree create(final SchemaContext context, final Class<?>... bindingClasses) {
241         return codecRegistry.create(context, bindingClasses);
242     }
243
244     @Nonnull protected Map.Entry<InstanceIdentifier<?>, BindingCodecTreeNode<?>> getSubtreeCodec(
245             final YangInstanceIdentifier domIdentifier) {
246
247         final BindingCodecTree currentCodecTree = codecRegistry.getCodecContext();
248         final InstanceIdentifier<?> bindingPath = codecRegistry.fromYangInstanceIdentifier(domIdentifier);
249         Preconditions.checkArgument(bindingPath != null);
250         /**
251          * If we are able to deserialize YANG instance identifier, getSubtreeCodec must
252          * return non-null value.
253          */
254         final BindingCodecTreeNode<?> codecContext = currentCodecTree.getSubtreeCodec(bindingPath);
255         return new SimpleEntry<InstanceIdentifier<?>, BindingCodecTreeNode<?>>(bindingPath, codecContext);
256     }
257
258     public Set<Class<? extends Notification>> getNotificationClasses(final Set<SchemaPath> interested) {
259         final Set<Class<? extends Notification>> result = new HashSet<>();
260         final Set<NotificationDefinition> knownNotifications = runtimeContext.getSchemaContext().getNotifications();
261         for (final NotificationDefinition notification : knownNotifications) {
262             if (interested.contains(notification.getPath())) {
263                 try {
264                     result.add((Class<? extends Notification>) runtimeContext.getClassForSchema(notification));
265                 } catch (final IllegalStateException e) {
266                     // Ignore
267                 }
268             }
269         }
270         return result;
271     }
272
273 }

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