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.DataRoot;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.opendaylight.yangtools.yang.binding.KeyedListAction;
51 import org.opendaylight.yangtools.yang.binding.Notification;
52 import org.opendaylight.yangtools.yang.binding.RpcInput;
53 import org.opendaylight.yangtools.yang.binding.RpcOutput;
54 import org.opendaylight.yangtools.yang.binding.contract.Naming;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.common.QNameModule;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
63 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
64 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
65 import org.opendaylight.yangtools.yang.model.api.Module;
66 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
70 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D, BindingRuntimeTypes>
71 implements BindingDataObjectCodecTreeNode<D> {
73 * Prototype for the root of YANG modeled world. This class only exists because DataContainerCodecContext requires
76 private static final class Prototype extends DataObjectCodecPrototype<BindingRuntimeTypes> {
77 private static final @NonNull NodeIdentifier ROOT_NODEID = NodeIdentifier.create(SchemaContext.NAME);
79 Prototype(final CodecContextFactory factory) {
80 super(DataRoot.class, ROOT_NODEID, factory.getRuntimeContext().getTypes(), factory);
84 DataContainerCodecContext<?, BindingRuntimeTypes> createInstance() {
85 throw new UnsupportedOperationException("Should never be invoked");
89 private final LoadingCache<Class<? extends DataObject>, DataContainerCodecContext<?, ?>> childrenByClass =
90 CacheBuilder.newBuilder().build(new CacheLoader<>() {
92 public DataContainerCodecContext<?, ?> load(final Class<? extends DataObject> key) {
93 return createDataTreeChildContext(key);
97 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass =
98 CacheBuilder.newBuilder().build(new CacheLoader<>() {
100 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
101 return createActionContext(key);
105 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
106 CacheBuilder.newBuilder().build(new CacheLoader<>() {
108 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
109 return createChoiceDataContext(key);
113 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
114 .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
116 public NotificationCodecContext<?> load(final Class<?> key) {
117 checkArgument(key.isInterface(), "Supplied class must be interface.");
119 // TODO: we should be able to work with bindingChild() instead of schemaTreeChild() here
120 final QName qname = BindingReflections.findQName(key);
121 final RuntimeType child = getType().schemaTreeChild(qname);
122 checkArgument(child instanceof NotificationRuntimeType, "Supplied %s is not valid notification",
124 return new NotificationCodecContext<>(key, (NotificationRuntimeType) child, factory());
128 private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder()
129 .build(new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
131 public ContainerNodeCodecContext<?> load(final Class<?> key) {
132 final BiFunction<BindingRuntimeTypes, QName, Optional<? extends ContainerLikeRuntimeType<?, ?>>> lookup;
133 if (RpcInput.class.isAssignableFrom(key)) {
134 lookup = BindingRuntimeTypes::findRpcInput;
135 } else if (RpcOutput.class.isAssignableFrom(key)) {
136 lookup = BindingRuntimeTypes::findRpcOutput;
138 throw new IllegalArgumentException(key + " does not represent an RPC container");
141 final CodecContextFactory factory = factory();
142 final BindingRuntimeContext context = factory.getRuntimeContext();
144 final QName qname = BindingReflections.findQName(key);
145 final QNameModule qnameModule = qname.getModule();
146 final Module module = context.getEffectiveModelContext().findModule(qnameModule)
147 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
148 final String className = Naming.getClassName(qname);
150 for (final RpcDefinition potential : module.getRpcs()) {
151 final QName potentialQName = potential.getQName();
153 * Check if rpc and class represents data from same module and then checks if rpc local name
154 * produces same class name as class name appended with Input/Output based on QName associated
155 * with binding class.
157 * FIXME: Rework this to have more precise logic regarding Binding Specification.
159 if (key.getSimpleName().equals(Naming.getClassName(potentialQName) + className)) {
160 final ContainerLike schema = getRpcDataSchema(potential, qname);
161 checkArgument(schema != null, "Schema for %s does not define input / output.", potentialQName);
163 final ContainerLikeRuntimeType<?, ?> type = lookup.apply(context.getTypes(), potentialQName)
164 .orElseThrow(() -> new IllegalArgumentException("Cannot find runtime type for " + key));
166 return (ContainerNodeCodecContext) DataContainerCodecPrototype.from(key,
167 (ContainerLikeRuntimeType<?, ?>) type, factory).get();
171 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
175 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName =
176 CacheBuilder.newBuilder().build(new CacheLoader<>() {
178 public DataContainerCodecContext<?, ?> load(final QName qname) throws ClassNotFoundException {
179 final var type = getType();
180 final var child = childNonNull(type.schemaTreeChild(qname), qname,
181 "Argument %s is not valid child of %s", qname, type);
182 if (!(child instanceof DataRuntimeType)) {
183 throw new IncorrectNestingException("Argument %s is not valid data tree child of %s", qname, type);
186 // TODO: improve this check?
187 final var childSchema = child.statement();
188 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
189 return streamChild(factory().getRuntimeContext().loadClass(child.javaType()));
192 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
196 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath =
197 CacheBuilder.newBuilder().build(new CacheLoader<>() {
199 public RpcInputCodec<?> load(final Absolute key) {
200 final var rpcName = key.firstNodeIdentifier();
201 final var context = factory().getRuntimeContext();
203 final Class<? extends DataContainer> container = switch (key.lastNodeIdentifier().getLocalName()) {
204 case "input" -> context.getRpcInput(rpcName);
205 case "output" -> context.getRpcOutput(rpcName);
206 default -> throw new IllegalArgumentException("Unhandled path " + key);
209 return getRpc(container);
213 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath =
214 CacheBuilder.newBuilder().build(new CacheLoader<>() {
216 public NotificationCodecContext<?> load(final Absolute key) {
217 final Class<?> cls = factory().getRuntimeContext().getClassForSchema(key);
218 checkArgument(Notification.class.isAssignableFrom(cls), "Path %s does not represent a notification",
220 return getNotificationImpl(cls);
224 SchemaRootCodecContext(final CodecContextFactory factory) {
225 super(new Prototype(factory));
229 public WithStatus getSchema() {
230 return getType().getEffectiveModelContext();
234 @SuppressWarnings("unchecked")
235 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
236 final var result = Notification.class.isAssignableFrom(childClass) ? getNotificationImpl(childClass)
237 : getOrRethrow(childrenByClass, childClass);
238 return (DataContainerCodecContext<C, ?>) result;
242 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
243 final Class<C> childClass) {
244 throw new UnsupportedOperationException("Not supported");
248 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
249 return getOrRethrow(childrenByQName, arg.getNodeType());
253 public D deserialize(final NormalizedNode data) {
254 throw new UnsupportedOperationException("Could not create Binding data representation for root");
258 public NormalizedNode serialize(final D data) {
259 return serializeImpl(data);
262 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
263 return getOrRethrow(actionsByClass, action);
266 NotificationCodecContext<?> getNotification(final Absolute notification) {
267 return getOrRethrow(notificationsByPath, notification);
270 NotificationCodecContext<?> getNotification(final Class<? extends Notification<?>> notification) {
271 return getNotificationImpl(notification);
274 private NotificationCodecContext<?> getNotificationImpl(final Class<?> notification) {
275 return getOrRethrow(notificationsByClass, notification);
278 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
279 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
282 RpcInputCodec<?> getRpc(final Absolute containerPath) {
283 return getOrRethrow(rpcDataByPath, containerPath);
286 DataContainerCodecContext<?, ?> createDataTreeChildContext(final Class<? extends DataObject> key) {
287 final RuntimeType childSchema = childNonNull(getType().bindingChild(JavaTypeName.create(key)), key,
288 "%s is not top-level item.", key);
289 if (childSchema instanceof CompositeRuntimeType composite && childSchema instanceof DataRuntimeType) {
290 return DataContainerCodecPrototype.from(key, composite, factory()).get();
292 throw new IncorrectNestingException("%s is not a valid data tree child of %s", key, this);
295 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
296 if (KeyedListAction.class.isAssignableFrom(action)) {
297 return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
298 } else if (Action.class.isAssignableFrom(action)) {
299 return prepareActionContext(1, 2, 3, action, Action.class);
301 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
304 private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
305 final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
306 final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
307 checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
309 final ParameterizedType paramType = optParamType.orElseThrow();
310 final Type[] args = paramType.getActualTypeArguments();
311 checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
312 final ActionRuntimeType schema = factory().getRuntimeContext().getActionDefinition(action);
313 return new ActionCodecContext(
314 DataContainerCodecPrototype.from(asClass(args[inputOffset], RpcInput.class), schema.input(),
315 factory()).getDataObject(),
316 DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.output(),
317 factory()).getDataObject());
320 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
321 verify(type instanceof Class, "Type %s is not a class", type);
322 return ((Class<?>) type).asSubclass(target);
326 * Returns RPC input or output schema based on supplied QName.
328 * @param rpc RPC Definition
329 * @param qname input or output QName with namespace same as RPC
330 * @return input or output schema. Returns null if RPC does not have input/output specified.
332 private static @Nullable ContainerLike getRpcDataSchema(final @NonNull RpcDefinition rpc,
333 final @NonNull QName qname) {
334 requireNonNull(rpc, "Rpc Schema must not be null");
335 return switch (requireNonNull(qname, "QName must not be null").getLocalName()) {
336 case "input" -> rpc.getInput();
337 case "output" -> rpc.getOutput();
338 default -> throw new IllegalArgumentException(
339 "Supplied qname " + qname + " does not represent rpc input or output.");
343 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
344 final var choiceClass = findCaseChoice(caseType);
345 if (choiceClass == null) {
346 throw new IllegalArgumentException(caseType + " is not a valid case representation");
349 final var runtimeType = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
350 if (!(runtimeType instanceof ChoiceRuntimeType choiceType)) {
351 throw new IllegalArgumentException(caseType + " does not refer to a choice");
354 final var choice = DataContainerCodecPrototype.from(choiceClass, choiceType, factory()).get();
355 verify(choice instanceof ChoiceNodeCodecContext);
356 return (ChoiceNodeCodecContext<?>) choice;
360 protected Object deserializeObject(final NormalizedNode normalizedNode) {
361 throw new UnsupportedOperationException("Unable to deserialize root");
365 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
366 checkArgument(arg == null);
371 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
372 checkArgument(arg == null);
377 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
378 final List<PathArgument> builder) {
379 final var caseType = arg.getCaseType();
380 if (caseType.isPresent()) {
381 final @NonNull Class<? extends DataObject> type = caseType.orElseThrow();
382 final var choice = choicesByClass.getUnchecked(type);
383 choice.addYangPathArgument(arg, builder);
384 final var caze = choice.streamChild(type);
385 caze.addYangPathArgument(arg, builder);
386 return caze.bindingPathArgumentChild(arg, builder);
389 return super.bindingPathArgumentChild(arg, builder);
393 public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
394 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
395 return createCachingCodec(this, cacheSpecifier);
398 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
399 for (var type : caseClass.getGenericInterfaces()) {
400 if (type instanceof Class<?> typeClass && ChoiceIn.class.isAssignableFrom(typeClass)) {
401 return typeClass.asSubclass(ChoiceIn.class);
407 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
409 return cache.getUnchecked(key);
410 } catch (UncheckedExecutionException e) {
411 final var cause = e.getCause();
413 Throwables.throwIfUnchecked(cause);