Fixed two-phase commit bug when change originated in DOM Broker
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / codegen / impl / RuntimeCodeGenerator.xtend
1 /*
2  * Copyright (c) 2013 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.controller.sal.binding.codegen.impl
9
10 import javassist.ClassPool
11 import org.opendaylight.yangtools.yang.binding.RpcService
12
13 import javassist.CtClass
14 import javassist.CtMethod
15 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
16 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext
17 import org.opendaylight.yangtools.yang.binding.BaseIdentity
18
19 import java.util.Map
20 import java.util.HashMap
21
22
23 import org.opendaylight.yangtools.yang.binding.NotificationListener
24 import org.opendaylight.yangtools.yang.binding.Notification
25
26
27 import static extension org.opendaylight.controller.sal.binding.codegen.YangtoolsMappingHelper.*
28 import static extension org.opendaylight.controller.sal.binding.codegen.RuntimeCodeSpecification.*
29 import java.util.HashSet
30 import static org.opendaylight.controller.sal.binding.impl.util.ClassLoaderUtils.*
31 import org.opendaylight.controller.sal.binding.spi.NotificationInvokerFactory
32 import org.opendaylight.controller.sal.binding.spi.NotificationInvokerFactory.NotificationInvoker
33 import java.util.Set
34 import org.opendaylight.controller.sal.binding.codegen.RuntimeCodeHelper
35 import java.util.WeakHashMap
36 import org.opendaylight.yangtools.yang.binding.annotations.QName
37 import org.opendaylight.yangtools.yang.binding.DataContainer
38 import org.opendaylight.yangtools.yang.binding.RpcImplementation
39 import org.opendaylight.controller.sal.binding.codegen.util.JavassistUtils
40
41 class RuntimeCodeGenerator implements org.opendaylight.controller.sal.binding.codegen.RuntimeCodeGenerator, NotificationInvokerFactory {
42
43     val CtClass BROKER_NOTIFICATION_LISTENER;
44     val ClassPool classPool;
45     val extension JavassistUtils utils;
46     val Map<Class<? extends NotificationListener>, RuntimeGeneratedInvokerPrototype> invokerClasses;
47
48     public new(ClassPool pool) {
49         classPool = pool;
50         utils = new JavassistUtils(pool);
51         invokerClasses = new WeakHashMap();
52         BROKER_NOTIFICATION_LISTENER = org.opendaylight.controller.sal.binding.api.NotificationListener.asCtClass;
53     }
54
55     override <T extends RpcService> getDirectProxyFor(Class<T> iface) {
56         val supertype = iface.asCtClass
57         val targetCls = createClass(iface.directProxyName, supertype) [
58             field(DELEGATE_FIELD, iface);
59             implementMethodsFrom(supertype) [
60                 body = '''return ($r) «DELEGATE_FIELD».«it.name»($$);'''
61             ]
62         ]
63         return targetCls.toClass(iface.classLoader).newInstance as T
64     }
65
66     override <T extends RpcService> getRouterFor(Class<T> iface) {
67         val instance = <RpcRouterCodegenInstance<T>>withClassLoaderAndLock(iface.classLoader,lock) [ |
68             val supertype = iface.asCtClass
69             val metadata = supertype.rpcMetadata;
70             val targetCls = createClass(iface.routerName, supertype) [
71                 addInterface(RpcImplementation.asCtClass)
72                 
73                 field(DELEGATE_FIELD, iface)
74                 //field(REMOTE_INVOKER_FIELD,iface);
75                 
76                 for (ctx : metadata.contexts) {
77                     field(ctx.routingTableField, Map)
78                 }
79                 implementMethodsFrom(supertype) [
80                     if (parameterTypes.size === 1) {
81                         val rpcMeta = metadata.rpcMethods.get(name);
82                         val bodyTmp = '''
83                         {
84                             final «InstanceIdentifier.name» identifier = $1.«rpcMeta.inputRouteGetter.name»()«IF rpcMeta.
85                             routeEncapsulated».getValue()«ENDIF»;
86                             «supertype.name» instance = («supertype.name») «rpcMeta.context.routingTableField».get(identifier);
87                             if(instance == null) {
88                                instance = «DELEGATE_FIELD»;
89                             }
90                             if(instance == null) {
91                                 throw new java.lang.IllegalStateException("No provider is processing supplied message");
92                             }
93                             return ($r) instance.«it.name»($$);
94                         }'''
95                         body = bodyTmp
96                     } else if (parameterTypes.size === 0) {
97                         body = '''return ($r) «DELEGATE_FIELD».«it.name»($$);'''
98                     }
99                 ]
100                 implementMethodsFrom(RpcImplementation.asCtClass) [
101                     switch (name) {
102                         case "getSupportedInputs":
103                             body = '''
104                             {
105                                 throw new java.lang.UnsupportedOperationException("Not implemented yet");
106                                 return ($r) null;
107                             }'''
108                         case "invoke": {
109                             val tmpBody = '''
110                             {
111                                 «FOR input : metadata.supportedInputs SEPARATOR " else "»
112                                 «val rpcMetadata = metadata.rpcInputs.get(input)»
113                                 if(«input.name».class.equals($1)) {
114                                     return ($r) this.«rpcMetadata.methodName»((«input.name») $2);
115                                 }
116                                 «ENDFOR»
117                                 throw new java.lang.IllegalArgumentException("Not supported message type");
118                                 return ($r) null;
119                             }
120                             '''
121                             body = tmpBody
122                         }
123                     }
124                 ]
125             ]
126             val instance = targetCls.toClass(iface.classLoader,iface.protectionDomain).newInstance as T
127             return new RpcRouterCodegenInstance(iface, instance, metadata.contexts,metadata.supportedInputs);
128         ];
129         return instance;
130     }
131
132     private def RpcServiceMetadata getRpcMetadata(CtClass iface) {
133         val metadata = new RpcServiceMetadata;
134         
135         iface.methods.filter[declaringClass == iface && parameterTypes.size === 1].forEach [ method |
136             val routingPair = method.rpcMetadata;
137             if (routingPair !== null) {
138                 metadata.contexts.add(routingPair.context)
139                 metadata.rpcMethods.put(method.name,routingPair)
140                 val input = routingPair.inputType.javaClass as Class<? extends DataContainer>;
141                 metadata.supportedInputs.add(input);
142                 metadata.rpcInputs.put(input,routingPair);
143             }
144         ]
145         return metadata;
146     }
147
148     private def getRpcMetadata(CtMethod method) {
149         val inputClass = method.parameterTypes.get(0); 
150         return inputClass.rpcMethodMetadata(inputClass,method.name);
151     }
152
153     private def RpcMetadata rpcMethodMetadata(CtClass dataClass,CtClass inputClass,String rpcMethod) {
154         for (method : dataClass.methods) {
155             if (method.name.startsWith("get") && method.parameterTypes.size === 0) {
156                 for (annotation : method.availableAnnotations) {
157                     if (annotation instanceof RoutingContext) {
158                         val encapsulated = !method.returnType.equals(InstanceIdentifier.asCtClass);
159                         return new RpcMetadata(null,rpcMethod,(annotation as RoutingContext).value, method, encapsulated,inputClass);
160                     }
161                 }
162             }
163         }
164         for (iface : dataClass.interfaces) {
165             val ret = rpcMethodMetadata(iface,inputClass,rpcMethod);
166             if(ret != null) return ret;
167         }
168         return null;
169     }
170
171     private def getJavaClass(CtClass cls) {
172         Thread.currentThread.contextClassLoader.loadClass(cls.name)
173     }
174
175     override getInvokerFactory() {
176         return this;
177     }
178
179     override invokerFor(NotificationListener instance) {
180         val cls = instance.class
181         val prototype = resolveInvokerClass(cls);
182
183         return new RuntimeGeneratedInvoker(instance, prototype)
184     }
185
186     protected def generateListenerInvoker(Class<? extends NotificationListener> iface) {
187         val callbacks = iface.methods.filter[notificationCallback]
188
189         val supportedNotification = callbacks.map[parameterTypes.get(0) as Class<? extends Notification>].toSet;
190
191         val targetCls = createClass(iface.invokerName, BROKER_NOTIFICATION_LISTENER) [
192             field(DELEGATE_FIELD, iface)
193             implementMethodsFrom(BROKER_NOTIFICATION_LISTENER) [
194                 body = '''
195                     {
196                         «FOR callback : callbacks SEPARATOR " else "»
197                             «val cls = callback.parameterTypes.get(0).name»
198                                 if($1 instanceof «cls») {
199                                     «DELEGATE_FIELD».«callback.name»((«cls») $1);
200                                     return null;
201                                 }
202                         «ENDFOR»
203                         return null;
204                     }
205                 '''
206             ]
207         ]
208         val finalClass = targetCls.toClass(iface.classLoader, iface.protectionDomain)
209         return new RuntimeGeneratedInvokerPrototype(supportedNotification,
210             finalClass as Class<? extends org.opendaylight.controller.sal.binding.api.NotificationListener<?>>);
211     }
212
213     
214
215
216
217     protected def resolveInvokerClass(Class<? extends NotificationListener> class1) {
218         return <RuntimeGeneratedInvokerPrototype>withClassLoaderAndLock(class1.classLoader,lock) [|
219             val invoker = invokerClasses.get(class1);
220             if (invoker !== null) {
221                 return invoker;
222             }
223             val newInvoker = generateListenerInvoker(class1);
224             invokerClasses.put(class1, newInvoker);
225             return newInvoker
226             
227         ]
228     }
229 }
230
231 @Data
232 package class RuntimeGeneratedInvoker implements NotificationInvoker {
233
234     @Property
235     val NotificationListener delegate;
236
237     @Property
238     var org.opendaylight.controller.sal.binding.api.NotificationListener<Notification> invocationProxy;
239
240     @Property
241     var RuntimeGeneratedInvokerPrototype prototype;
242
243     new(NotificationListener delegate, RuntimeGeneratedInvokerPrototype prototype) {
244         _delegate = delegate;
245         _prototype = prototype;
246         _invocationProxy = prototype.protoClass.newInstance as org.opendaylight.controller.sal.binding.api.NotificationListener<Notification>;
247         RuntimeCodeHelper.setDelegate(_invocationProxy, delegate);
248     }
249
250     override getSupportedNotifications() {
251         prototype.supportedNotifications;
252     }
253
254     override close() {
255     }
256 }
257
258 @Data
259 package class RuntimeGeneratedInvokerPrototype {
260
261     @Property
262     val Set<Class<? extends Notification>> supportedNotifications;
263
264     @Property
265     val Class<? extends org.opendaylight.controller.sal.binding.api.NotificationListener<?>> protoClass;
266 }
267
268 package class RpcServiceMetadata {
269
270     @Property
271     val contexts = new HashSet<Class<? extends BaseIdentity>>();
272
273     @Property
274     val rpcMethods = new HashMap<String, RpcMetadata>();
275     
276     @Property
277     val rpcInputs = new HashMap<Class<? extends DataContainer>, RpcMetadata>();
278     
279     
280     @Property
281     val supportedInputs = new HashSet<Class<? extends DataContainer>>();
282 }
283
284 @Data
285 package class RpcMetadata {
286
287     @Property
288     val QName qname;
289
290     @Property
291     val String methodName;
292
293     @Property
294     val Class<? extends BaseIdentity> context;
295     @Property
296     val CtMethod inputRouteGetter;
297
298     @Property
299     val boolean routeEncapsulated;
300     
301     @Property
302     val CtClass inputType;
303 }