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;
14 import com.google.common.base.Throwables;
15 import com.google.common.base.Verify;
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.util.concurrent.UncheckedExecutionException;
20 import java.lang.reflect.ParameterizedType;
21 import java.lang.reflect.Type;
22 import java.util.List;
23 import java.util.Optional;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
26 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
27 import org.opendaylight.yangtools.util.ClassLoaderUtils;
28 import org.opendaylight.yangtools.yang.binding.Action;
29 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
30 import org.opendaylight.yangtools.yang.binding.DataContainer;
31 import org.opendaylight.yangtools.yang.binding.DataObject;
32 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
33 import org.opendaylight.yangtools.yang.binding.KeyedListAction;
34 import org.opendaylight.yangtools.yang.binding.Notification;
35 import org.opendaylight.yangtools.yang.binding.RpcInput;
36 import org.opendaylight.yangtools.yang.binding.RpcOutput;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
43 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
45 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.Module;
48 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
49 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
50 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
51 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
52 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
53 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
55 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D,SchemaContext> {
57 private final LoadingCache<Class<? extends DataObject>, DataContainerCodecContext<?, ?>> childrenByClass =
58 CacheBuilder.newBuilder().build(new CacheLoader<>() {
60 public DataContainerCodecContext<?, ?> load(final Class<? extends DataObject> key) {
61 if (Notification.class.isAssignableFrom(key)) {
62 return createNotificationDataContext(key);
64 if (RpcInput.class.isAssignableFrom(key) || RpcOutput.class.isAssignableFrom(key)) {
65 return createRpcDataContext(key);
67 return createDataTreeChildContext(key);
71 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass =
72 CacheBuilder.newBuilder().build(new CacheLoader<>() {
74 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
75 return createActionContext(key);
79 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
80 CacheBuilder.newBuilder().build(new CacheLoader<>() {
82 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
83 return createChoiceDataContext(key);
87 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName =
88 CacheBuilder.newBuilder().build(new CacheLoader<>() {
90 public DataContainerCodecContext<?, ?> load(final QName qname) {
91 final DataSchemaNode childSchema = getSchema().dataChildByName(qname);
92 childNonNull(childSchema, qname, "Argument %s is not valid child of %s", qname, getSchema());
93 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
94 @SuppressWarnings("unchecked")
95 final Class<? extends DataObject> childCls = (Class<? extends DataObject>)
96 factory().getRuntimeContext().getClassForSchema(childSchema);
97 return streamChild(childCls);
100 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
104 private final LoadingCache<Absolute, RpcInputCodec<?>> rpcDataByPath =
105 CacheBuilder.newBuilder().build(new CacheLoader<>() {
107 public RpcInputCodec<?> load(final Absolute key) {
108 final ContainerLike schema = SchemaContextUtil.getRpcDataSchema(getSchema(), key.asSchemaPath());
109 @SuppressWarnings("unchecked")
110 final Class<? extends DataContainer> cls = (Class<? extends DataContainer>)
111 factory().getRuntimeContext().getClassForSchema(schema);
116 private final LoadingCache<Absolute, NotificationCodecContext<?>> notificationsByPath =
117 CacheBuilder.newBuilder().build(new CacheLoader<>() {
119 public NotificationCodecContext<?> load(final Absolute key) {
120 final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(),
121 // FIXME: do not convert here!
123 @SuppressWarnings("unchecked")
124 final Class<? extends Notification> clz = (Class<? extends Notification>)
125 factory().getRuntimeContext().getClassForSchema(schema);
126 return getNotification(clz);
130 private SchemaRootCodecContext(final DataContainerCodecPrototype<SchemaContext> dataPrototype) {
131 super(dataPrototype);
135 * Creates RootNode from supplied CodecContextFactory.
138 * CodecContextFactory
139 * @return A new root node
141 static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
142 final DataContainerCodecPrototype<SchemaContext> prototype = DataContainerCodecPrototype.rootPrototype(factory);
143 return new SchemaRootCodecContext<>(prototype);
147 @SuppressWarnings("unchecked")
149 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
150 return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass, childClass);
154 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
155 final Class<C> childClass) {
156 throw new UnsupportedOperationException("Not supported");
160 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
161 return getOrRethrow(childrenByQName, arg.getNodeType());
165 public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
166 throw new UnsupportedOperationException("Could not create Binding data representation for root");
169 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
170 return getOrRethrow(actionsByClass, action);
173 NotificationCodecContext<?> getNotification(final Class<? extends Notification> notification) {
174 return (NotificationCodecContext<?>) streamChild((Class<? extends DataObject>)notification);
177 NotificationCodecContext<?> getNotification(final Absolute notification) {
178 return getOrRethrow(notificationsByPath, notification);
181 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
182 return (ContainerNodeCodecContext<?>) streamChild((Class<? extends DataObject>)rpcInputOrOutput);
185 RpcInputCodec<?> getRpc(final Absolute containerPath) {
186 return getOrRethrow(rpcDataByPath, containerPath);
189 DataContainerCodecContext<?,?> createDataTreeChildContext(final Class<?> key) {
190 final QName qname = BindingReflections.findQName(key);
191 final DataSchemaNode childSchema = childNonNull(getSchema().dataChildByName(qname), key,
192 "%s is not top-level item.", key);
193 return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
196 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
197 if (KeyedListAction.class.isAssignableFrom(action)) {
198 return prepareActionContext(2, 3, 4, action, KeyedListAction.class);
199 } else if (Action.class.isAssignableFrom(action)) {
200 return prepareActionContext(1, 2, 3, action, Action.class);
202 throw new IllegalArgumentException("The specific action type does not exist for action " + action.getName());
205 private ActionCodecContext prepareActionContext(final int inputOffset, final int outputOffset,
206 final int expectedArgsLength, final Class<? extends Action<?, ?, ?>> action, final Class<?> actionType) {
207 final Optional<ParameterizedType> optParamType = ClassLoaderUtils.findParameterizedType(action, actionType);
208 checkState(optParamType.isPresent(), "%s does not specialize %s", action, actionType);
210 final ParameterizedType paramType = optParamType.get();
211 final Type[] args = paramType.getActualTypeArguments();
212 checkArgument(args.length == expectedArgsLength, "Unexpected (%s) Action generatic arguments", args.length);
213 final ActionDefinition schema = factory().getRuntimeContext().getActionDefinition(action);
214 return new ActionCodecContext(
215 DataContainerCodecPrototype.from(asClass(args[inputOffset], RpcInput.class), schema.getInput(),
217 DataContainerCodecPrototype.from(asClass(args[outputOffset], RpcOutput.class), schema.getOutput(),
221 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
222 verify(type instanceof Class, "Type %s is not a class", type);
223 return ((Class<?>) type).asSubclass(target);
226 ContainerNodeCodecContext<?> createRpcDataContext(final Class<?> key) {
227 checkArgument(DataContainer.class.isAssignableFrom(key));
228 final QName qname = BindingReflections.findQName(key);
229 final QNameModule qnameModule = qname.getModule();
230 final Module module = getSchema().findModule(qnameModule)
231 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
232 final String className = BindingMapping.getClassName(qname);
234 for (final RpcDefinition potential : module.getRpcs()) {
235 final QName potentialQName = potential.getQName();
237 * Check if rpc and class represents data from same module and then checks if rpc local name produces same
238 * class name as class name appended with Input/Output based on QName associated with binding class.
240 * FIXME: Rework this to have more precise logic regarding Binding Specification.
242 if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
243 final ContainerLike schema = SchemaNodeUtils.getRpcDataSchema(potential, qname);
244 checkArgument(schema != null, "Schema for %s does not define input / output.", potential.getQName());
245 return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
249 throw new IllegalArgumentException("Supplied class " + key + " is not valid RPC class.");
252 NotificationCodecContext<?> createNotificationDataContext(final Class<?> notificationType) {
253 checkArgument(Notification.class.isAssignableFrom(notificationType));
254 checkArgument(notificationType.isInterface(), "Supplied class must be interface.");
255 final QName qname = BindingReflections.findQName(notificationType);
256 final NotificationDefinition schema = getSchema().findNotification(qname).orElseThrow(
257 () -> new IllegalArgumentException("Supplied " + notificationType + " is not valid notification"));
258 return new NotificationCodecContext<>(notificationType, schema, factory());
261 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
262 final Class<?> choiceClass = findCaseChoice(caseType);
263 checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
264 final DataSchemaNode schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
265 checkArgument(schema instanceof ChoiceSchemaNode, "Class %s does not refer to a choice", caseType);
267 final DataContainerCodecContext<?, ChoiceSchemaNode> choice = DataContainerCodecPrototype.from(choiceClass,
268 (ChoiceSchemaNode)schema, factory()).get();
269 Verify.verify(choice instanceof ChoiceNodeCodecContext);
270 return (ChoiceNodeCodecContext<?>) choice;
274 protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
275 throw new UnsupportedOperationException("Unable to deserialize root");
279 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
280 checkArgument(arg == null);
285 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
286 checkArgument(arg == null);
291 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
292 final List<PathArgument> builder) {
293 final Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
294 if (caseType.isPresent()) {
295 final @NonNull Class<? extends DataObject> type = caseType.orElseThrow();
296 final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(type);
297 choice.addYangPathArgument(arg, builder);
298 final DataContainerCodecContext<?, ?> caze = choice.streamChild(type);
299 caze.addYangPathArgument(arg, builder);
300 return caze.bindingPathArgumentChild(arg, builder);
303 return super.bindingPathArgumentChild(arg, builder);
306 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
307 for (Type type : caseClass.getGenericInterfaces()) {
308 if (type instanceof Class) {
309 final Class<?> typeClass = (Class<?>) type;
310 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
311 return typeClass.asSubclass(ChoiceIn.class);
319 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
321 return cache.getUnchecked(key);
322 } catch (final UncheckedExecutionException e) {
323 final Throwable cause = e.getCause();
325 Throwables.throwIfUnchecked(cause);