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.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.CompositeRuntimeType;
37 import org.opendaylight.mdsal.binding.runtime.api.ContainerLikeRuntimeType;
38 import org.opendaylight.mdsal.binding.runtime.api.DataRuntimeType;
39 import org.opendaylight.mdsal.binding.runtime.api.NotificationRuntimeType;
40 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
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.PathArgument;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
59 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
61 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
62 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
65 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
67 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D, BindingRuntimeTypes>
68 implements BindingDataObjectCodecTreeNode<D> {
70 private final LoadingCache<Class<? extends DataObject>, DataContainerCodecContext<?, ?>> childrenByClass =
71 CacheBuilder.newBuilder().build(new CacheLoader<>() {
73 public DataContainerCodecContext<?, ?> load(final Class<? extends DataObject> key) {
74 return createDataTreeChildContext(key);
78 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass =
79 CacheBuilder.newBuilder().build(new CacheLoader<>() {
81 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
82 return createActionContext(key);
86 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
87 CacheBuilder.newBuilder().build(new CacheLoader<>() {
89 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
90 return createChoiceDataContext(key);
94 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
95 .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
97 public NotificationCodecContext<?> load(final Class<?> key) {
98 checkArgument(key.isInterface(), "Supplied class must be interface.");
100 // TODO: we should be able to work with bindingChild() instead of schemaTreeChild() here
101 final QName qname = BindingReflections.findQName(key);
102 final RuntimeType child = getType().schemaTreeChild(qname);
103 checkArgument(child instanceof NotificationRuntimeType, "Supplied %s is not valid notification",
105 return new NotificationCodecContext<>(key, (NotificationRuntimeType) child, factory());
109 private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder()
110 .build(new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
112 public ContainerNodeCodecContext<?> load(final Class<?> key) {
113 final BiFunction<BindingRuntimeTypes, QName, Optional<? extends ContainerLikeRuntimeType<?, ?>>> lookup;
114 if (RpcInput.class.isAssignableFrom(key)) {
115 lookup = BindingRuntimeTypes::findRpcInput;
116 } else if (RpcOutput.class.isAssignableFrom(key)) {
117 lookup = BindingRuntimeTypes::findRpcOutput;
119 throw new IllegalArgumentException(key + " does not represent an RPC container");
122 final CodecContextFactory factory = factory();
123 final BindingRuntimeContext context = factory.getRuntimeContext();
125 final QName qname = BindingReflections.findQName(key);
126 final QNameModule qnameModule = qname.getModule();
127 final Module module = context.getEffectiveModelContext().findModule(qnameModule)
128 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
129 final String className = Naming.getClassName(qname);
131 for (final RpcDefinition potential : module.getRpcs()) {
132 final QName potentialQName = potential.getQName();
134 * Check if rpc and class represents data from same module and then checks if rpc local name
135 * produces same class name as class name appended with Input/Output based on QName associated
136 * with binding class.
138 * FIXME: Rework this to have more precise logic regarding Binding Specification.
140 if (key.getSimpleName().equals(Naming.getClassName(potentialQName) + className)) {
141 final ContainerLike schema = getRpcDataSchema(potential, qname);
142 checkArgument(schema != null, "Schema for %s does not define input / output.", potentialQName);
144 final ContainerLikeRuntimeType<?, ?> type = lookup.apply(context.getTypes(), potentialQName)
145 .orElseThrow(() -> new IllegalArgumentException("Cannot find runtime type for " + key));
147 return (ContainerNodeCodecContext) DataContainerCodecPrototype.from(key,
148 (ContainerLikeRuntimeType<?, ?>) type, factory).get();
152 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
156 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName =
157 CacheBuilder.newBuilder().build(new CacheLoader<>() {
159 public DataContainerCodecContext<?, ?> load(final QName qname) throws ClassNotFoundException {
160 final var type = getType();
161 final var child = childNonNull(type.schemaTreeChild(qname), qname,
162 "Argument %s is not valid child of %s", qname, type);
163 if (!(child instanceof DataRuntimeType)) {
164 throw IncorrectNestingException.create("Argument %s is not valid data tree child of %s", qname,
168 // TODO: improve this check?
169 final var childSchema = child.statement();
170 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
171 return streamChild(factory().getRuntimeContext().loadClass(child.javaType()));
174 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
178 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath =
179 CacheBuilder.newBuilder().build(new CacheLoader<>() {
181 public RpcInputCodec<?> load(final Absolute key) {
182 final var rpcName = key.firstNodeIdentifier();
183 final var context = factory().getRuntimeContext();
185 final Class<? extends DataContainer> container = switch (key.lastNodeIdentifier().getLocalName()) {
186 case "input" -> context.getRpcInput(rpcName);
187 case "output" -> context.getRpcOutput(rpcName);
188 default -> throw new IllegalArgumentException("Unhandled path " + key);
191 return getRpc(container);
195 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath =
196 CacheBuilder.newBuilder().build(new CacheLoader<>() {
198 public NotificationCodecContext<?> load(final Absolute key) {
199 final Class<?> cls = factory().getRuntimeContext().getClassForSchema(key);
200 checkArgument(Notification.class.isAssignableFrom(cls), "Path %s does not represent a notification",
202 return getNotificationImpl(cls);
206 SchemaRootCodecContext(final CodecContextFactory factory) {
207 super(DataContainerCodecPrototype.rootPrototype(factory));
211 public WithStatus getSchema() {
212 return getType().getEffectiveModelContext();
216 @SuppressWarnings("unchecked")
217 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
218 final var result = Notification.class.isAssignableFrom(childClass) ? getNotificationImpl(childClass)
219 : getOrRethrow(childrenByClass, childClass);
220 return (DataContainerCodecContext<C, ?>) result;
224 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
225 final Class<C> childClass) {
226 throw new UnsupportedOperationException("Not supported");
230 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
231 return getOrRethrow(childrenByQName, arg.getNodeType());
235 public D deserialize(final NormalizedNode data) {
236 throw new UnsupportedOperationException("Could not create Binding data representation for root");
240 public NormalizedNode serialize(final D data) {
241 return serializeImpl(data);
244 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
245 return getOrRethrow(actionsByClass, action);
248 NotificationCodecContext<?> getNotification(final Absolute notification) {
249 return getOrRethrow(notificationsByPath, notification);
252 NotificationCodecContext<?> getNotification(final Class<? extends Notification<?>> notification) {
253 return getNotificationImpl(notification);
256 private NotificationCodecContext<?> getNotificationImpl(final Class<?> notification) {
257 return getOrRethrow(notificationsByClass, notification);
260 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
261 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
264 RpcInputCodec<?> getRpc(final Absolute containerPath) {
265 return getOrRethrow(rpcDataByPath, containerPath);
268 DataContainerCodecContext<?, ?> createDataTreeChildContext(final Class<? extends DataObject> key) {
269 final RuntimeType childSchema = childNonNull(getType().bindingChild(JavaTypeName.create(key)), key,
270 "%s is not top-level item.", key);
271 if (childSchema instanceof CompositeRuntimeType composite && childSchema instanceof DataRuntimeType) {
272 return DataContainerCodecPrototype.from(key, composite, factory()).get();
274 throw IncorrectNestingException.create("%s is not a valid data tree child of %s", key, this);
277 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
278 if (KeyedListAction.class.isAssignableFrom(action)) {
279 return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
280 } else if (Action.class.isAssignableFrom(action)) {
281 return prepareActionContext(1, 2, 3, action, Action.class);
283 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
286 private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
287 final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
288 final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
289 checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
291 final ParameterizedType paramType = optParamType.orElseThrow();
292 final Type[] args = paramType.getActualTypeArguments();
293 checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
294 final ActionRuntimeType schema = factory().getRuntimeContext().getActionDefinition(action);
295 return new ActionCodecContext(
296 DataContainerCodecPrototype.from(asClass(args[inputOffset], RpcInput.class), schema.input(),
297 factory()).getDataObject(),
298 DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.output(),
299 factory()).getDataObject());
302 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
303 verify(type instanceof Class, "Type %s is not a class", type);
304 return ((Class<?>) type).asSubclass(target);
308 * Returns RPC input or output schema based on supplied QName.
310 * @param rpc RPC Definition
311 * @param qname input or output QName with namespace same as RPC
312 * @return input or output schema. Returns null if RPC does not have input/output specified.
314 private static @Nullable ContainerLike getRpcDataSchema(final @NonNull RpcDefinition rpc,
315 final @NonNull QName qname) {
316 requireNonNull(rpc, "Rpc Schema must not be null");
317 return switch (requireNonNull(qname, "QName must not be null").getLocalName()) {
318 case "input" -> rpc.getInput();
319 case "output" -> rpc.getOutput();
320 default -> throw new IllegalArgumentException(
321 "Supplied qname " + qname + " does not represent rpc input or output.");
325 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
326 final var choiceClass = findCaseChoice(caseType);
327 if (choiceClass == null) {
328 throw new IllegalArgumentException(caseType + " is not a valid case representation");
331 final var runtimeType = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
332 if (!(runtimeType instanceof ChoiceRuntimeType choiceType)) {
333 throw new IllegalArgumentException(caseType + " does not refer to a choice");
336 final var choice = DataContainerCodecPrototype.from(choiceClass, choiceType, factory()).get();
337 verify(choice instanceof ChoiceNodeCodecContext);
338 return (ChoiceNodeCodecContext<?>) choice;
342 protected Object deserializeObject(final NormalizedNode normalizedNode) {
343 throw new UnsupportedOperationException("Unable to deserialize root");
347 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
348 checkArgument(arg == null);
353 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
354 checkArgument(arg == null);
359 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
360 final List<PathArgument> builder) {
361 final var caseType = arg.getCaseType();
362 if (caseType.isPresent()) {
363 final @NonNull Class<? extends DataObject> type = caseType.orElseThrow();
364 final var choice = choicesByClass.getUnchecked(type);
365 choice.addYangPathArgument(arg, builder);
366 final var caze = choice.streamChild(type);
367 caze.addYangPathArgument(arg, builder);
368 return caze.bindingPathArgumentChild(arg, builder);
371 return super.bindingPathArgumentChild(arg, builder);
375 public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
376 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
377 return createCachingCodec(this, cacheSpecifier);
380 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
381 for (var type : caseClass.getGenericInterfaces()) {
382 if (type instanceof Class<?> typeClass && ChoiceIn.class.isAssignableFrom(typeClass)) {
383 return typeClass.asSubclass(ChoiceIn.class);
389 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
391 return cache.getUnchecked(key);
392 } catch (UncheckedExecutionException e) {
393 final var cause = e.getCause();
395 Throwables.throwIfUnchecked(cause);