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.base.Verify;
17 import com.google.common.cache.CacheBuilder;
18 import com.google.common.cache.CacheLoader;
19 import com.google.common.cache.LoadingCache;
20 import com.google.common.util.concurrent.UncheckedExecutionException;
21 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
22 import java.lang.reflect.ParameterizedType;
23 import java.lang.reflect.Type;
24 import java.util.List;
25 import java.util.Optional;
26 import java.util.function.BiFunction;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
30 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
31 import org.opendaylight.mdsal.binding.runtime.api.ActionRuntimeType;
32 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
33 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeTypes;
34 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
35 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
36 import org.opendaylight.mdsal.binding.runtime.api.ContainerLikeRuntimeType;
37 import org.opendaylight.mdsal.binding.runtime.api.DataRuntimeType;
38 import org.opendaylight.mdsal.binding.runtime.api.NotificationRuntimeType;
39 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
40 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
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.ChoiceIn;
45 import org.opendaylight.yangtools.yang.binding.DataContainer;
46 import org.opendaylight.yangtools.yang.binding.DataObject;
47 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
48 import org.opendaylight.yangtools.yang.binding.KeyedListAction;
49 import org.opendaylight.yangtools.yang.binding.Notification;
50 import org.opendaylight.yangtools.yang.binding.RpcInput;
51 import org.opendaylight.yangtools.yang.binding.RpcOutput;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.QNameModule;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
56 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
57 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
61 import org.opendaylight.yangtools.yang.model.api.Module;
62 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
63 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
65 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D, BindingRuntimeTypes> {
67 private final LoadingCache<Class<? extends DataObject>, DataContainerCodecContext<?, ?>> childrenByClass =
68 CacheBuilder.newBuilder().build(new CacheLoader<>() {
70 public DataContainerCodecContext<?, ?> load(final Class<? extends DataObject> key) {
71 return createDataTreeChildContext(key);
75 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass =
76 CacheBuilder.newBuilder().build(new CacheLoader<>() {
78 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
79 return createActionContext(key);
83 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
84 CacheBuilder.newBuilder().build(new CacheLoader<>() {
86 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
87 return createChoiceDataContext(key);
91 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
92 .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
94 public NotificationCodecContext<?> load(final Class<?> key) {
95 checkArgument(key.isInterface(), "Supplied class must be interface.");
97 // TODO: we should be able to work with bindingChild() instead of schemaTreeChild() here
98 final QName qname = BindingReflections.findQName(key);
99 final RuntimeType child = getType().schemaTreeChild(qname);
100 checkArgument(child instanceof NotificationRuntimeType, "Supplied %s is not valid notification",
102 return new NotificationCodecContext<>(key, (NotificationRuntimeType) child, factory());
106 private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder()
107 .build(new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
109 public ContainerNodeCodecContext<?> load(final Class<?> key) {
110 final BiFunction<BindingRuntimeTypes, QName, Optional<? extends ContainerLikeRuntimeType<?, ?>>> lookup;
111 if (RpcInput.class.isAssignableFrom(key)) {
112 lookup = BindingRuntimeTypes::findRpcInput;
113 } else if (RpcOutput.class.isAssignableFrom(key)) {
114 lookup = BindingRuntimeTypes::findRpcOutput;
116 throw new IllegalArgumentException(key + " does not represent an RPC container");
119 final CodecContextFactory factory = factory();
120 final BindingRuntimeContext context = factory.getRuntimeContext();
122 final QName qname = BindingReflections.findQName(key);
123 final QNameModule qnameModule = qname.getModule();
124 final Module module = context.getEffectiveModelContext().findModule(qnameModule)
125 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
126 final String className = BindingMapping.getClassName(qname);
128 for (final RpcDefinition potential : module.getRpcs()) {
129 final QName potentialQName = potential.getQName();
131 * Check if rpc and class represents data from same module and then checks if rpc local name
132 * produces same class name as class name appended with Input/Output based on QName associated
133 * with binding class.
135 * FIXME: Rework this to have more precise logic regarding Binding Specification.
137 if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
138 final ContainerLike schema = getRpcDataSchema(potential, qname);
139 checkArgument(schema != null, "Schema for %s does not define input / output.", potentialQName);
141 final ContainerLikeRuntimeType<?, ?> type = lookup.apply(context.getTypes(), potentialQName)
142 .orElseThrow(() -> new IllegalArgumentException("Cannot find runtime type for " + key));
144 return (ContainerNodeCodecContext) DataContainerCodecPrototype.from(key,
145 (ContainerLikeRuntimeType<?, ?>) type, factory).get();
149 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
153 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName =
154 CacheBuilder.newBuilder().build(new CacheLoader<>() {
156 public DataContainerCodecContext<?, ?> load(final QName qname) throws ClassNotFoundException {
157 final var type = getType();
158 final var child = childNonNull(type.schemaTreeChild(qname), qname,
159 "Argument %s is not valid child of %s", qname, type);
160 if (!(child instanceof DataRuntimeType)) {
161 throw IncorrectNestingException.create("Argument %s is not valid data tree child of %s", qname,
165 // TODO: improve this check?
166 final var childSchema = child.statement();
167 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
168 return streamChild(factory().getRuntimeContext().loadClass(child.javaType()));
171 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
175 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath =
176 CacheBuilder.newBuilder().build(new CacheLoader<>() {
178 public RpcInputCodec<?> load(final Absolute key) {
179 final var rpcName = key.firstNodeIdentifier();
180 final var context = factory().getRuntimeContext();
182 final Class<? extends DataContainer> container;
183 switch (key.lastNodeIdentifier().getLocalName()) {
185 container = context.getRpcInput(rpcName);
188 container = context.getRpcOutput(rpcName);
191 throw new IllegalArgumentException("Unhandled path " + key);
194 return getRpc(container);
198 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath =
199 CacheBuilder.newBuilder().build(new CacheLoader<>() {
201 public NotificationCodecContext<?> load(final Absolute key) {
202 final Class<?> cls = factory().getRuntimeContext().getClassForSchema(key);
203 checkArgument(Notification.class.isAssignableFrom(cls), "Path %s does not represent a notification",
205 return getNotificationImpl(cls);
209 private SchemaRootCodecContext(final DataContainerCodecPrototype<BindingRuntimeTypes> dataPrototype) {
210 super(dataPrototype);
214 * Creates RootNode from supplied CodecContextFactory.
217 * CodecContextFactory
218 * @return A new root node
220 static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
221 return new SchemaRootCodecContext<>(DataContainerCodecPrototype.rootPrototype(factory));
225 public WithStatus getSchema() {
226 return getType().getEffectiveModelContext();
229 @SuppressWarnings("unchecked")
231 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
232 return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass, childClass);
236 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
237 final Class<C> childClass) {
238 throw new UnsupportedOperationException("Not supported");
242 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
243 return getOrRethrow(childrenByQName, arg.getNodeType());
247 public D deserialize(final NormalizedNode normalizedNode) {
248 throw new UnsupportedOperationException("Could not create Binding data representation for root");
251 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
252 return getOrRethrow(actionsByClass, action);
255 NotificationCodecContext<?> getNotification(final Absolute notification) {
256 return getOrRethrow(notificationsByPath, notification);
259 NotificationCodecContext<?> getNotification(final Class<? extends Notification<?>> notification) {
260 return getNotificationImpl(notification);
263 private NotificationCodecContext<?> getNotificationImpl(final Class<?> notification) {
264 return getOrRethrow(notificationsByClass, notification);
267 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
268 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
271 RpcInputCodec<?> getRpc(final Absolute containerPath) {
272 return getOrRethrow(rpcDataByPath, containerPath);
275 DataContainerCodecContext<?, ?> createDataTreeChildContext(final Class<? extends DataObject> key) {
276 final RuntimeType childSchema = childNonNull(getType().bindingChild(JavaTypeName.create(key)), key,
277 "%s is not top-level item.", key);
278 if (childSchema instanceof CompositeRuntimeType && childSchema instanceof DataRuntimeType) {
279 return DataContainerCodecPrototype.from(key, (CompositeRuntimeType) childSchema, factory()).get();
281 throw IncorrectNestingException.create("%s is not a valid data tree child of %s", key, this);
284 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
285 if (KeyedListAction.class.isAssignableFrom(action)) {
286 return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
287 } else if (Action.class.isAssignableFrom(action)) {
288 return prepareActionContext(1, 2, 3, action, Action.class);
290 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
293 private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
294 final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
295 final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
296 checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
298 final ParameterizedType paramType = optParamType.get();
299 final Type[] args = paramType.getActualTypeArguments();
300 checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
301 final ActionRuntimeType schema = factory().getRuntimeContext().getActionDefinition(action);
302 return new ActionCodecContext(
303 DataContainerCodecPrototype.from(asClass(args[inputOffset], RpcInput.class), schema.input(),
305 DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.output(),
309 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
310 verify(type instanceof Class, "Type %s is not a class", type);
311 return ((Class<?>) type).asSubclass(target);
315 * Returns RPC input or output schema based on supplied QName.
317 * @param rpc RPC Definition
318 * @param qname input or output QName with namespace same as RPC
319 * @return input or output schema. Returns null if RPC does not have input/output specified.
321 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
322 justification = "https://github.com/spotbugs/spotbugs/issues/811")
323 private static @Nullable ContainerLike getRpcDataSchema(final @NonNull RpcDefinition rpc,
324 final @NonNull QName qname) {
325 requireNonNull(rpc, "Rpc Schema must not be null");
326 switch (requireNonNull(qname, "QName must not be null").getLocalName()) {
328 return rpc.getInput();
330 return rpc.getOutput();
332 throw new IllegalArgumentException("Supplied qname " + qname
333 + " does not represent rpc input or output.");
337 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
338 final Class<?> choiceClass = findCaseChoice(caseType);
339 checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
340 final CompositeRuntimeType schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
341 checkArgument(schema instanceof ChoiceRuntimeType, "Class %s does not refer to a choice", caseType);
343 final DataContainerCodecContext<?, ChoiceRuntimeType> choice = DataContainerCodecPrototype.from(choiceClass,
344 (ChoiceRuntimeType)schema, factory()).get();
345 Verify.verify(choice instanceof ChoiceNodeCodecContext);
346 return (ChoiceNodeCodecContext<?>) choice;
350 protected Object deserializeObject(final NormalizedNode normalizedNode) {
351 throw new UnsupportedOperationException("Unable to deserialize root");
355 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
356 checkArgument(arg == null);
361 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
362 checkArgument(arg == null);
367 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
368 final List<PathArgument> builder) {
369 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
370 if (caseType.isPresent()) {
371 final @NonNull Class<? extends DataObject> type = caseType.orElseThrow();
372 final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(type);
373 choice.addYangPathArgument(arg, builder);
374 final DataContainerCodecContext<?, ?> caze = choice.streamChild(type);
375 caze.addYangPathArgument(arg, builder);
376 return caze.bindingPathArgumentChild(arg, builder);
379 return super.bindingPathArgumentChild(arg, builder);
382 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
383 for (Type type : caseClass.getGenericInterfaces()) {
384 if (type instanceof Class) {
385 final Class<?> typeClass = (Class<?>) type;
386 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
387 return typeClass.asSubclass(ChoiceIn.class);
395 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
397 return cache.getUnchecked(key);
398 } catch (final UncheckedExecutionException e) {
399 final Throwable cause = e.getCause();
401 Throwables.throwIfUnchecked(cause);