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