8ce6245c9d3154ff5d9ab5f8aceb81109649e8c0
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / SchemaRootCodecContext.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.binding.data.codec.impl;
9
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.cache.CacheBuilder;
14 import com.google.common.cache.CacheLoader;
15 import com.google.common.cache.LoadingCache;
16 import com.google.common.util.concurrent.UncheckedExecutionException;
17 import org.opendaylight.yangtools.util.ClassLoaderUtils;
18 import org.opendaylight.yangtools.yang.binding.BindingMapping;
19 import org.opendaylight.yangtools.yang.binding.ChildOf;
20 import org.opendaylight.yangtools.yang.binding.DataContainer;
21 import org.opendaylight.yangtools.yang.binding.DataObject;
22 import org.opendaylight.yangtools.yang.binding.DataRoot;
23 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
24 import org.opendaylight.yangtools.yang.binding.Notification;
25 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
34 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
36 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
39 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
40 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
41
42 final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D,SchemaContext> {
43
44     private final LoadingCache<Class<?>, DataContainerCodecContext<?,?>> childrenByClass = CacheBuilder.newBuilder()
45             .build(new CacheLoader<Class<?>, DataContainerCodecContext<?,?>>() {
46                 @Override
47                 public DataContainerCodecContext<?,?> load(final Class<?> key) {
48                     return createDataTreeChildContext(key);
49                 }
50
51             });
52
53     private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder().build(
54             new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
55                 @Override
56                 public ContainerNodeCodecContext<?> load(final Class<?> key) {
57                     return createRpcDataContext(key);
58                 }
59             });
60
61     private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
62             .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
63                 @Override
64                 public NotificationCodecContext<?> load(final Class<?> key) {
65                     return createNotificationDataContext(key);
66                 }
67             });
68
69     private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName = CacheBuilder.newBuilder().build(
70             new CacheLoader<QName, DataContainerCodecContext<?,?>>() {
71                 @SuppressWarnings("unchecked")
72                 @Override
73                 public DataContainerCodecContext<?,?> load(final QName qname) {
74                     final DataSchemaNode childSchema = getSchema().getDataChildByName(qname);
75                     childNonNull(childSchema, qname,"Argument %s is not valid child of %s", qname,getSchema());
76                     if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
77                         @SuppressWarnings("rawtypes")
78                         final Class childCls = factory().getRuntimeContext().getClassForSchema(childSchema);
79                         return streamChild(childCls);
80                     } else {
81                         throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
82                     }
83                 }
84             });
85
86     private final LoadingCache<SchemaPath, ContainerNodeCodecContext<?>> rpcDataByPath = CacheBuilder.newBuilder().build(
87             new CacheLoader<SchemaPath, ContainerNodeCodecContext<?>>() {
88
89                 @SuppressWarnings({ "rawtypes", "unchecked" })
90                 @Override
91                 public ContainerNodeCodecContext load(final SchemaPath key) {
92                     final ContainerSchemaNode schema = SchemaContextUtil.getRpcDataSchema(getSchema(), key);
93                     final Class cls = factory().getRuntimeContext().getClassForSchema(schema);
94                     return getRpc(cls);
95                 }
96             });
97
98     private final LoadingCache<SchemaPath, NotificationCodecContext<?>> notificationsByPath = CacheBuilder.newBuilder()
99             .build(new CacheLoader<SchemaPath, NotificationCodecContext<?>>() {
100
101                 @SuppressWarnings({ "rawtypes", "unchecked" })
102                 @Override
103                 public NotificationCodecContext load(final SchemaPath key) throws Exception {
104                     final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(), key);
105                     final Class clz = factory().getRuntimeContext().getClassForSchema(schema);
106                     return getNotification(clz);
107                 }
108             });
109
110     private SchemaRootCodecContext(final DataContainerCodecPrototype<SchemaContext> dataPrototype) {
111         super(dataPrototype);
112     }
113
114     /**
115      * Creates RootNode from supplied CodecContextFactory.
116      *
117      * @param factory
118      *            CodecContextFactory
119      * @return
120      */
121     static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
122         final DataContainerCodecPrototype<SchemaContext> prototype = DataContainerCodecPrototype.rootPrototype(factory);
123         return new SchemaRootCodecContext<>(prototype);
124     }
125
126
127     @SuppressWarnings("unchecked")
128     @Override
129     public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass)
130             throws IllegalArgumentException {
131         /* FIXME: This is still not solved for RPCs
132          * TODO: Probably performance wise RPC, Data and Notification loading cache
133          *       should be merge for performance resons. Needs microbenchmark to
134          *       determine which is faster (keeping them separate or in same cache).
135          */
136         if (Notification.class.isAssignableFrom(childClass)) {
137             return (DataContainerCodecContext<DV, ?>) getNotification((Class<? extends Notification>)childClass);
138         }
139         return (DataContainerCodecContext<DV, ?>) getOrRethrow(childrenByClass,childClass);
140     }
141
142     @Override
143     public <E extends DataObject> Optional<DataContainerCodecContext<E,?>> possibleStreamChild(final Class<E> childClass) {
144         throw new UnsupportedOperationException("Not supported");
145     }
146
147     @Override
148     public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
149         return getOrRethrow(childrenByQName,arg.getNodeType());
150     }
151
152     @Override
153     public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
154         throw new UnsupportedOperationException(
155                 "Could not create Binding data representation for root");
156     }
157
158
159     ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
160         return getOrRethrow(rpcDataByClass, rpcInputOrOutput);
161     }
162
163     NotificationCodecContext<?> getNotification(final Class<? extends Notification> notification) {
164         return getOrRethrow(notificationsByClass, notification);
165     }
166
167     NotificationCodecContext<?> getNotification(final SchemaPath notification) {
168         return getOrRethrow(notificationsByPath, notification);
169     }
170
171     ContainerNodeCodecContext<?> getRpc(final SchemaPath notification) {
172         return getOrRethrow(rpcDataByPath, notification);
173     }
174
175     private DataContainerCodecContext<?,?> createDataTreeChildContext(final Class<?> key) {
176         final Class<Object> parent = ClassLoaderUtils.findFirstGenericArgument(key, ChildOf.class);
177         IncorrectNestingException.check(DataRoot.class.isAssignableFrom(parent), "Class %s is not top level item.", key);
178         final QName qname = BindingReflections.findQName(key);
179         final DataSchemaNode childSchema = childNonNull(getSchema().getDataChildByName(qname),key,"%s is not top-level item.",key);
180         return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
181     }
182
183     private ContainerNodeCodecContext<?> createRpcDataContext(final Class<?> key) {
184         Preconditions.checkArgument(DataContainer.class.isAssignableFrom(key));
185         final QName qname = BindingReflections.findQName(key);
186         final QNameModule module = qname.getModule();
187         RpcDefinition rpc = null;
188         for (final RpcDefinition potential : getSchema().getOperations()) {
189             final QName potentialQName = potential.getQName();
190             /*
191              *
192              * Check if rpc and class represents data from same module and then
193              * checks if rpc local name produces same class name as class name
194              * appended with Input/Output based on QName associated with bidning
195              * class.
196              *
197              * FIXME: Rework this to have more precise logic regarding Binding
198              * Specification.
199              */
200             if (module.equals(potentialQName.getModule())
201                     && key.getSimpleName().equals(
202                             BindingMapping.getClassName(potentialQName) + BindingMapping.getClassName(qname))) {
203                 rpc = potential;
204                 break;
205             }
206         }
207         Preconditions.checkArgument(rpc != null, "Supplied class %s is not valid RPC class.", key);
208         final ContainerSchemaNode schema = SchemaNodeUtils.getRpcDataSchema(rpc, qname);
209         Preconditions.checkArgument(schema != null, "Schema for %s does not define input / output.", rpc.getQName());
210         return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
211     }
212
213     private NotificationCodecContext<?> createNotificationDataContext(final Class<?> notificationType) {
214         Preconditions.checkArgument(Notification.class.isAssignableFrom(notificationType));
215         Preconditions.checkArgument(notificationType.isInterface(), "Supplied class must be interface.");
216         final QName qname = BindingReflections.findQName(notificationType);
217         /**
218          *  FIXME: After Lithium cleanup of yang-model-api, use direct call on schema context
219          *  to retrieve notification via index.
220          */
221         final NotificationDefinition schema = SchemaContextUtil.getNotificationSchema(getSchema(),
222                 SchemaPath.create(true, qname));
223         Preconditions.checkArgument(schema != null, "Supplied %s is not valid notification", notificationType);
224
225         return new NotificationCodecContext<>(notificationType, schema, factory());
226     }
227
228     @Override
229     protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
230         throw new UnsupportedOperationException("Unable to deserialize root");
231     }
232
233     @Override
234     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
235         Preconditions.checkArgument(arg == null);
236         return null;
237     }
238
239     @Override
240     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
241         Preconditions.checkArgument(arg == null);
242         return null;
243     }
244
245     private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
246         try {
247             return cache.getUnchecked(key);
248         } catch (final UncheckedExecutionException e) {
249             final Throwable cause = e.getCause();
250             if(cause != null) {
251                 Throwables.propagateIfPossible(cause);
252             }
253             throw e;
254         }
255     }
256
257 }