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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import com.google.common.base.Verify;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.util.concurrent.UncheckedExecutionException;
18 import java.lang.reflect.Type;
19 import java.util.List;
20 import org.opendaylight.yangtools.yang.binding.BindingMapping;
21 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
22 import org.opendaylight.yangtools.yang.binding.DataContainer;
23 import org.opendaylight.yangtools.yang.binding.DataObject;
24 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
25 import org.opendaylight.yangtools.yang.binding.Notification;
26 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.common.QNameModule;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
32 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.Module;
37 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
38 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
42 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
44 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D,SchemaContext> {
46 private final LoadingCache<Class<?>, DataContainerCodecContext<?,?>> childrenByClass = CacheBuilder.newBuilder()
47 .build(new CacheLoader<Class<?>, DataContainerCodecContext<?,?>>() {
49 public DataContainerCodecContext<?,?> load(final Class<?> key) {
50 return createDataTreeChildContext(key);
54 private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder().build(
55 new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
57 public ContainerNodeCodecContext<?> load(final Class<?> key) {
58 return createRpcDataContext(key);
62 private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
63 .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
65 public NotificationCodecContext<?> load(final Class<?> key) {
66 return createNotificationDataContext(key);
70 private final LoadingCache<Class<? extends DataObject>, ChoiceNodeCodecContext<?>> choicesByClass =
71 CacheBuilder.newBuilder().build(new CacheLoader<Class<? extends DataObject>, ChoiceNodeCodecContext<?>>() {
73 public ChoiceNodeCodecContext<?> load(final Class<? extends DataObject> key) {
74 return createChoiceDataContext(key);
78 private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName = CacheBuilder.newBuilder().build(
79 new CacheLoader<QName, DataContainerCodecContext<?,?>>() {
81 public DataContainerCodecContext<?,?> load(final QName qname) {
82 final DataSchemaNode childSchema = getSchema().getDataChildByName(qname);
83 childNonNull(childSchema, qname,"Argument %s is not valid child of %s", qname,getSchema());
84 if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
85 @SuppressWarnings("unchecked")
86 final Class<? extends DataObject> childCls = (Class<? extends DataObject>)
87 factory().getRuntimeContext().getClassForSchema(childSchema);
88 return streamChild(childCls);
91 throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
95 private final LoadingCache<SchemaPath, RpcInputCodec<?>> rpcDataByPath = CacheBuilder.newBuilder().build(
96 new CacheLoader<SchemaPath, RpcInputCodec<?>>() {
98 public RpcInputCodec<?> load(final SchemaPath key) {
99 final ContainerSchemaNode schema = SchemaContextUtil.getRpcDataSchema(getSchema(), key);
100 @SuppressWarnings("unchecked")
101 final Class<? extends DataContainer> cls = (Class<? extends DataContainer>)
102 factory().getRuntimeContext().getClassForSchema(schema);
107 private final LoadingCache<SchemaPath, NotificationCodecContext<?>> notificationsByPath = CacheBuilder.newBuilder()
108 .build(new CacheLoader<SchemaPath, NotificationCodecContext<?>>() {
110 public NotificationCodecContext<?> load(final SchemaPath key) {
111 final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(), key);
112 @SuppressWarnings("unchecked")
113 final Class<? extends Notification> clz = (Class<? extends Notification>)
114 factory().getRuntimeContext().getClassForSchema(schema);
115 return getNotification(clz);
119 private SchemaRootCodecContext(final DataContainerCodecPrototype<SchemaContext> dataPrototype) {
120 super(dataPrototype);
124 * Creates RootNode from supplied CodecContextFactory.
127 * CodecContextFactory
128 * @return A new root node
130 static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
131 final DataContainerCodecPrototype<SchemaContext> prototype = DataContainerCodecPrototype.rootPrototype(factory);
132 return new SchemaRootCodecContext<>(prototype);
136 @SuppressWarnings("unchecked")
138 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
139 /* FIXME: This is still not solved for RPCs
140 * TODO: Probably performance wise RPC, Data and Notification loading cache
141 * should be merge for performance resons. Needs microbenchmark to
142 * determine which is faster (keeping them separate or in same cache).
144 if (Notification.class.isAssignableFrom(childClass)) {
145 return (DataContainerCodecContext<C, ?>) getNotification((Class<? extends Notification>)childClass);
147 return (DataContainerCodecContext<C, ?>) getOrRethrow(childrenByClass,childClass);
151 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
152 final Class<C> childClass) {
153 throw new UnsupportedOperationException("Not supported");
157 public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
158 return getOrRethrow(childrenByQName, arg.getNodeType());
162 public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
163 throw new UnsupportedOperationException("Could not create Binding data representation for root");
166 NotificationCodecContext<?> getNotification(final Class<? extends Notification> notification) {
167 return getOrRethrow(notificationsByClass, notification);
170 NotificationCodecContext<?> getNotification(final SchemaPath notification) {
171 return getOrRethrow(notificationsByPath, notification);
174 ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
175 return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
178 RpcInputCodec<?> getRpc(final SchemaPath notification) {
179 return getOrRethrow(rpcDataByPath, notification);
182 DataContainerCodecContext<?,?> createDataTreeChildContext(final Class<?> key) {
183 final QName qname = BindingReflections.findQName(key);
184 final DataSchemaNode childSchema = childNonNull(getSchema().getDataChildByName(qname), key,
185 "%s is not top-level item.", key);
186 return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
189 ContainerNodeCodecContext<?> createRpcDataContext(final Class<?> key) {
190 Preconditions.checkArgument(DataContainer.class.isAssignableFrom(key));
191 final QName qname = BindingReflections.findQName(key);
192 final QNameModule qnameModule = qname.getModule();
193 final Module module = getSchema().findModule(qnameModule)
194 .orElseThrow(() -> new IllegalArgumentException("Failed to find module for " + qnameModule));
195 final String className = BindingMapping.getClassName(qname);
197 RpcDefinition rpc = null;
198 for (final RpcDefinition potential : module.getRpcs()) {
199 final QName potentialQName = potential.getQName();
201 * Check if rpc and class represents data from same module and then
202 * checks if rpc local name produces same class name as class name
203 * appended with Input/Output based on QName associated with bidning
206 * FIXME: Rework this to have more precise logic regarding Binding
209 if (key.getSimpleName().equals(BindingMapping.getClassName(potentialQName) + className)) {
214 Preconditions.checkArgument(rpc != null, "Supplied class %s is not valid RPC class.", key);
215 final ContainerSchemaNode schema = SchemaNodeUtils.getRpcDataSchema(rpc, qname);
216 Preconditions.checkArgument(schema != null, "Schema for %s does not define input / output.", rpc.getQName());
217 return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
220 NotificationCodecContext<?> createNotificationDataContext(final Class<?> notificationType) {
221 Preconditions.checkArgument(Notification.class.isAssignableFrom(notificationType));
222 Preconditions.checkArgument(notificationType.isInterface(), "Supplied class must be interface.");
223 final QName qname = BindingReflections.findQName(notificationType);
225 * FIXME: After Lithium cleanup of yang-model-api, use direct call on schema context
226 * to retrieve notification via index.
228 final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(),
229 SchemaPath.create(true, qname));
230 Preconditions.checkArgument(schema != null, "Supplied %s is not valid notification", notificationType);
232 return new NotificationCodecContext<>(notificationType, schema, factory());
235 ChoiceNodeCodecContext<?> createChoiceDataContext(final Class<? extends DataObject> caseType) {
236 final Class<?> choiceClass = findCaseChoice(caseType);
237 Preconditions.checkArgument(choiceClass != null, "Class %s is not a valid case representation", caseType);
238 final DataSchemaNode schema = factory().getRuntimeContext().getSchemaDefinition(choiceClass);
239 Preconditions.checkArgument(schema instanceof ChoiceSchemaNode, "Class %s does not refer to a choice",
242 final DataContainerCodecContext<?, ChoiceSchemaNode> choice = DataContainerCodecPrototype.from(choiceClass,
243 (ChoiceSchemaNode)schema, factory()).get();
244 Verify.verify(choice instanceof ChoiceNodeCodecContext);
245 return (ChoiceNodeCodecContext<?>) choice;
249 protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
250 throw new UnsupportedOperationException("Unable to deserialize root");
254 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
255 Preconditions.checkArgument(arg == null);
260 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
261 Preconditions.checkArgument(arg == null);
266 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
267 final List<PathArgument> builder) {
268 final java.util.Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
269 if (caseType.isPresent()) {
270 final Class<? extends DataObject> type = caseType.get();
271 final ChoiceNodeCodecContext<?> choice = choicesByClass.getUnchecked(type);
272 choice.addYangPathArgument(arg, builder);
273 final DataContainerCodecContext<?, ?> caze = choice.streamChild(type);
274 caze.addYangPathArgument(arg, builder);
275 return caze.bindingPathArgumentChild(arg, builder);
278 return super.bindingPathArgumentChild(arg, builder);
281 private static Class<?> findCaseChoice(final Class<? extends DataObject> caseClass) {
282 for (Type type : caseClass.getGenericInterfaces()) {
283 if (type instanceof Class) {
284 final Class<?> typeClass = (Class<?>) type;
285 if (ChoiceIn.class.isAssignableFrom(typeClass)) {
286 return typeClass.asSubclass(ChoiceIn.class);
294 private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
296 return cache.getUnchecked(key);
297 } catch (final UncheckedExecutionException e) {
298 final Throwable cause = e.getCause();
300 Throwables.throwIfUnchecked(cause);