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