jvpp: adding callbacks for all messages (VPP-914)
[vpp.git] / src / vpp-api / java / jvpp / gen / jvppgen / jvpp_callback_facade_gen.py
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2016 Cisco and/or its affiliates.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import os, util
17 from string import Template
18
19 import callback_gen
20 import dto_gen
21
22 jvpp_ifc_template = Template("""
23 package $plugin_package.$callback_facade_package;
24
25 /**
26  * <p>Callback Java API representation of $plugin_package plugin.
27  * <br>It was generated by jvpp_callback_facade_gen.py based on $inputfile
28  * <br>(python representation of api file generated by vppapigen).
29  */
30 public interface CallbackJVpp${plugin_name} extends $base_package.$notification_package.EventRegistryProvider, java.lang.AutoCloseable {
31
32     // TODO add send
33
34 $methods
35 }
36 """)
37
38 jvpp_impl_template = Template("""
39 package $plugin_package.$callback_facade_package;
40
41 /**
42  * <p>Default implementation of Callback${plugin_name}JVpp interface.
43  * <br>It was generated by jvpp_callback_facade_gen.py based on $inputfile
44  * <br>(python representation of api file generated by vppapigen).
45  */
46 public final class CallbackJVpp${plugin_name}Facade implements CallbackJVpp${plugin_name} {
47
48     private final $plugin_package.JVpp${plugin_name} jvpp;
49     private final java.util.Map<Integer, $base_package.$callback_package.JVppCallback> callbacks;
50     private final $plugin_package.$notification_package.${plugin_name}EventRegistryImpl eventRegistry = new $plugin_package.$notification_package.${plugin_name}EventRegistryImpl();
51     /**
52      * <p>Create CallbackJVpp${plugin_name}Facade object for provided JVpp instance.
53      * Constructor internally creates CallbackJVppFacadeCallback class for processing callbacks
54      * and then connects to provided JVpp instance
55      *
56      * @param jvpp provided $base_package.JVpp instance
57      *
58      * @throws java.io.IOException in case instance cannot connect to JVPP
59      */
60     public CallbackJVpp${plugin_name}Facade(final $base_package.JVppRegistry registry, final $plugin_package.JVpp${plugin_name} jvpp) throws java.io.IOException {
61         this.jvpp = java.util.Objects.requireNonNull(jvpp,"jvpp is null");
62         this.callbacks = new java.util.HashMap<>();
63         java.util.Objects.requireNonNull(registry, "JVppRegistry should not be null");
64         registry.register(jvpp, new CallbackJVpp${plugin_name}FacadeCallback(this.callbacks, eventRegistry));
65     }
66
67     @Override
68     public $plugin_package.$notification_package.${plugin_name}EventRegistry getEventRegistry() {
69         return eventRegistry;
70     }
71
72     @Override
73     public void close() throws Exception {
74         jvpp.close();
75     }
76
77     // TODO add send()
78
79 $methods
80 }
81 """)
82
83 method_template = Template(
84     """    void $name($plugin_package.$dto_package.$request request, $plugin_package.$callback_package.$callback callback) throws $base_package.VppInvocationException;""")
85
86 method_impl_template = Template("""    public final void $name($plugin_package.$dto_package.$request request, $plugin_package.$callback_package.$callback callback) throws $base_package.VppInvocationException {
87         synchronized (callbacks) {
88             callbacks.put(jvpp.$name(request), callback);
89         }
90     }
91 """)
92
93 no_arg_method_template = Template("""    void $name($plugin_package.$callback_package.$callback callback) throws $base_package.VppInvocationException;""")
94 no_arg_method_impl_template = Template("""    public final void $name($plugin_package.$callback_package.$callback callback) throws $base_package.VppInvocationException {
95         synchronized (callbacks) {
96             callbacks.put(jvpp.$name(), callback);
97         }
98     }
99 """)
100
101
102 def generate_jvpp(func_list, base_package, plugin_package, plugin_name, dto_package, callback_package, notification_package, callback_facade_package, inputfile):
103     """ Generates callback facade """
104     print "Generating JVpp callback facade"
105
106     if os.path.exists(callback_facade_package):
107         util.remove_folder(callback_facade_package)
108
109     os.mkdir(callback_facade_package)
110
111     methods = []
112     methods_impl = []
113     for func in func_list:
114
115         if util.is_notification(func['name']) or util.is_ignored(func['name']):
116             continue
117
118         camel_case_name = util.underscore_to_camelcase(func['name'])
119         camel_case_name_upper = util.underscore_to_camelcase_upper(func['name'])
120         if util.is_reply(camel_case_name) or util.is_control_ping(camel_case_name):
121             continue
122
123         # Strip suffix for dump calls
124         callback_type = get_request_name(camel_case_name_upper, func['name'])
125         if (util.is_dump(camel_case_name_upper)):
126             callback_type += "Details"
127         elif (not util.is_notification(camel_case_name_upper)):
128             callback_type += "Reply"
129         callback_type += callback_gen.callback_suffix
130
131         if len(func['args']) == 0:
132             methods.append(no_arg_method_template.substitute(name=camel_case_name,
133                                                              base_package=base_package,
134                                                              plugin_package=plugin_package,
135                                                              dto_package=dto_package,
136                                                              callback_package=callback_package,
137                                                              callback=callback_type))
138             methods_impl.append(no_arg_method_impl_template.substitute(name=camel_case_name,
139                                                                        base_package=base_package,
140                                                                        plugin_package=plugin_package,
141                                                                        dto_package=dto_package,
142                                                                        callback_package=callback_package,
143                                                                        callback=callback_type))
144         else:
145             methods.append(method_template.substitute(name=camel_case_name,
146                                                       request=camel_case_name_upper,
147                                                       base_package=base_package,
148                                                       plugin_package=plugin_package,
149                                                       dto_package=dto_package,
150                                                       callback_package=callback_package,
151                                                       callback=callback_type))
152             methods_impl.append(method_impl_template.substitute(name=camel_case_name,
153                                                                 request=camel_case_name_upper,
154                                                                 base_package=base_package,
155                                                                 plugin_package=plugin_package,
156                                                                 dto_package=dto_package,
157                                                                 callback_package=callback_package,
158                                                                 callback=callback_type))
159
160     join = os.path.join(callback_facade_package, "CallbackJVpp%s.java" % plugin_name)
161     jvpp_file = open(join, 'w')
162     jvpp_file.write(
163         jvpp_ifc_template.substitute(inputfile=inputfile,
164                                      methods="\n".join(methods),
165                                      base_package=base_package,
166                                      plugin_package=plugin_package,
167                                      plugin_name=plugin_name,
168                                      dto_package=dto_package,
169                                      notification_package=notification_package,
170                                      callback_facade_package=callback_facade_package))
171     jvpp_file.flush()
172     jvpp_file.close()
173
174     jvpp_file = open(os.path.join(callback_facade_package, "CallbackJVpp%sFacade.java" % plugin_name), 'w')
175     jvpp_file.write(jvpp_impl_template.substitute(inputfile=inputfile,
176                                                   methods="\n".join(methods_impl),
177                                                   base_package=base_package,
178                                                   plugin_package=plugin_package,
179                                                   plugin_name=plugin_name,
180                                                   dto_package=dto_package,
181                                                   notification_package=notification_package,
182                                                   callback_package=callback_package,
183                                                   callback_facade_package=callback_facade_package))
184     jvpp_file.flush()
185     jvpp_file.close()
186
187     generate_callback(func_list, base_package, plugin_package, plugin_name, dto_package, callback_package, notification_package, callback_facade_package, inputfile)
188
189
190 jvpp_facade_callback_template = Template("""
191 package $plugin_package.$callback_facade_package;
192
193 /**
194  * <p>Implementation of JVppGlobalCallback interface for Java Callback API.
195  * <br>It was generated by jvpp_callback_facade_gen.py based on $inputfile
196  * <br>(python representation of api file generated by vppapigen).
197  */
198 public final class CallbackJVpp${plugin_name}FacadeCallback implements $plugin_package.$callback_package.JVpp${plugin_name}GlobalCallback {
199
200     private final java.util.Map<Integer, $base_package.$callback_package.JVppCallback> requests;
201     private final $plugin_package.$notification_package.Global${plugin_name}EventCallback eventCallback;
202     private static final java.util.logging.Logger LOG = java.util.logging.Logger.getLogger(CallbackJVpp${plugin_name}FacadeCallback.class.getName());
203
204     public CallbackJVpp${plugin_name}FacadeCallback(final java.util.Map<Integer, $base_package.$callback_package.JVppCallback> requestMap,
205                                       final $plugin_package.$notification_package.Global${plugin_name}EventCallback eventCallback) {
206         this.requests = requestMap;
207         this.eventCallback = eventCallback;
208     }
209
210     @Override
211     public void onError($base_package.VppCallbackException reply) {
212
213         $base_package.$callback_package.JVppCallback failedCall;
214         synchronized(requests) {
215             failedCall = requests.remove(reply.getCtxId());
216         }
217
218         if(failedCall != null) {
219             try {
220                 failedCall.onError(reply);
221             } catch(RuntimeException ex) {
222                 ex.addSuppressed(reply);
223                 LOG.log(java.util.logging.Level.WARNING, String.format("Callback: %s failed while handling exception: %s", failedCall, reply), ex);
224             }
225         }
226     }
227
228     @Override
229     @SuppressWarnings("unchecked")
230     public void onControlPingReply(final $base_package.$dto_package.ControlPingReply reply) {
231
232         $base_package.$callback_package.ControlPingCallback callback;
233         final int replyId = reply.context;
234         synchronized(requests) {
235             callback = ($base_package.$callback_package.ControlPingCallback) requests.remove(replyId);
236         }
237
238         if(callback != null) {
239             callback.onControlPingReply(reply);
240         }
241     }
242
243 $methods
244 }
245 """)
246
247 jvpp_facade_callback_method_template = Template("""
248     @Override
249     @SuppressWarnings("unchecked")
250     public void on$callback_dto(final $plugin_package.$dto_package.$callback_dto reply) {
251
252         $plugin_package.$callback_package.$callback callback;
253         final int replyId = reply.context;
254         if (LOG.isLoggable(java.util.logging.Level.FINE)) {
255             LOG.fine(String.format("Received $callback_dto event message: %s", reply));
256         }
257         synchronized(requests) {
258             callback = ($plugin_package.$callback_package.$callback) requests.remove(replyId);
259         }
260
261         if(callback != null) {
262             callback.on$callback_dto(reply);
263         }
264     }
265 """)
266
267 jvpp_facade_callback_notification_method_template = Template("""
268     @Override
269     @SuppressWarnings("unchecked")
270     public void on$callback_dto($plugin_package.$dto_package.$callback_dto notification) {
271         if (LOG.isLoggable(java.util.logging.Level.FINE)) {
272             LOG.fine(String.format("Received $callback_dto event message: %s", notification));
273         }
274         eventCallback.on$callback_dto(notification);
275     }
276 """)
277
278
279 def generate_callback(func_list, base_package, plugin_package, plugin_name, dto_package, callback_package, notification_package, callback_facade_package, inputfile):
280     callbacks = []
281     for func in func_list:
282
283         camel_case_name_with_suffix = util.underscore_to_camelcase_upper(func['name'])
284
285         if util.is_ignored(func['name']) or util.is_control_ping(camel_case_name_with_suffix):
286             continue
287
288         if util.is_reply(camel_case_name_with_suffix):
289             request_method = camel_case_name_with_suffix
290             callbacks.append(jvpp_facade_callback_method_template.substitute(plugin_package=plugin_package,
291                                                                              dto_package=dto_package,
292                                                                              callback_package=callback_package,
293                                                                              callback=camel_case_name_with_suffix + callback_gen.callback_suffix,
294                                                                              callback_dto=request_method))
295
296         if util.is_notification(func["name"]):
297             callbacks.append(jvpp_facade_callback_notification_method_template.substitute(plugin_package=plugin_package,
298                                                                              dto_package=dto_package,
299                                                                              callback_package=callback_package,
300                                                                              callback=camel_case_name_with_suffix + callback_gen.callback_suffix,
301                                                                              callback_dto=camel_case_name_with_suffix))
302
303     jvpp_file = open(os.path.join(callback_facade_package, "CallbackJVpp%sFacadeCallback.java" % plugin_name), 'w')
304     jvpp_file.write(jvpp_facade_callback_template.substitute(inputfile=inputfile,
305                                                              base_package=base_package,
306                                                              plugin_package=plugin_package,
307                                                              plugin_name=plugin_name,
308                                                              dto_package=dto_package,
309                                                              notification_package=notification_package,
310                                                              callback_package=callback_package,
311                                                              methods="".join(callbacks),
312                                                              callback_facade_package=callback_facade_package))
313     jvpp_file.flush()
314     jvpp_file.close()
315
316
317 # Returns request name or special one from unconventional_naming_rep_req map
318 def get_request_name(camel_case_dto_name, func_name):
319     if func_name in reverse_dict(util.unconventional_naming_rep_req):
320         request_name = util.underscore_to_camelcase_upper(reverse_dict(util.unconventional_naming_rep_req)[func_name])
321     else:
322         request_name = camel_case_dto_name
323     return remove_suffix(request_name)
324
325
326 def reverse_dict(map):
327     return dict((v, k) for k, v in map.iteritems())
328
329
330 def remove_suffix(name):
331     if util.is_reply(name):
332         return util.remove_reply_suffix(name)
333     else:
334         if util.is_dump(name):
335             return util.remove_suffix(name, util.dump_suffix)
336         else:
337             return name