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 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.IncorrectNestingException;
29 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
30 import org.opendaylight.mdsal.binding.runtime.api.ActionRuntimeType;
31 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
32 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeTypes;
33 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
34 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
35 import org.opendaylight.mdsal.binding.runtime.api.ContainerLikeRuntimeType;
36 import org.opendaylight.mdsal.binding.runtime.api.DataRuntimeType;
37 import org.opendaylight.mdsal.binding.runtime.api.NotificationRuntimeType;
38 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
39 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
40 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
41 import org.opendaylight.yangtools.util.ClassLoaderUtils;
42 import org.opendaylight.yangtools.yang.binding.Action;
43 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
44 import org.opendaylight.yangtools.yang.binding.DataContainer;
45 import org.opendaylight.yangtools.yang.binding.DataObject;
46 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
47 import org.opendaylight.yangtools.yang.binding.KeyedListAction;
48 import org.opendaylight.yangtools.yang.binding.Notification;
49 import org.opendaylight.yangtools.yang.binding.RpcInput;
50 import org.opendaylight.yangtools.yang.binding.RpcOutput;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.common.QNameModule;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
58 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
62 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
64 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D, BindingRuntimeTypes> {
66 private final LoadingCache<Class<? extends DataObject>, DataContainerCodecContext<?, ?>> childrenByClass =
67 CacheBuilder.newBuilder().build(new CacheLoader<>() {
69 public DataContainerCodecContext<?, ?> load(final Class<? extends DataObject> key) {
70 return createDataTreeChildContext(key);
74 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass =
75 CacheBuilder.newBuilder().build(new CacheLoader<>() {
77 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
78 return createActionContext(key);
82 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
83 CacheBuilder.newBuilder().build(new CacheLoader<>() {
85 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
86 return createChoiceDataContext(key);
90 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
91 .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
93 public NotificationCodecContext<?> load(final Class<?> key) {
94 checkArgument(key.isInterface(), "Supplied class must be interface.");
96 // TODO: we should be able to work with bindingChild() instead of schemaTreeChild() here
97 final QName qname = BindingReflections.findQName(key);
98 final RuntimeType child = getType().schemaTreeChild(qname);
99 checkArgument(child instanceof NotificationRuntimeType, "Supplied %s is not valid notification",
101 return new NotificationCodecContext<>(key, (NotificationRuntimeType) child, factory());
105 private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder()
106 .build(new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
108 public ContainerNodeCodecContext<?> load(final Class<?> key) {
109 final BiFunction<BindingRuntimeTypes, QName, Optional<? extends ContainerLikeRuntimeType<?, ?>>> lookup;
110 if (RpcInput.class.isAssignableFrom(key)) {
111 lookup = BindingRuntimeTypes::findRpcInput;
112 } else if (RpcOutput.class.isAssignableFrom(key)) {
113 lookup = BindingRuntimeTypes::findRpcOutput;
115 throw new IllegalArgumentException(key + " does not represent an RPC container");
118 final CodecContextFactory factory = factory();
119 final BindingRuntimeContext context = factory.getRuntimeContext();
121 final QName qname = BindingReflections.findQName(key);
122 final QNameModule qnameModule = qname.getModule();
123 final Module module = context.getEffectiveModelContext().findModule(qnameModule)
124 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
125 final String className = BindingMapping.getClassName(qname);
127 for (final RpcDefinition potential : module.getRpcs()) {
128 final QName potentialQName = potential.getQName();
130 * Check if rpc and class represents data from same module and then checks if rpc local name
131 * produces same class name as class name appended with Input/Output based on QName associated
132 * with binding class.
134 * FIXME: Rework this to have more precise logic regarding Binding Specification.
136 if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
137 final ContainerLike schema = getRpcDataSchema(potential, qname);
138 checkArgument(schema != null, "Schema for %s does not define input / output.", potentialQName);
140 final ContainerLikeRuntimeType<?, ?> type = lookup.apply(context.getTypes(), potentialQName)
141 .orElseThrow(() -> new IllegalArgumentException("Cannot find runtime type for " + key));
143 return (ContainerNodeCodecContext) DataContainerCodecPrototype.from(key,
144 (ContainerLikeRuntimeType<?, ?>) type, factory).get();
148 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
152 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName =
153 CacheBuilder.newBuilder().build(new CacheLoader<>() {
155 public DataContainerCodecContext<?, ?> load(final QName qname) throws ClassNotFoundException {
156 final var type = getType();
157 final var child = childNonNull(type.schemaTreeChild(qname), qname,
158 "Argument %s is not valid child of %s", qname, type);
159 if (!(child instanceof DataRuntimeType)) {
160 throw IncorrectNestingException.create("Argument %s is not valid data tree child of %s", qname,
164 // TODO: improve this check?
165 final var childSchema = child.statement();
166 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
167 return streamChild(factory().getRuntimeContext().loadClass(child.javaType()));
170 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
174 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath =
175 CacheBuilder.newBuilder().build(new CacheLoader<>() {
177 public RpcInputCodec<?> load(final Absolute key) {
178 final var rpcName = key.firstNodeIdentifier();
179 final var context = factory().getRuntimeContext();
181 final Class<? extends DataContainer> container;
182 switch (key.lastNodeIdentifier().getLocalName()) {
184 container = context.getRpcInput(rpcName);
187 container = context.getRpcOutput(rpcName);
190 throw new IllegalArgumentException("Unhandled path " + key);
193 return getRpc(container);
197 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath =
198 CacheBuilder.newBuilder().build(new CacheLoader<>() {
200 public NotificationCodecContext<?> load(final Absolute key) {
201 final Class<?> cls = factory().getRuntimeContext().getClassForSchema(key);
202 checkArgument(Notification.class.isAssignableFrom(cls), "Path %s does not represent a notification",
204 return getNotificationImpl(cls);
208 private SchemaRootCodecContext(final DataContainerCodecPrototype<BindingRuntimeTypes> dataPrototype) {
209 super(dataPrototype);
213 * Creates RootNode from supplied CodecContextFactory.
216 * CodecContextFactory
217 * @return A new root node
219 static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
220 return new SchemaRootCodecContext<>(DataContainerCodecPrototype.rootPrototype(factory));
224 public WithStatus getSchema() {
225 return getType().getEffectiveModelContext();
229 @SuppressWarnings("unchecked")
230 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
231 final DataContainerCodecContext<?, ?> result = Notification.class.isAssignableFrom(childClass)
232 ? getNotificationImpl(childClass) : getOrRethrow(childrenByClass, childClass);
233 return (DataContainerCodecContext<C, ?>) result;
237 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
238 final Class<C> childClass) {
239 throw new UnsupportedOperationException("Not supported");
243 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
244 return getOrRethrow(childrenByQName, arg.getNodeType());
248 public D deserialize(final NormalizedNode normalizedNode) {
249 throw new UnsupportedOperationException("Could not create Binding data representation for root");
252 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
253 return getOrRethrow(actionsByClass, action);
256 NotificationCodecContext<?> getNotification(final Absolute notification) {
257 return getOrRethrow(notificationsByPath, notification);
260 NotificationCodecContext<?> getNotification(final Class<? extends Notification<?>> notification) {
261 return getNotificationImpl(notification);
264 private NotificationCodecContext<?> getNotificationImpl(final Class<?> notification) {
265 return getOrRethrow(notificationsByClass, notification);
268 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
269 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
272 RpcInputCodec<?> getRpc(final Absolute containerPath) {
273 return getOrRethrow(rpcDataByPath, containerPath);
276 DataContainerCodecContext<?, ?> createDataTreeChildContext(final Class<? extends DataObject> key) {
277 final RuntimeType childSchema = childNonNull(getType().bindingChild(JavaTypeName.create(key)), key,
278 "%s is not top-level item.", key);
279 if (childSchema instanceof CompositeRuntimeType && childSchema instanceof DataRuntimeType) {
280 return DataContainerCodecPrototype.from(key, (CompositeRuntimeType) childSchema, factory()).get();
282 throw IncorrectNestingException.create("%s is not a valid data tree child of %s", key, this);
285 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
286 if (KeyedListAction.class.isAssignableFrom(action)) {
287 return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
288 } else if (Action.class.isAssignableFrom(action)) {
289 return prepareActionContext(1, 2, 3, action, Action.class);
291 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
294 private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
295 final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
296 final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
297 checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
299 final ParameterizedType paramType = optParamType.get();
300 final Type[] args = paramType.getActualTypeArguments();
301 checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
302 final ActionRuntimeType schema = factory().getRuntimeContext().getActionDefinition(action);
303 return new ActionCodecContext(
304 DataContainerCodecPrototype.from(asClass(args[inputOffset], RpcInput.class), schema.input(),
306 DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.output(),
310 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
311 verify(type instanceof Class, "Type %s is not a class", type);
312 return ((Class<?>) type).asSubclass(target);
316 * Returns RPC input or output schema based on supplied QName.
318 * @param rpc RPC Definition
319 * @param qname input or output QName with namespace same as RPC
320 * @return input or output schema. Returns null if RPC does not have input/output specified.
322 private static @Nullable ContainerLike getRpcDataSchema(final @NonNull RpcDefinition rpc,
323 final @NonNull QName qname) {
324 requireNonNull(rpc, "Rpc Schema must not be null");
325 switch (requireNonNull(qname, "QName must not be null").getLocalName()) {
327 return rpc.getInput();
329 return rpc.getOutput();
331 throw new IllegalArgumentException("Supplied qname " + qname
332 + " does not represent rpc input or output.");
336 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
337 final Class<?> choiceClass = findCaseChoice(caseType);
338 checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
339 final CompositeRuntimeType schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
340 checkArgument(schema instanceof ChoiceRuntimeType, "Class %s does not refer to a choice", caseType);
342 final DataContainerCodecContext<?, ChoiceRuntimeType> choice = DataContainerCodecPrototype.from(choiceClass,
343 (ChoiceRuntimeType)schema, factory()).get();
344 Verify.verify(choice instanceof ChoiceNodeCodecContext);
345 return (ChoiceNodeCodecContext<?>) choice;
349 protected Object deserializeObject(final NormalizedNode normalizedNode) {
350 throw new UnsupportedOperationException("Unable to deserialize root");
354 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
355 checkArgument(arg == null);
360 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
361 checkArgument(arg == null);
366 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
367 final List<PathArgument> builder) {
368 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
369 if (caseType.isPresent()) {
370 final @NonNull Class<? extends DataObject> type = caseType.orElseThrow();
371 final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(type);
372 choice.addYangPathArgument(arg, builder);
373 final DataContainerCodecContext<?, ?> caze = choice.streamChild(type);
374 caze.addYangPathArgument(arg, builder);
375 return caze.bindingPathArgumentChild(arg, builder);
378 return super.bindingPathArgumentChild(arg, builder);
381 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
382 for (Type type : caseClass.getGenericInterfaces()) {
383 if (type instanceof Class) {
384 final Class<?> typeClass = (Class<?>) type;
385 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
386 return typeClass.asSubclass(ChoiceIn.class);
394 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
396 return cache.getUnchecked(key);
397 } catch (final UncheckedExecutionException e) {
398 final Throwable cause = e.getCause();
400 Throwables.throwIfUnchecked(cause);