Merge branch 'mdsal-trace' from controller
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / SchemaRootCodecContext.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.mdsal.binding.dom.codec.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12
13 import com.google.common.base.Throwables;
14 import com.google.common.base.Verify;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.util.concurrent.UncheckedExecutionException;
19 import java.lang.reflect.Type;
20 import java.util.List;
21 import java.util.Optional;
22 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
23 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
24 import org.opendaylight.yangtools.util.ClassLoaderUtils;
25 import org.opendaylight.yangtools.yang.binding.Action;
26 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
27 import org.opendaylight.yangtools.yang.binding.DataContainer;
28 import org.opendaylight.yangtools.yang.binding.DataObject;
29 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
30 import org.opendaylight.yangtools.yang.binding.Notification;
31 import org.opendaylight.yangtools.yang.binding.RpcInput;
32 import org.opendaylight.yangtools.yang.binding.RpcOutput;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
39 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.Module;
44 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
48 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
49 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
50
51 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D,SchemaContext> {
52
53     private final LoadingCache<Class<?>, DataContainerCodecContext<?,?>> childrenByClass = CacheBuilder.newBuilder()
54             .build(new CacheLoader<Class<?>, DataContainerCodecContext<?,?>>() {
55                 @Override
56                 public DataContainerCodecContext<?,?> load(final Class<?> key) {
57                     return createDataTreeChildContext(key);
58                 }
59             });
60
61     private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass = CacheBuilder
62             .newBuilder().build(new CacheLoader<Class<? extends Action<?, ?, ?>>, ActionCodecContext>() {
63                 @Override
64                 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
65                     return createActionContext(key);
66                 }
67             });
68
69     private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder().build(
70             new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
71                 @Override
72                 public ContainerNodeCodecContext<?> load(final Class<?> key) {
73                     return createRpcDataContext(key);
74                 }
75             });
76
77     private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
78             .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
79                 @Override
80                 public NotificationCodecContext<?> load(final Class<?> key) {
81                     return createNotificationDataContext(key);
82                 }
83             });
84
85     private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
86             CacheBuilder.newBuilder().build(new CacheLoader<Class<? extends DataObject>, ChoiceNodeCodecContext<?>>() {
87                 @Override
88                 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
89                     return createChoiceDataContext(key);
90                 }
91             });
92
93     private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName = CacheBuilder.newBuilder().build(
94             new CacheLoader<QName, DataContainerCodecContext<?,?>>() {
95                 @Override
96                 public DataContainerCodecContext<?,?> load(final QName qname) {
97                     final DataSchemaNode childSchema = getSchema().getDataChildByName(qname);
98                     childNonNull(childSchema, qname,"Argument %s is not valid child of %s", qname,getSchema());
99                     if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
100                         @SuppressWarnings("unchecked")
101                         final Class<? extends DataObject> childCls = (Class<? extends DataObject>)
102                                 factory().getRuntimeContext().getClassForSchema(childSchema);
103                         return streamChild(childCls);
104                     }
105
106                     throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
107                 }
108             });
109
110     private final LoadingCache<SchemaPath, RpcInputCodec<?>> rpcDataByPath = CacheBuilder.newBuilder().build(
111         new CacheLoader<SchemaPath, RpcInputCodec<?>>() {
112             @Override
113             public RpcInputCodec<?> load(final SchemaPath key) {
114                 final ContainerSchemaNode schema = SchemaContextUtil.getRpcDataSchema(getSchema(), key);
115                 @SuppressWarnings("unchecked")
116                 final Class<? extends DataContainer> cls = (Class<? extends DataContainer>)
117                         factory().getRuntimeContext().getClassForSchema(schema);
118                 return getRpc(cls);
119             }
120         });
121
122     private final LoadingCache<SchemaPath, NotificationCodecContext<?>> notificationsByPath = CacheBuilder.newBuilder()
123             .build(new CacheLoader<SchemaPath, NotificationCodecContext<?>>() {
124                 @Override
125                 public NotificationCodecContext<?> load(final SchemaPath key) {
126                     final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(), key);
127                     @SuppressWarnings("unchecked")
128                     final Class<? extends Notification> clz = (Class<? extends Notification>)
129                             factory().getRuntimeContext().getClassForSchema(schema);
130                     return getNotification(clz);
131                 }
132             });
133
134     private SchemaRootCodecContext(final DataContainerCodecPrototype<SchemaContext> dataPrototype) {
135         super(dataPrototype);
136     }
137
138     /**
139      * Creates RootNode from supplied CodecContextFactory.
140      *
141      * @param factory
142      *            CodecContextFactory
143      * @return A new root node
144      */
145     static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
146         final DataContainerCodecPrototype<SchemaContext> prototype = DataContainerCodecPrototype.rootPrototype(factory);
147         return new SchemaRootCodecContext<>(prototype);
148     }
149
150
151     @SuppressWarnings("unchecked")
152     @Override
153     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
154         /* FIXME: This is still not solved for RPCs
155          * TODO: Probably performance wise RPC, Data and Notification loading cache
156          *       should be merge for performance resons. Needs microbenchmark to
157          *       determine which is faster (keeping them separate or in same cache).
158          */
159         if (Notification.class.isAssignableFrom(childClass)) {
160             return (DataContainerCodecContext<C, ?>) getNotification((Class<? extends Notification>)childClass);
161         }
162         return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass,childClass);
163     }
164
165     @Override
166     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
167             final Class<C> childClass) {
168         throw new UnsupportedOperationException("Not supported");
169     }
170
171     @Override
172     public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
173         return getOrRethrow(childrenByQName, arg.getNodeType());
174     }
175
176     @Override
177     public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
178         throw new UnsupportedOperationException("Could not create Binding data representation for root");
179     }
180
181     ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
182         return getOrRethrow(actionsByClass, action);
183     }
184
185     NotificationCodecContext<?> getNotification(final Class<? extends Notification> notification) {
186         return getOrRethrow(notificationsByClass, notification);
187     }
188
189     NotificationCodecContext<?> getNotification(final SchemaPath notification) {
190         return getOrRethrow(notificationsByPath, notification);
191     }
192
193     ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
194         return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
195     }
196
197     RpcInputCodec<?> getRpc(final SchemaPath notification) {
198         return getOrRethrow(rpcDataByPath, notification);
199     }
200
201     DataContainerCodecContext<?,?> createDataTreeChildContext(final Class<?> key) {
202         final QName qname = BindingReflections.findQName(key);
203         final DataSchemaNode childSchema = childNonNull(getSchema().getDataChildByName(qname), key,
204             "%s is not top-level item.", key);
205         return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
206     }
207
208     ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
209         final Type[] args = ClassLoaderUtils.findParameterizedType(action, Action.class).getActualTypeArguments();
210         checkArgument(args.length == 3, "Unexpected (%s) Action generatic arguments", args.length);
211
212         final ActionDefinition schema = factory().getRuntimeContext().getActionDefinition(action);
213         return new ActionCodecContext(
214             DataContainerCodecPrototype.from(asClass(args[1], RpcInput.class), schema.getInput(), factory()).get(),
215             DataContainerCodecPrototype.from(asClass(args[2], RpcOutput.class), schema.getOutput(), factory()).get());
216     }
217
218     private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
219         verify(type instanceof Class, "Type %s is not a class", type);
220         return ((Class<?>) type).asSubclass(target);
221     }
222
223     ContainerNodeCodecContext<?> createRpcDataContext(final Class<?> key) {
224         checkArgument(DataContainer.class.isAssignableFrom(key));
225         final QName qname = BindingReflections.findQName(key);
226         final QNameModule qnameModule = qname.getModule();
227         final Module module = getSchema().findModule(qnameModule)
228                 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
229         final String className = BindingMapping.getClassName(qname);
230
231         RpcDefinition rpc = null;
232         for (final RpcDefinition potential : module.getRpcs()) {
233             final QName potentialQName = potential.getQName();
234             /*
235              * Check if rpc and class represents data from same module and then
236              * checks if rpc local name produces same class name as class name
237              * appended with Input/Output based on QName associated with bidning
238              * class.
239              *
240              * FIXME: Rework this to have more precise logic regarding Binding
241              * Specification.
242              */
243             if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
244                 rpc = potential;
245                 break;
246             }
247         }
248         checkArgument(rpc != null, "Supplied class %s is not valid RPC class.", key);
249         final ContainerSchemaNode schema = SchemaNodeUtils.getRpcDataSchema(rpc, qname);
250         checkArgument(schema != null, "Schema for %s does not define input / output.", rpc.getQName());
251         return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
252     }
253
254     NotificationCodecContext<?> createNotificationDataContext(final Class<?> notificationType) {
255         checkArgument(Notification.class.isAssignableFrom(notificationType));
256         checkArgument(notificationType.isInterface(), "Supplied class must be interface.");
257         final QName qname = BindingReflections.findQName(notificationType);
258         /**
259          *  FIXME: After Lithium cleanup of yang-model-api, use direct call on schema context
260          *  to retrieve notification via index.
261          */
262         final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(),
263                 SchemaPath.create(true, qname));
264         checkArgument(schema != null, "Supplied %s is not valid notification", notificationType);
265
266         return new NotificationCodecContext<>(notificationType, schema, factory());
267     }
268
269     ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
270         final Class<?> choiceClass = findCaseChoice(caseType);
271         checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
272         final DataSchemaNode schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
273         checkArgument(schema instanceof ChoiceSchemaNode, "Class %s does not refer to a choice", caseType);
274
275         final DataContainerCodecContext<?, ChoiceSchemaNode> choice = DataContainerCodecPrototype.from(choiceClass,
276             (ChoiceSchemaNode)schema, factory()).get();
277         Verify.verify(choice instanceof ChoiceNodeCodecContext);
278         return (ChoiceNodeCodecContext<?>) choice;
279     }
280
281     @Override
282     protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
283         throw new UnsupportedOperationException("Unable to deserialize root");
284     }
285
286     @Override
287     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
288         checkArgument(arg == null);
289         return null;
290     }
291
292     @Override
293     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
294         checkArgument(arg == null);
295         return null;
296     }
297
298     @Override
299     public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
300             final List<PathArgument> builder) {
301         final java.util.Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
302         if (caseType.isPresent()) {
303             final Class<? extends DataObject> type = caseType.get();
304             final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(type);
305             choice.addYangPathArgument(arg, builder);
306             final DataContainerCodecContext<?, ?> caze = choice.streamChild(type);
307             caze.addYangPathArgument(arg, builder);
308             return caze.bindingPathArgumentChild(arg, builder);
309         }
310
311         return super.bindingPathArgumentChild(arg, builder);
312     }
313
314     private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
315         for (Type type : caseClass.getGenericInterfaces()) {
316             if (type instanceof Class) {
317                 final Class<?> typeClass = (Class<?>) type;
318                 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
319                     return typeClass.asSubclass(ChoiceIn.class);
320                 }
321             }
322         }
323
324         return null;
325     }
326
327     private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
328         try {
329             return cache.getUnchecked(key);
330         } catch (final UncheckedExecutionException e) {
331             final Throwable cause = e.getCause();
332             if (cause != null) {
333                 Throwables.throwIfUnchecked(cause);
334             }
335             throw e;
336         }
337     }
338 }