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