2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
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;
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.naming.BindingMapping;
39 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
40 import org.opendaylight.yangtools.util.ClassLoaderUtils;
41 import org.opendaylight.yangtools.yang.binding.Action;
42 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
43 import org.opendaylight.yangtools.yang.binding.DataContainer;
44 import org.opendaylight.yangtools.yang.binding.DataObject;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.opendaylight.yangtools.yang.binding.KeyedListAction;
47 import org.opendaylight.yangtools.yang.binding.Notification;
48 import org.opendaylight.yangtools.yang.binding.RpcInput;
49 import org.opendaylight.yangtools.yang.binding.RpcOutput;
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;
63 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D, BindingRuntimeTypes> {
65 private final LoadingCache<Class<? extends DataObject>, DataContainerCodecContext<?, ?>> childrenByClass =
66 CacheBuilder.newBuilder().build(new CacheLoader<>() {
68 public DataContainerCodecContext<?, ?> load(final Class<? extends DataObject> key) {
69 return createDataTreeChildContext(key);
73 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass =
74 CacheBuilder.newBuilder().build(new CacheLoader<>() {
76 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
77 return createActionContext(key);
81 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
82 CacheBuilder.newBuilder().build(new CacheLoader<>() {
84 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
85 return createChoiceDataContext(key);
89 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
90 .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
92 public NotificationCodecContext<?> load(final Class<?> key) {
93 checkArgument(key.isInterface(), "Supplied class must be interface.");
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",
100 return new NotificationCodecContext<>(key, (NotificationRuntimeType) child, factory());
104 private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder()
105 .build(new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
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;
114 throw new IllegalArgumentException(key + " does not represent an RPC container");
117 final CodecContextFactory factory = factory();
118 final BindingRuntimeContext context = factory.getRuntimeContext();
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 = BindingMapping.getClassName(qname);
126 for (final RpcDefinition potential : module.getRpcs()) {
127 final QName potentialQName = potential.getQName();
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.
133 * FIXME: Rework this to have more precise logic regarding Binding Specification.
135 if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
136 final ContainerLike schema = getRpcDataSchema(potential, qname);
137 checkArgument(schema != null, "Schema for %s does not define input / output.", potentialQName);
139 final ContainerLikeRuntimeType<?, ?> type = lookup.apply(context.getTypes(), potentialQName)
140 .orElseThrow(() -> new IllegalArgumentException("Cannot find runtime type for " + key));
142 return (ContainerNodeCodecContext) DataContainerCodecPrototype.from(key,
143 (ContainerLikeRuntimeType<?, ?>) type, factory).get();
147 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
151 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName =
152 CacheBuilder.newBuilder().build(new CacheLoader<>() {
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,
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()));
169 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
173 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath =
174 CacheBuilder.newBuilder().build(new CacheLoader<>() {
176 public RpcInputCodec<?> load(final Absolute key) {
177 final var rpcName = key.firstNodeIdentifier();
178 final var context = factory().getRuntimeContext();
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);
186 return getRpc(container);
190 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath =
191 CacheBuilder.newBuilder().build(new CacheLoader<>() {
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",
197 return getNotificationImpl(cls);
201 private SchemaRootCodecContext(final DataContainerCodecPrototype<BindingRuntimeTypes> dataPrototype) {
202 super(dataPrototype);
206 * Creates RootNode from supplied CodecContextFactory.
209 * CodecContextFactory
210 * @return A new root node
212 static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
213 return new SchemaRootCodecContext<>(DataContainerCodecPrototype.rootPrototype(factory));
217 public WithStatus getSchema() {
218 return getType().getEffectiveModelContext();
222 @SuppressWarnings("unchecked")
223 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
224 final DataContainerCodecContext<?, ?> result = Notification.class.isAssignableFrom(childClass)
225 ? getNotificationImpl(childClass) : getOrRethrow(childrenByClass, childClass);
226 return (DataContainerCodecContext<C, ?>) result;
230 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
231 final Class<C> childClass) {
232 throw new UnsupportedOperationException("Not supported");
236 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
237 return getOrRethrow(childrenByQName, arg.getNodeType());
241 public D deserialize(final NormalizedNode data) {
242 throw new UnsupportedOperationException("Could not create Binding data representation for root");
245 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
246 return getOrRethrow(actionsByClass, action);
249 NotificationCodecContext<?> getNotification(final Absolute notification) {
250 return getOrRethrow(notificationsByPath, notification);
253 NotificationCodecContext<?> getNotification(final Class<? extends Notification<?>> notification) {
254 return getNotificationImpl(notification);
257 private NotificationCodecContext<?> getNotificationImpl(final Class<?> notification) {
258 return getOrRethrow(notificationsByClass, notification);
261 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
262 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
265 RpcInputCodec<?> getRpc(final Absolute containerPath) {
266 return getOrRethrow(rpcDataByPath, containerPath);
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();
275 throw IncorrectNestingException.create("%s is not a valid data tree child of %s", key, this);
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);
284 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
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);
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(),
299 DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.output(),
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);
309 * Returns RPC input or output schema based on supplied QName.
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.
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.");
326 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
327 final Class<?> choiceClass = findCaseChoice(caseType);
328 checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
329 final CompositeRuntimeType schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
330 checkArgument(schema instanceof ChoiceRuntimeType, "Class %s does not refer to a choice", caseType);
332 final DataContainerCodecContext<?, ChoiceRuntimeType> choice = DataContainerCodecPrototype.from(choiceClass,
333 (ChoiceRuntimeType)schema, factory()).get();
334 verify(choice instanceof ChoiceNodeCodecContext);
335 return (ChoiceNodeCodecContext<?>) choice;
339 protected Object deserializeObject(final NormalizedNode normalizedNode) {
340 throw new UnsupportedOperationException("Unable to deserialize root");
344 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
345 checkArgument(arg == null);
350 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
351 checkArgument(arg == null);
356 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
357 final List<PathArgument> builder) {
358 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
359 if (caseType.isPresent()) {
360 final @NonNull Class<? extends DataObject> type = caseType.orElseThrow();
361 final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(type);
362 choice.addYangPathArgument(arg, builder);
363 final DataContainerCodecContext<?, ?> caze = choice.streamChild(type);
364 caze.addYangPathArgument(arg, builder);
365 return caze.bindingPathArgumentChild(arg, builder);
368 return super.bindingPathArgumentChild(arg, builder);
371 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
372 for (Type type : caseClass.getGenericInterfaces()) {
373 if (type instanceof Class<?> typeClass) {
374 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
375 return typeClass.asSubclass(ChoiceIn.class);
382 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
384 return cache.getUnchecked(key);
385 } catch (final UncheckedExecutionException e) {
386 final Throwable cause = e.getCause();
388 Throwables.throwIfUnchecked(cause);