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