29bbebf469e3cc52de1fbefae5a4c862c2bce3e2
[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.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.base.Throwables;
16 import com.google.common.base.Verify;
17 import com.google.common.cache.CacheBuilder;
18 import com.google.common.cache.CacheLoader;
19 import com.google.common.cache.LoadingCache;
20 import com.google.common.util.concurrent.UncheckedExecutionException;
21 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
22 import java.lang.reflect.ParameterizedType;
23 import java.lang.reflect.Type;
24 import java.util.List;
25 import java.util.Optional;
26 import java.util.function.BiFunction;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
30 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
31 import org.opendaylight.mdsal.binding.runtime.api.ActionRuntimeType;
32 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
33 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeTypes;
34 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
35 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
36 import org.opendaylight.mdsal.binding.runtime.api.ContainerLikeRuntimeType;
37 import org.opendaylight.mdsal.binding.runtime.api.DataRuntimeType;
38 import org.opendaylight.mdsal.binding.runtime.api.NotificationRuntimeType;
39 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
40 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
41 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
42 import org.opendaylight.yangtools.util.ClassLoaderUtils;
43 import org.opendaylight.yangtools.yang.binding.Action;
44 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
45 import org.opendaylight.yangtools.yang.binding.DataContainer;
46 import org.opendaylight.yangtools.yang.binding.DataObject;
47 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
48 import org.opendaylight.yangtools.yang.binding.KeyedListAction;
49 import org.opendaylight.yangtools.yang.binding.Notification;
50 import org.opendaylight.yangtools.yang.binding.RpcInput;
51 import org.opendaylight.yangtools.yang.binding.RpcOutput;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.QNameModule;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
56 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
57 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
61 import org.opendaylight.yangtools.yang.model.api.Module;
62 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
63 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
64
65 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D, BindingRuntimeTypes> {
66
67     private final LoadingCache<Class<? extends DataObject>, DataContainerCodecContext<?, ?>> childrenByClass =
68         CacheBuilder.newBuilder().build(new CacheLoader<>() {
69             @Override
70             public DataContainerCodecContext<?, ?> load(final Class<? extends DataObject> key) {
71                 return createDataTreeChildContext(key);
72             }
73         });
74
75     private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass =
76         CacheBuilder.newBuilder().build(new CacheLoader<>() {
77             @Override
78             public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
79                 return createActionContext(key);
80             }
81         });
82
83     private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
84         CacheBuilder.newBuilder().build(new CacheLoader<>() {
85             @Override
86             public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
87                 return createChoiceDataContext(key);
88             }
89         });
90
91     private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
92         .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
93             @Override
94             public NotificationCodecContext<?> load(final Class<?> key) {
95                 checkArgument(key.isInterface(), "Supplied class must be interface.");
96
97                 // TODO: we should be able to work with bindingChild() instead of schemaTreeChild() here
98                 final QName qname = BindingReflections.findQName(key);
99                 final RuntimeType child = getType().schemaTreeChild(qname);
100                 checkArgument(child instanceof NotificationRuntimeType, "Supplied %s is not valid notification",
101                     key);
102                 return new NotificationCodecContext<>(key, (NotificationRuntimeType) child, factory());
103             }
104         });
105
106     private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder()
107         .build(new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
108             @Override
109             public ContainerNodeCodecContext<?> load(final Class<?> key) {
110                 final BiFunction<BindingRuntimeTypes, QName, Optional<? extends ContainerLikeRuntimeType<?, ?>>> lookup;
111                 if (RpcInput.class.isAssignableFrom(key)) {
112                     lookup = BindingRuntimeTypes::findRpcInput;
113                 } else if (RpcOutput.class.isAssignableFrom(key)) {
114                     lookup = BindingRuntimeTypes::findRpcOutput;
115                 } else {
116                     throw new IllegalArgumentException(key + " does not represent an RPC container");
117                 }
118
119                 final CodecContextFactory factory = factory();
120                 final BindingRuntimeContext context = factory.getRuntimeContext();
121
122                 final QName qname = BindingReflections.findQName(key);
123                 final QNameModule qnameModule = qname.getModule();
124                 final Module module = context.getEffectiveModelContext().findModule(qnameModule)
125                     .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
126                 final String className = BindingMapping.getClassName(qname);
127
128                 for (final RpcDefinition potential : module.getRpcs()) {
129                     final QName potentialQName = potential.getQName();
130                     /*
131                      * Check if rpc and class represents data from same module and then checks if rpc local name
132                      * produces same class name as class name appended with Input/Output based on QName associated
133                      * with binding class.
134                      *
135                      * FIXME: Rework this to have more precise logic regarding Binding Specification.
136                      */
137                     if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
138                         final ContainerLike schema = getRpcDataSchema(potential, qname);
139                         checkArgument(schema != null, "Schema for %s does not define input / output.", potentialQName);
140
141                         final ContainerLikeRuntimeType<?, ?> type = lookup.apply(context.getTypes(), potentialQName)
142                             .orElseThrow(() -> new IllegalArgumentException("Cannot find runtime type for " + key));
143
144                         return (ContainerNodeCodecContext) DataContainerCodecPrototype.from(key,
145                             (ContainerLikeRuntimeType<?, ?>) type, factory).get();
146                     }
147                 }
148
149                 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
150             }
151         });
152
153     private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName =
154         CacheBuilder.newBuilder().build(new CacheLoader<>() {
155             @Override
156             public DataContainerCodecContext<?, ?> load(final QName qname) throws ClassNotFoundException {
157                 final var type = getType();
158                 final var child = childNonNull(type.schemaTreeChild(qname), qname,
159                     "Argument %s is not valid child of %s", qname, type);
160                 if (!(child instanceof DataRuntimeType)) {
161                     throw IncorrectNestingException.create("Argument %s is not valid data tree child of %s", qname,
162                         type);
163                 }
164
165                 // TODO: improve this check?
166                 final var childSchema = child.statement();
167                 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
168                     return streamChild(factory().getRuntimeContext().loadClass(child.javaType()));
169                 }
170
171                 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
172             }
173         });
174
175     private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath =
176         CacheBuilder.newBuilder().build(new CacheLoader<>() {
177             @Override
178             public RpcInputCodec<?> load(final Absolute key) {
179                 final var rpcName = key.firstNodeIdentifier();
180                 final var context = factory().getRuntimeContext();
181
182                 final Class<? extends DataContainer> container;
183                 switch (key.lastNodeIdentifier().getLocalName()) {
184                     case "input":
185                         container = context.getRpcInput(rpcName);
186                         break;
187                     case "output":
188                         container = context.getRpcOutput(rpcName);
189                         break;
190                     default:
191                         throw new IllegalArgumentException("Unhandled path " + key);
192                 }
193
194                 return getRpc(container);
195             }
196         });
197
198     private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath =
199         CacheBuilder.newBuilder().build(new CacheLoader<>() {
200             @Override
201             public NotificationCodecContext<?> load(final Absolute key) {
202                 final Class<?> cls = factory().getRuntimeContext().getClassForSchema(key);
203                 checkArgument(Notification.class.isAssignableFrom(cls), "Path %s does not represent a notification",
204                     key);
205                 return getNotificationImpl(cls);
206             }
207         });
208
209     private SchemaRootCodecContext(final DataContainerCodecPrototype<BindingRuntimeTypes> dataPrototype) {
210         super(dataPrototype);
211     }
212
213     /**
214      * Creates RootNode from supplied CodecContextFactory.
215      *
216      * @param factory
217      *            CodecContextFactory
218      * @return A new root node
219      */
220     static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
221         return new SchemaRootCodecContext<>(DataContainerCodecPrototype.rootPrototype(factory));
222     }
223
224     @Override
225     public WithStatus getSchema() {
226         return getType().getEffectiveModelContext();
227     }
228
229     @SuppressWarnings("unchecked")
230     @Override
231     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
232         return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass, childClass);
233     }
234
235     @Override
236     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
237             final Class<C> childClass) {
238         throw new UnsupportedOperationException("Not supported");
239     }
240
241     @Override
242     public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
243         return getOrRethrow(childrenByQName, arg.getNodeType());
244     }
245
246     @Override
247     public D deserialize(final NormalizedNode normalizedNode) {
248         throw new UnsupportedOperationException("Could not create Binding data representation for root");
249     }
250
251     ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
252         return getOrRethrow(actionsByClass, action);
253     }
254
255     NotificationCodecContext<?> getNotification(final Absolute notification) {
256         return getOrRethrow(notificationsByPath, notification);
257     }
258
259     NotificationCodecContext<?> getNotification(final Class<? extends Notification<?>> notification) {
260         return getNotificationImpl(notification);
261     }
262
263     private NotificationCodecContext<?> getNotificationImpl(final Class<?> notification) {
264         return getOrRethrow(notificationsByClass, notification);
265     }
266
267     ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
268         return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
269     }
270
271     RpcInputCodec<?> getRpc(final Absolute containerPath) {
272         return getOrRethrow(rpcDataByPath, containerPath);
273     }
274
275     DataContainerCodecContext<?, ?> createDataTreeChildContext(final Class<? extends DataObject> key) {
276         final RuntimeType childSchema = childNonNull(getType().bindingChild(JavaTypeName.create(key)), key,
277             "%s is not top-level item.", key);
278         if (childSchema instanceof CompositeRuntimeType && childSchema instanceof DataRuntimeType) {
279             return DataContainerCodecPrototype.from(key, (CompositeRuntimeType) childSchema, factory()).get();
280         }
281         throw IncorrectNestingException.create("%s is not a valid data tree child of %s", key, this);
282     }
283
284     ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
285         if (KeyedListAction.class.isAssignableFrom(action)) {
286             return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
287         } else if (Action.class.isAssignableFrom(action)) {
288             return prepareActionContext(1, 2, 3, action, Action.class);
289         }
290         throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
291     }
292
293     private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
294             final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
295         final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
296         checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
297
298         final ParameterizedType paramType = optParamType.get();
299         final Type[] args = paramType.getActualTypeArguments();
300         checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
301         final ActionRuntimeType schema = factory().getRuntimeContext().getActionDefinition(action);
302         return new ActionCodecContext(
303             DataContainerCodecPrototype.from(asClass(args[inputOffset], RpcInput.class), schema.input(),
304                 factory()).get(),
305             DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.output(),
306                 factory()).get());
307     }
308
309     private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
310         verify(type instanceof Class, "Type %s is not a class", type);
311         return ((Class<?>) type).asSubclass(target);
312     }
313
314     /**
315      * Returns RPC input or output schema based on supplied QName.
316      *
317      * @param rpc RPC Definition
318      * @param qname input or output QName with namespace same as RPC
319      * @return input or output schema. Returns null if RPC does not have input/output specified.
320      */
321     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
322         justification = "https://github.com/spotbugs/spotbugs/issues/811")
323     private static @Nullable ContainerLike getRpcDataSchema(final @NonNull RpcDefinition rpc,
324             final @NonNull QName qname) {
325         requireNonNull(rpc, "Rpc Schema must not be null");
326         switch (requireNonNull(qname, "QName must not be null").getLocalName()) {
327             case "input":
328                 return rpc.getInput();
329             case "output":
330                 return rpc.getOutput();
331             default:
332                 throw new IllegalArgumentException("Supplied qname " + qname
333                         + " does not represent rpc input or output.");
334         }
335     }
336
337     ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
338         final Class<?> choiceClass = findCaseChoice(caseType);
339         checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
340         final CompositeRuntimeType schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
341         checkArgument(schema instanceof ChoiceRuntimeType, "Class %s does not refer to a choice", caseType);
342
343         final DataContainerCodecContext<?, ChoiceRuntimeType> choice = DataContainerCodecPrototype.from(choiceClass,
344             (ChoiceRuntimeType)schema, factory()).get();
345         Verify.verify(choice instanceof ChoiceNodeCodecContext);
346         return (ChoiceNodeCodecContext<?>) choice;
347     }
348
349     @Override
350     protected Object deserializeObject(final NormalizedNode normalizedNode) {
351         throw new UnsupportedOperationException("Unable to deserialize root");
352     }
353
354     @Override
355     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
356         checkArgument(arg == null);
357         return null;
358     }
359
360     @Override
361     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
362         checkArgument(arg == null);
363         return null;
364     }
365
366     @Override
367     public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
368             final List<PathArgument> builder) {
369         final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
370         if (caseType.isPresent()) {
371             final @NonNull Class<? extends DataObject> type = caseType.orElseThrow();
372             final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(type);
373             choice.addYangPathArgument(arg, builder);
374             final DataContainerCodecContext<?, ?> caze = choice.streamChild(type);
375             caze.addYangPathArgument(arg, builder);
376             return caze.bindingPathArgumentChild(arg, builder);
377         }
378
379         return super.bindingPathArgumentChild(arg, builder);
380     }
381
382     private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
383         for (Type type : caseClass.getGenericInterfaces()) {
384             if (type instanceof Class) {
385                 final Class<?> typeClass = (Class<?>) type;
386                 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
387                     return typeClass.asSubclass(ChoiceIn.class);
388                 }
389             }
390         }
391
392         return null;
393     }
394
395     private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
396         try {
397             return cache.getUnchecked(key);
398         } catch (final UncheckedExecutionException e) {
399             final Throwable cause = e.getCause();
400             if (cause != null) {
401                 Throwables.throwIfUnchecked(cause);
402             }
403             throw e;
404         }
405     }
406 }