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