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.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.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.PresenceEffectiveStatement;
69 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
71 final class RootCodecContext<D extends DataObject> extends DataContainerCodecContext<D, BindingRuntimeTypes>
72 implements BindingDataObjectCodecTreeNode<D> {
74 * Prototype for the root of YANG modeled world. This class only exists because DataContainerCodecContext requires
77 static final class Prototype extends DataObjectCodecPrototype<BindingRuntimeTypes> {
78 private static final @NonNull NodeIdentifier ROOT_NODEID = NodeIdentifier.create(SchemaContext.NAME);
80 private Prototype(final CodecContextFactory factory) {
81 super(DataRoot.class, ROOT_NODEID, factory.getRuntimeContext().getTypes(), factory);
85 RootCodecContext<?> createInstance() {
86 throw new UnsupportedOperationException("Should never be invoked");
90 private final LoadingCache<Class<? extends DataObject>, DataContainerCodecContext<?, ?>> childrenByClass =
91 CacheBuilder.newBuilder().build(new CacheLoader<>() {
93 public DataContainerCodecContext<?, ?> load(final Class<? extends DataObject> key) {
94 return createDataTreeChildContext(key);
98 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass =
99 CacheBuilder.newBuilder().build(new CacheLoader<>() {
101 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
102 return createActionContext(key);
106 private final LoadingCache<Class<? extends DataObject>, ChoiceCodecContext<?>> choicesByClass =
107 CacheBuilder.newBuilder().build(new CacheLoader<>() {
109 public ChoiceCodecContext<?> load(final Class<? extends DataObject> key) {
110 return createChoiceDataContext(key);
114 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
115 .build(new CacheLoader<>() {
117 public NotificationCodecContext<?> load(final Class<?> key) {
118 // FIXME: sharpen check to an Notification.class
119 checkArgument(key.isInterface(), "Supplied class must be interface.");
121 // TODO: we should be able to work with bindingChild() instead of schemaTreeChild() here
122 final var qname = BindingReflections.findQName(key);
123 if (type().schemaTreeChild(qname) instanceof NotificationRuntimeType type) {
124 return new NotificationCodecContext<>(key, type, factory());
126 throw new IllegalArgumentException("Supplied " + key + " is not valid notification");
130 private final LoadingCache<Class<?>, ContainerLikeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder()
131 .build(new CacheLoader<>() {
133 public ContainerLikeCodecContext<?> load(final Class<?> key) {
134 final BiFunction<BindingRuntimeTypes, QName, Optional<? extends ContainerLikeRuntimeType<?, ?>>> lookup;
135 if (RpcInput.class.isAssignableFrom(key)) {
136 lookup = BindingRuntimeTypes::findRpcInput;
137 } else if (RpcOutput.class.isAssignableFrom(key)) {
138 lookup = BindingRuntimeTypes::findRpcOutput;
140 throw new IllegalArgumentException(key + " does not represent an RPC container");
143 final CodecContextFactory factory = factory();
144 final BindingRuntimeContext context = factory.getRuntimeContext();
146 final QName qname = BindingReflections.findQName(key);
147 final QNameModule qnameModule = qname.getModule();
148 final Module module = context.getEffectiveModelContext().findModule(qnameModule)
149 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
150 final String className = Naming.getClassName(qname);
152 for (final RpcDefinition potential : module.getRpcs()) {
153 final QName potentialQName = potential.getQName();
155 * Check if rpc and class represents data from same module and then checks if rpc local name
156 * produces same class name as class name appended with Input/Output based on QName associated
157 * with binding class.
159 * FIXME: Rework this to have more precise logic regarding Binding Specification.
161 if (key.getSimpleName().equals(Naming.getClassName(potentialQName) + className)) {
162 final ContainerLike schema = getRpcDataSchema(potential, qname);
163 checkArgument(schema != null, "Schema for %s does not define input / output.", potentialQName);
165 final var type = lookup.apply(context.getTypes(), potentialQName)
166 .orElseThrow(() -> new IllegalArgumentException("Cannot find runtime type for " + key));
168 // FIXME: accurate type
169 return new ContainerLikeCodecContext(key, type, factory);
173 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
177 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName =
178 CacheBuilder.newBuilder().build(new CacheLoader<>() {
180 public DataContainerCodecContext<?, ?> load(final QName qname) throws ClassNotFoundException {
181 final var type = type();
182 final var child = childNonNull(type.schemaTreeChild(qname), qname,
183 "Argument %s is not valid child of %s", qname, type);
184 if (!(child instanceof DataRuntimeType)) {
185 throw new IncorrectNestingException("Argument %s is not valid data tree child of %s", qname, type);
188 // TODO: improve this check?
189 final var childSchema = child.statement();
190 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
191 return getStreamChild(factory().getRuntimeContext().loadClass(child.javaType()));
194 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
198 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath =
199 CacheBuilder.newBuilder().build(new CacheLoader<>() {
201 public RpcInputCodec<?> load(final Absolute key) {
202 final var rpcName = key.firstNodeIdentifier();
203 final var context = factory().getRuntimeContext();
205 final Class<? extends DataContainer> container = switch (key.lastNodeIdentifier().getLocalName()) {
206 case "input" -> context.getRpcInput(rpcName);
207 case "output" -> context.getRpcOutput(rpcName);
208 default -> throw new IllegalArgumentException("Unhandled path " + key);
211 return getRpc(container);
215 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath =
216 CacheBuilder.newBuilder().build(new CacheLoader<>() {
218 public NotificationCodecContext<?> load(final Absolute key) {
219 final var cls = factory().getRuntimeContext().getClassForSchema(key);
221 return getNotificationImpl(cls.asSubclass(Notification.class));
222 } catch (ClassCastException e) {
223 throw new IllegalArgumentException("Path " + key + " does not represent a notification", e);
228 RootCodecContext(final CodecContextFactory factory) {
229 super(new Prototype(factory));
233 public WithStatus getSchema() {
234 return type().getEffectiveModelContext();
238 @SuppressWarnings("unchecked")
239 public <C extends DataObject> DataContainerCodecContext<C, ?> getStreamChild(final Class<C> childClass) {
240 final var result = Notification.class.isAssignableFrom(childClass) ? getNotificationImpl(childClass)
241 : getOrRethrow(childrenByClass, childClass);
242 return (DataContainerCodecContext<C, ?>) result;
246 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
247 // FIXME: implement this
248 throw new UnsupportedOperationException("Not supported");
252 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
253 return getOrRethrow(childrenByQName, arg.getNodeType());
257 public D deserialize(final NormalizedNode data) {
258 throw new UnsupportedOperationException("Could not create Binding data representation for root");
262 public NormalizedNode serialize(final D data) {
263 return serializeImpl(data);
266 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
267 return getOrRethrow(actionsByClass, action);
270 NotificationCodecContext<?> getNotification(final Absolute notification) {
271 return getOrRethrow(notificationsByPath, notification);
274 NotificationCodecContext<?> getNotification(final Class<? extends Notification<?>> notification) {
275 return getNotificationImpl(notification);
278 private NotificationCodecContext<?> getNotificationImpl(final Class<?> notification) {
279 return getOrRethrow(notificationsByClass, notification);
282 ContainerLikeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
283 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
286 RpcInputCodec<?> getRpc(final Absolute containerPath) {
287 return getOrRethrow(rpcDataByPath, containerPath);
290 DataContainerCodecContext<?, ?> createDataTreeChildContext(final Class<? extends DataObject> key) {
291 final var childSchema = childNonNull(type().bindingChild(JavaTypeName.create(key)), key,
292 "%s is not top-level item.", key);
293 if (childSchema instanceof ContainerLikeRuntimeType containerLike) {
294 if (childSchema instanceof ContainerRuntimeType container
295 && container.statement().findFirstEffectiveSubstatement(PresenceEffectiveStatement.class).isEmpty()) {
296 return new StructuralContainerCodecContext<>(key, container, factory());
298 return new ContainerLikeCodecContext<>(key, containerLike, factory());
299 } else if (childSchema instanceof ListRuntimeType list) {
300 return list.keyType() == null ? new ListCodecContext<>(key, list, factory())
301 : MapCodecContext.of(key, list, factory());
302 } else if (childSchema instanceof ChoiceRuntimeType choice) {
303 return new ChoiceCodecContext<>(key, choice, factory());
305 throw new IncorrectNestingException("%s is not a valid data tree child of %s", key, this);
308 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
309 if (KeyedListAction.class.isAssignableFrom(action)) {
310 return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
311 } else if (Action.class.isAssignableFrom(action)) {
312 return prepareActionContext(1, 2, 3, action, Action.class);
314 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
317 private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
318 final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
319 final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
320 checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
322 final ParameterizedType paramType = optParamType.orElseThrow();
323 final Type[] args = paramType.getActualTypeArguments();
324 checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
325 final ActionRuntimeType schema = factory().getRuntimeContext().getActionDefinition(action);
326 return new ActionCodecContext(
327 new ContainerLikeCodecContext(asClass(args[inputOffset], RpcInput.class), schema.input(), factory()),
328 new ContainerLikeCodecContext(asClass(args[outputOffset], RpcOutput.class), schema.output(), factory()));
331 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
332 verify(type instanceof Class, "Type %s is not a class", type);
333 return ((Class<?>) type).asSubclass(target);
337 * Returns RPC input or output schema based on supplied QName.
339 * @param rpc RPC Definition
340 * @param qname input or output QName with namespace same as RPC
341 * @return input or output schema. Returns null if RPC does not have input/output specified.
343 private static @Nullable ContainerLike getRpcDataSchema(final @NonNull RpcDefinition rpc,
344 final @NonNull QName qname) {
345 requireNonNull(rpc, "Rpc Schema must not be null");
346 return switch (requireNonNull(qname, "QName must not be null").getLocalName()) {
347 case "input" -> rpc.getInput();
348 case "output" -> rpc.getOutput();
349 default -> throw new IllegalArgumentException(
350 "Supplied qname " + qname + " does not represent rpc input or output.");
354 ChoiceCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
355 final var choiceClass = findCaseChoice(caseType);
356 if (choiceClass == null) {
357 throw new IllegalArgumentException(caseType + " is not a valid case representation");
360 final var runtimeType = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
361 if (!(runtimeType instanceof ChoiceRuntimeType choiceType)) {
362 throw new IllegalArgumentException(caseType + " does not refer to a choice");
365 // FIXME: accurate type!
366 return new ChoiceCodecContext(choiceClass, choiceType, factory());
370 protected Object deserializeObject(final NormalizedNode normalizedNode) {
371 throw new UnsupportedOperationException("Unable to deserialize root");
375 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
376 checkArgument(arg == null);
381 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
382 checkArgument(arg == null);
387 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
388 final List<PathArgument> builder) {
389 final var caseType = arg.getCaseType();
390 if (caseType.isPresent()) {
391 final @NonNull Class<? extends DataObject> type = caseType.orElseThrow();
392 final var choice = choicesByClass.getUnchecked(type);
393 choice.addYangPathArgument(arg, builder);
394 final var caze = choice.getStreamChild(type);
395 caze.addYangPathArgument(arg, builder);
396 return caze.bindingPathArgumentChild(arg, builder);
399 return super.bindingPathArgumentChild(arg, builder);
403 public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
404 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
405 return createCachingCodec(this, cacheSpecifier);
408 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
409 for (var type : caseClass.getGenericInterfaces()) {
410 if (type instanceof Class<?> typeClass && ChoiceIn.class.isAssignableFrom(typeClass)) {
411 return typeClass.asSubclass(ChoiceIn.class);
417 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
419 return cache.getUnchecked(key);
420 } catch (UncheckedExecutionException e) {
421 final var cause = e.getCause();
423 Throwables.throwIfUnchecked(cause);