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.Verify.verify;
13 import com.google.common.base.Throwables;
14 import com.google.common.base.Verify;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.util.concurrent.UncheckedExecutionException;
19 import java.lang.reflect.Type;
20 import java.util.List;
21 import java.util.Optional;
22 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
23 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
24 import org.opendaylight.yangtools.util.ClassLoaderUtils;
25 import org.opendaylight.yangtools.yang.binding.Action;
26 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
27 import org.opendaylight.yangtools.yang.binding.DataContainer;
28 import org.opendaylight.yangtools.yang.binding.DataObject;
29 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
30 import org.opendaylight.yangtools.yang.binding.Notification;
31 import org.opendaylight.yangtools.yang.binding.RpcInput;
32 import org.opendaylight.yangtools.yang.binding.RpcOutput;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
39 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.Module;
44 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
48 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
49 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
51 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D,SchemaContext> {
53 private final LoadingCache<Class<?>, DataContainerCodecContext<?,?>> childrenByClass = CacheBuilder.newBuilder()
54 .build(new CacheLoader<Class<?>, DataContainerCodecContext<?,?>>() {
56 public DataContainerCodecContext<?,?> load(final Class<?> key) {
57 return createDataTreeChildContext(key);
61 private final LoadingCache<Class<? extends Action<?, ?, ?>>, ActionCodecContext> actionsByClass = CacheBuilder
62 .newBuilder().build(new CacheLoader<Class<? extends Action<?, ?, ?>>, ActionCodecContext>() {
64 public ActionCodecContext load(final Class<? extends Action<?, ?, ?>> key) {
65 return createActionContext(key);
69 private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder().build(
70 new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
72 public ContainerNodeCodecContext<?> load(final Class<?> key) {
73 return createRpcDataContext(key);
77 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
78 .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
80 public NotificationCodecContext<?> load(final Class<?> key) {
81 return createNotificationDataContext(key);
85 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
86 CacheBuilder.newBuilder().build(new CacheLoader<Class<? extends DataObject>, ChoiceNodeCodecContext<?>>() {
88 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
89 return createChoiceDataContext(key);
93 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName = CacheBuilder.newBuilder().build(
94 new CacheLoader<QName, DataContainerCodecContext<?,?>>() {
96 public DataContainerCodecContext<?,?> load(final QName qname) {
97 final DataSchemaNode childSchema = getSchema().getDataChildByName(qname);
98 childNonNull(childSchema, qname,"Argument %s is not valid child of %s", qname,getSchema());
99 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
100 @SuppressWarnings("unchecked")
101 final Class<? extends DataObject> childCls = (Class<? extends DataObject>)
102 factory().getRuntimeContext().getClassForSchema(childSchema);
103 return streamChild(childCls);
106 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
110 private final LoadingCache<SchemaPath, RpcInputCodec<?>> rpcDataByPath = CacheBuilder.newBuilder().build(
111 new CacheLoader<SchemaPath, RpcInputCodec<?>>() {
113 public RpcInputCodec<?> load(final SchemaPath key) {
114 final ContainerSchemaNode schema = SchemaContextUtil.getRpcDataSchema(getSchema(), key);
115 @SuppressWarnings("unchecked")
116 final Class<? extends DataContainer> cls = (Class<? extends DataContainer>)
117 factory().getRuntimeContext().getClassForSchema(schema);
122 private final LoadingCache<SchemaPath, NotificationCodecContext<?>> notificationsByPath = CacheBuilder.newBuilder()
123 .build(new CacheLoader<SchemaPath, NotificationCodecContext<?>>() {
125 public NotificationCodecContext<?> load(final SchemaPath key) {
126 final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(), key);
127 @SuppressWarnings("unchecked")
128 final Class<? extends Notification> clz = (Class<? extends Notification>)
129 factory().getRuntimeContext().getClassForSchema(schema);
130 return getNotification(clz);
134 private SchemaRootCodecContext(final DataContainerCodecPrototype<SchemaContext> dataPrototype) {
135 super(dataPrototype);
139 * Creates RootNode from supplied CodecContextFactory.
142 * CodecContextFactory
143 * @return A new root node
145 static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
146 final DataContainerCodecPrototype<SchemaContext> prototype = DataContainerCodecPrototype.rootPrototype(factory);
147 return new SchemaRootCodecContext<>(prototype);
151 @SuppressWarnings("unchecked")
153 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
154 /* FIXME: This is still not solved for RPCs
155 * TODO: Probably performance wise RPC, Data and Notification loading cache
156 * should be merge for performance resons. Needs microbenchmark to
157 * determine which is faster (keeping them separate or in same cache).
159 if (Notification.class.isAssignableFrom(childClass)) {
160 return (DataContainerCodecContext<C, ?>) getNotification((Class<? extends Notification>)childClass);
162 return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass,childClass);
166 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
167 final Class<C> childClass) {
168 throw new UnsupportedOperationException("Not supported");
172 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
173 return getOrRethrow(childrenByQName, arg.getNodeType());
177 public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
178 throw new UnsupportedOperationException("Could not create Binding data representation for root");
181 ActionCodecContext getAction(final Class<? extends Action<?, ?, ?>> action) {
182 return getOrRethrow(actionsByClass, action);
185 NotificationCodecContext<?> getNotification(final Class<? extends Notification> notification) {
186 return getOrRethrow(notificationsByClass, notification);
189 NotificationCodecContext<?> getNotification(final SchemaPath notification) {
190 return getOrRethrow(notificationsByPath, notification);
193 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
194 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
197 RpcInputCodec<?> getRpc(final SchemaPath notification) {
198 return getOrRethrow(rpcDataByPath, notification);
201 DataContainerCodecContext<?,?> createDataTreeChildContext(final Class<?> key) {
202 final QName qname = BindingReflections.findQName(key);
203 final DataSchemaNode childSchema = childNonNull(getSchema().getDataChildByName(qname), key,
204 "%s is not top-level item.", key);
205 return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
208 ActionCodecContext createActionContext(final Class<? extends Action<?, ?, ?>> action) {
209 final Type[] args = ClassLoaderUtils.findParameterizedType(action, Action.class).getActualTypeArguments();
210 checkArgument(args.length == 3, "Unexpected (%s) Action generatic arguments", args.length);
212 final ActionDefinition schema = factory().getRuntimeContext().getActionDefinition(action);
213 return new ActionCodecContext(
214 DataContainerCodecPrototype.from(asClass(args[1], RpcInput.class), schema.getInput(), factory()).get(),
215 DataContainerCodecPrototype.from(asClass(args[2], RpcOutput.class), schema.getOutput(), factory()).get());
218 private static <T extends DataObject> Class<? extends T> asClass(final Type type, final Class<T> target) {
219 verify(type instanceof Class, "Type %s is not a class", type);
220 return ((Class<?>) type).asSubclass(target);
223 ContainerNodeCodecContext<?> createRpcDataContext(final Class<?> key) {
224 checkArgument(DataContainer.class.isAssignableFrom(key));
225 final QName qname = BindingReflections.findQName(key);
226 final QNameModule qnameModule = qname.getModule();
227 final Module module = getSchema().findModule(qnameModule)
228 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
229 final String className = BindingMapping.getClassName(qname);
231 RpcDefinition rpc = null;
232 for (final RpcDefinition potential : module.getRpcs()) {
233 final QName potentialQName = potential.getQName();
235 * Check if rpc and class represents data from same module and then
236 * checks if rpc local name produces same class name as class name
237 * appended with Input/Output based on QName associated with bidning
240 * FIXME: Rework this to have more precise logic regarding Binding
243 if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
248 checkArgument(rpc != null, "Supplied class %s is not valid RPC class.", key);
249 final ContainerSchemaNode schema = SchemaNodeUtils.getRpcDataSchema(rpc, qname);
250 checkArgument(schema != null, "Schema for %s does not define input / output.", rpc.getQName());
251 return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
254 NotificationCodecContext<?> createNotificationDataContext(final Class<?> notificationType) {
255 checkArgument(Notification.class.isAssignableFrom(notificationType));
256 checkArgument(notificationType.isInterface(), "Supplied class must be interface.");
257 final QName qname = BindingReflections.findQName(notificationType);
259 * FIXME: After Lithium cleanup of yang-model-api, use direct call on schema context
260 * to retrieve notification via index.
262 final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(),
263 SchemaPath.create(true, qname));
264 checkArgument(schema != null, "Supplied %s is not valid notification", notificationType);
266 return new NotificationCodecContext<>(notificationType, schema, factory());
269 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
270 final Class<?> choiceClass = findCaseChoice(caseType);
271 checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
272 final DataSchemaNode schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
273 checkArgument(schema instanceof ChoiceSchemaNode, "Class %s does not refer to a choice", caseType);
275 final DataContainerCodecContext<?, ChoiceSchemaNode> choice = DataContainerCodecPrototype.from(choiceClass,
276 (ChoiceSchemaNode)schema, factory()).get();
277 Verify.verify(choice instanceof ChoiceNodeCodecContext);
278 return (ChoiceNodeCodecContext<?>) choice;
282 protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
283 throw new UnsupportedOperationException("Unable to deserialize root");
287 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
288 checkArgument(arg == null);
293 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
294 checkArgument(arg == null);
299 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
300 final List<PathArgument> builder) {
301 final java.util.Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
302 if (caseType.isPresent()) {
303 final Class<? extends DataObject> type = caseType.get();
304 final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(type);
305 choice.addYangPathArgument(arg, builder);
306 final DataContainerCodecContext<?, ?> caze = choice.streamChild(type);
307 caze.addYangPathArgument(arg, builder);
308 return caze.bindingPathArgumentChild(arg, builder);
311 return super.bindingPathArgumentChild(arg, builder);
314 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
315 for (Type type : caseClass.getGenericInterfaces()) {
316 if (type instanceof Class) {
317 final Class<?> typeClass = (Class<?>) type;
318 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
319 return typeClass.asSubclass(ChoiceIn.class);
327 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
329 return cache.getUnchecked(key);
330 } catch (final UncheckedExecutionException e) {
331 final Throwable cause = e.getCause();
333 Throwables.throwIfUnchecked(cause);