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