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