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.Iterator;
25 import java.util.List;
26 import java.util.Optional;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
30 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
31 import org.opendaylight.yangtools.util.ClassLoaderUtils;
32 import org.opendaylight.yangtools.yang.binding.Action;
33 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
34 import org.opendaylight.yangtools.yang.binding.DataContainer;
35 import org.opendaylight.yangtools.yang.binding.DataObject;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.binding.KeyedListAction;
38 import org.opendaylight.yangtools.yang.binding.Notification;
39 import org.opendaylight.yangtools.yang.binding.RpcInput;
40 import org.opendaylight.yangtools.yang.binding.RpcOutput;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.QNameModule;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
52 import org.opendaylight.yangtools.yang.model.api.Module;
53 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
54 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
55 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
56 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
58 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D, EffectiveModelContext> {
60 private final LoadingCache<Class<? extends DataObject>, DataContainerCodecContext<?, ?>> childrenByClass =
61 CacheBuilder.newBuilder().build(new CacheLoader<>() {
63 public DataContainerCodecContext<?, ?> load(final Class<? extends DataObject> key) {
64 if (Notification.class.isAssignableFrom(key)) {
65 checkArgument(key.isInterface(), "Supplied class must be interface.");
66 final QName qname = BindingReflections.findQName(key);
67 final NotificationDefinition schema = getSchema().findNotification(qname).orElseThrow(
68 () -> new IllegalArgumentException("Supplied " + key + " is not valid notification"));
69 return new NotificationCodecContext<>(key, schema, factory());
71 if (RpcInput.class.isAssignableFrom(key) || RpcOutput.class.isAssignableFrom(key)) {
72 final QName qname = BindingReflections.findQName(key);
73 final QNameModule qnameModule = qname.getModule();
74 final Module module = getSchema().findModule(qnameModule).orElseThrow(
75 () -> new IllegalArgumentException("Failed to find module for " + qnameModule));
76 final String className = BindingMapping.getClassName(qname);
78 for (final RpcDefinition potential : module.getRpcs()) {
79 final QName potentialQName = potential.getQName();
81 * Check if rpc and class represents data from same module and then checks if rpc local name
82 * produces same class name as class name appended with Input/Output based on QName associated
85 * FIXME: Rework this to have more precise logic regarding Binding Specification.
87 if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
88 final ContainerLike schema = getRpcDataSchema(potential, qname);
89 checkArgument(schema != null, "Schema for %s does not define input / output.",
91 return DataContainerCodecPrototype.from(key, schema, factory()).get();
95 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
97 return createDataTreeChildContext(key);
101 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass =
102 CacheBuilder.newBuilder().build(new CacheLoader<>() {
104 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
105 return createActionContext(key);
109 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
110 CacheBuilder.newBuilder().build(new CacheLoader<>() {
112 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
113 return createChoiceDataContext(key);
117 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName =
118 CacheBuilder.newBuilder().build(new CacheLoader<>() {
120 public DataContainerCodecContext<?, ?> load(final QName qname) {
121 final DataSchemaNode childSchema = getSchema().dataChildByName(qname);
122 childNonNull(childSchema, qname, "Argument %s is not valid child of %s", qname, getSchema());
123 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
124 @SuppressWarnings("unchecked")
125 final Class<? extends DataObject> childCls = (Class<? extends DataObject>)
126 factory().getRuntimeContext().getClassForSchema(childSchema);
127 return streamChild(childCls);
130 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
134 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath =
135 CacheBuilder.newBuilder().build(new CacheLoader<>() {
137 public RpcInputCodec<?> load(final Absolute key) {
138 final ContainerLike schema = getRpcDataSchema(getSchema(), key);
139 @SuppressWarnings("unchecked")
140 final Class<? extends DataContainer> cls = (Class<? extends DataContainer>)
141 factory().getRuntimeContext().getClassForSchema(schema);
146 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath =
147 CacheBuilder.newBuilder().build(new CacheLoader<>() {
149 public NotificationCodecContext<?> load(final Absolute key) {
150 final SchemaTreeEffectiveStatement<?> stmt = getSchema().findSchemaTreeNode(key)
151 .orElseThrow(() -> new IllegalArgumentException("Cannot find statement at " + key));
152 checkArgument(stmt instanceof NotificationDefinition, "Statement %s is not a notification", stmt);
154 @SuppressWarnings("unchecked")
155 final Class<? extends Notification<?>> clz = (Class<? extends Notification<?>>)
156 factory().getRuntimeContext().getClassForSchema((NotificationDefinition) stmt);
157 return getNotification(clz);
161 private SchemaRootCodecContext(final DataContainerCodecPrototype<EffectiveModelContext> dataPrototype) {
162 super(dataPrototype);
166 * Creates RootNode from supplied CodecContextFactory.
169 * CodecContextFactory
170 * @return A new root node
172 static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
173 return new SchemaRootCodecContext<>(DataContainerCodecPrototype.rootPrototype(factory));
176 @SuppressWarnings("unchecked")
178 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
179 return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass, childClass);
183 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
184 final Class<C> childClass) {
185 throw new UnsupportedOperationException("Not supported");
189 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
190 return getOrRethrow(childrenByQName, arg.getNodeType());
194 public D deserialize(final NormalizedNode normalizedNode) {
195 throw new UnsupportedOperationException("Could not create Binding data representation for root");
198 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
199 return getOrRethrow(actionsByClass, action);
202 NotificationCodecContext<?> getNotification(final Class<? extends Notification<?>> notification) {
203 return (NotificationCodecContext<?>) streamChild((Class<? extends DataObject>)notification);
206 NotificationCodecContext<?> getNotification(final Absolute notification) {
207 return getOrRethrow(notificationsByPath, notification);
210 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
211 return (ContainerNodeCodecContext<?>) streamChild((Class<? extends DataObject>)rpcInputOrOutput);
214 RpcInputCodec<?> getRpc(final Absolute containerPath) {
215 return getOrRethrow(rpcDataByPath, containerPath);
218 DataContainerCodecContext<?, ?> createDataTreeChildContext(final Class<? extends DataObject> key) {
219 final QName qname = BindingReflections.findQName(key);
220 final DataSchemaNode childSchema = childNonNull(getSchema().dataChildByName(qname), key,
221 "%s is not top-level item.", key);
222 return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
225 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
226 if (KeyedListAction.class.isAssignableFrom(action)) {
227 return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
228 } else if (Action.class.isAssignableFrom(action)) {
229 return prepareActionContext(1, 2, 3, action, Action.class);
231 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
234 private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
235 final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
236 final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
237 checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
239 final ParameterizedType paramType = optParamType.get();
240 final Type[] args = paramType.getActualTypeArguments();
241 checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
242 final ActionDefinition schema = factory().getRuntimeContext().getActionDefinition(action);
243 return new ActionCodecContext(
244 DataContainerCodecPrototype.from(asClass(args[inputOffset], RpcInput.class), schema.getInput(),
246 DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.getOutput(),
250 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
251 verify(type instanceof Class, "Type %s is not a class", type);
252 return ((Class<?>) type).asSubclass(target);
256 * Returns RPC input or output schema based on supplied QName.
258 * @param rpc RPC Definition
259 * @param qname input or output QName with namespace same as RPC
260 * @return input or output schema. Returns null if RPC does not have input/output specified.
262 private static @Nullable ContainerLike getRpcDataSchema(final @NonNull RpcDefinition rpc,
263 final @NonNull QName qname) {
264 requireNonNull(rpc, "Rpc Schema must not be null");
265 switch (requireNonNull(qname, "QName must not be null").getLocalName()) {
267 return rpc.getInput();
269 return rpc.getOutput();
271 throw new IllegalArgumentException("Supplied qname " + qname
272 + " does not represent rpc input or output.");
277 * Returns RPC Input or Output Data container from RPC definition.
279 * @param schema SchemaContext in which lookup should be performed.
280 * @param path Schema path of RPC input/output data container
281 * @return Notification schema or null, if notification is not present in schema context.
283 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
284 justification = "https://github.com/spotbugs/spotbugs/issues/811")
285 private static @Nullable ContainerLike getRpcDataSchema(final @NonNull EffectiveModelContext schema,
286 final @NonNull Absolute path) {
287 requireNonNull(schema, "Schema context must not be null.");
288 requireNonNull(path, "Schema path must not be null.");
289 final Iterator<QName> it = path.getNodeIdentifiers().iterator();
290 checkArgument(it.hasNext(), "Rpc must have QName.");
291 final QName rpcName = it.next();
292 checkArgument(it.hasNext(), "input or output must be part of path.");
293 final QName inOrOut = it.next();
294 for (final RpcDefinition potential : schema.getOperations()) {
295 if (rpcName.equals(potential.getQName())) {
296 return getRpcDataSchema(potential, inOrOut);
302 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
303 final Class<?> choiceClass = findCaseChoice(caseType);
304 checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
305 final DataSchemaNode schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
306 checkArgument(schema instanceof ChoiceSchemaNode, "Class %s does not refer to a choice", caseType);
308 final DataContainerCodecContext<?, ChoiceSchemaNode> choice = DataContainerCodecPrototype.from(choiceClass,
309 (ChoiceSchemaNode)schema, factory()).get();
310 Verify.verify(choice instanceof ChoiceNodeCodecContext);
311 return (ChoiceNodeCodecContext<?>) choice;
315 protected Object deserializeObject(final NormalizedNode normalizedNode) {
316 throw new UnsupportedOperationException("Unable to deserialize root");
320 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
321 checkArgument(arg == null);
326 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
327 checkArgument(arg == null);
332 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
333 final List<PathArgument> builder) {
334 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
335 if (caseType.isPresent()) {
336 final @NonNull Class<? extends DataObject> type = caseType.orElseThrow();
337 final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(type);
338 choice.addYangPathArgument(arg, builder);
339 final DataContainerCodecContext<?, ?> caze = choice.streamChild(type);
340 caze.addYangPathArgument(arg, builder);
341 return caze.bindingPathArgumentChild(arg, builder);
344 return super.bindingPathArgumentChild(arg, builder);
347 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
348 for (Type type : caseClass.getGenericInterfaces()) {
349 if (type instanceof Class) {
350 final Class<?> typeClass = (Class<?>) type;
351 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
352 return typeClass.asSubclass(ChoiceIn.class);
360 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
362 return cache.getUnchecked(key);
363 } catch (final UncheckedExecutionException e) {
364 final Throwable cause = e.getCause();
366 Throwables.throwIfUnchecked(cause);