jvpp: use Python's logging API
[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
21 jvpp_ifc_template = Template("""
22 package $plugin_package.$callback_facade_package;
23
24 /**
25  * <p>Callback Java API representation of $plugin_package plugin.
26  * <br>It was generated by jvpp_callback_facade_gen.py based on $inputfile
27  * <br>(python representation of api file generated by vppapigen).
28  */
29 public interface CallbackJVpp${plugin_name} extends $base_package.$notification_package.EventRegistryProvider, java.lang.AutoCloseable {
30
31     // TODO add send
32
33 $methods
34 }
35 """)
36
37 jvpp_impl_template = Template("""
38 package $plugin_package.$callback_facade_package;
39
40 /**
41  * <p>Default implementation of Callback${plugin_name}JVpp interface.
42  * <br>It was generated by jvpp_callback_facade_gen.py based on $inputfile
43  * <br>(python representation of api file generated by vppapigen).
44  */
45 public final class CallbackJVpp${plugin_name}Facade implements CallbackJVpp${plugin_name} {
46
47     private final $plugin_package.JVpp${plugin_name} jvpp;
48     private final java.util.Map<Integer, $base_package.$callback_package.JVppCallback> callbacks;
49     private final $plugin_package.$notification_package.${plugin_name}EventRegistryImpl eventRegistry = new $plugin_package.$notification_package.${plugin_name}EventRegistryImpl();
50     /**
51      * <p>Create CallbackJVpp${plugin_name}Facade object for provided JVpp instance.
52      * Constructor internally creates CallbackJVppFacadeCallback class for processing callbacks
53      * and then connects to provided JVpp instance
54      *
55      * @param jvpp provided $base_package.JVpp instance
56      *
57      * @throws java.io.IOException in case instance cannot connect to JVPP
58      */
59     public CallbackJVpp${plugin_name}Facade(final $base_package.JVppRegistry registry, final $plugin_package.JVpp${plugin_name} jvpp) throws java.io.IOException {
60         this.jvpp = java.util.Objects.requireNonNull(jvpp,"jvpp is null");
61         this.callbacks = new java.util.HashMap<>();
62         java.util.Objects.requireNonNull(registry, "JVppRegistry should not be null");
63         registry.register(jvpp, new CallbackJVpp${plugin_name}FacadeCallback(this.callbacks, eventRegistry));
64     }
65
66     @Override
67     public $plugin_package.$notification_package.${plugin_name}EventRegistry getEventRegistry() {
68         return eventRegistry;
69     }
70
71     @Override
72     public void close() throws Exception {
73         jvpp.close();
74     }
75
76     // TODO add send()
77
78 $methods
79 }
80 """)
81
82 method_template = Template(
83     """    void $name($plugin_package.$dto_package.$request request, $plugin_package.$callback_package.$callback callback) throws $base_package.VppInvocationException;""")
84
85 method_impl_template = Template("""    public final void $name($plugin_package.$dto_package.$request request, $plugin_package.$callback_package.$callback callback) throws $base_package.VppInvocationException {
86         synchronized (callbacks) {
87             callbacks.put(jvpp.$name(request), callback);
88         }
89     }
90 """)
91
92 no_arg_method_template = Template("""    void $name($plugin_package.$callback_package.$callback callback) throws $base_package.VppInvocationException;""")
93 no_arg_method_impl_template = Template("""    public final void $name($plugin_package.$callback_package.$callback callback) throws $base_package.VppInvocationException {
94         synchronized (callbacks) {
95             callbacks.put(jvpp.$name(), callback);
96         }
97     }
98 """)
99
100
101 def generate_jvpp(func_list, base_package, plugin_package, plugin_name, dto_package, callback_package,
102                   notification_package, callback_facade_package, inputfile, logger):
103     """ Generates callback facade """
104     logger.debug("Generating JVpp callback facade for %s" % inputfile)
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
114     # Generate methods for sending messages.
115     for func in func_list:
116         camel_case_name = util.underscore_to_camelcase(func['name'])
117         camel_case_name_upper = util.underscore_to_camelcase_upper(func['name'])
118         if util.is_reply(camel_case_name) or util.is_control_ping(camel_case_name):
119             continue
120
121         # Strip suffix for dump calls
122         callback_type = get_request_name(camel_case_name_upper)
123         if util.is_dump(camel_case_name_upper):
124             callback_type += "Details"
125         elif util.is_request(func['name'], func_list):
126             callback_type += "Reply"
127         else:
128             # Skip messages that do not not have replies (e.g events/counters).
129             continue
130         callback_type += callback_gen.callback_suffix
131
132         if len(func['args']) == 0:
133             methods.append(no_arg_method_template.substitute(name=camel_case_name,
134                                                              base_package=base_package,
135                                                              plugin_package=plugin_package,
136                                                              dto_package=dto_package,
137                                                              callback_package=callback_package,
138                                                              callback=callback_type))
139             methods_impl.append(no_arg_method_impl_template.substitute(name=camel_case_name,
140                                                                        base_package=base_package,
141                                                                        plugin_package=plugin_package,
142                                                                        dto_package=dto_package,
143                                                                        callback_package=callback_package,
144                                                                        callback=callback_type))
145         else:
146             methods.append(method_template.substitute(name=camel_case_name,
147                                                       request=camel_case_name_upper,
148                                                       base_package=base_package,
149                                                       plugin_package=plugin_package,
150                                                       dto_package=dto_package,
151                                                       callback_package=callback_package,
152                                                       callback=callback_type))
153             methods_impl.append(method_impl_template.substitute(name=camel_case_name,
154                                                                 request=camel_case_name_upper,
155                                                                 base_package=base_package,
156                                                                 plugin_package=plugin_package,
157                                                                 dto_package=dto_package,
158                                                                 callback_package=callback_package,
159                                                                 callback=callback_type))
160
161     join = os.path.join(callback_facade_package, "CallbackJVpp%s.java" % plugin_name)
162     jvpp_file = open(join, 'w')
163     jvpp_file.write(
164         jvpp_ifc_template.substitute(inputfile=inputfile,
165                                      methods="\n".join(methods),
166                                      base_package=base_package,
167                                      plugin_package=plugin_package,
168                                      plugin_name=plugin_name,
169                                      dto_package=dto_package,
170                                      notification_package=notification_package,
171                                      callback_facade_package=callback_facade_package))
172     jvpp_file.flush()
173     jvpp_file.close()
174
175     jvpp_file = open(os.path.join(callback_facade_package, "CallbackJVpp%sFacade.java" % plugin_name), 'w')
176     jvpp_file.write(jvpp_impl_template.substitute(inputfile=inputfile,
177                                                   methods="\n".join(methods_impl),
178                                                   base_package=base_package,
179                                                   plugin_package=plugin_package,
180                                                   plugin_name=plugin_name,
181                                                   dto_package=dto_package,
182                                                   notification_package=notification_package,
183                                                   callback_package=callback_package,
184                                                   callback_facade_package=callback_facade_package))
185     jvpp_file.flush()
186     jvpp_file.close()
187
188     generate_callback(func_list, base_package, plugin_package, plugin_name, dto_package, callback_package, notification_package, callback_facade_package, inputfile)
189
190
191 jvpp_facade_callback_template = Template("""
192 package $plugin_package.$callback_facade_package;
193
194 /**
195  * <p>Implementation of JVppGlobalCallback interface for Java Callback API.
196  * <br>It was generated by jvpp_callback_facade_gen.py based on $inputfile
197  * <br>(python representation of api file generated by vppapigen).
198  */
199 public final class CallbackJVpp${plugin_name}FacadeCallback implements $plugin_package.$callback_package.JVpp${plugin_name}GlobalCallback {
200
201     private final java.util.Map<Integer, $base_package.$callback_package.JVppCallback> requests;
202     private final $plugin_package.$notification_package.Global${plugin_name}EventCallback eventCallback;
203     private static final java.util.logging.Logger LOG = java.util.logging.Logger.getLogger(CallbackJVpp${plugin_name}FacadeCallback.class.getName());
204
205     public CallbackJVpp${plugin_name}FacadeCallback(final java.util.Map<Integer, $base_package.$callback_package.JVppCallback> requestMap,
206                                       final $plugin_package.$notification_package.Global${plugin_name}EventCallback eventCallback) {
207         this.requests = requestMap;
208         this.eventCallback = eventCallback;
209     }
210
211     @Override
212     public void onError($base_package.VppCallbackException reply) {
213
214         $base_package.$callback_package.JVppCallback failedCall;
215         synchronized(requests) {
216             failedCall = requests.remove(reply.getCtxId());
217         }
218
219         if(failedCall != null) {
220             try {
221                 failedCall.onError(reply);
222             } catch(RuntimeException ex) {
223                 ex.addSuppressed(reply);
224                 LOG.log(java.util.logging.Level.WARNING, String.format("Callback: %s failed while handling exception: %s", failedCall, reply), ex);
225             }
226         }
227     }
228
229     @Override
230     @SuppressWarnings("unchecked")
231     public void onControlPingReply(final $base_package.$dto_package.ControlPingReply reply) {
232
233         $base_package.$callback_package.ControlPingCallback callback;
234         final int replyId = reply.context;
235         synchronized(requests) {
236             callback = ($base_package.$callback_package.ControlPingCallback) requests.remove(replyId);
237         }
238
239         if(callback != null) {
240             callback.onControlPingReply(reply);
241         }
242     }
243
244 $methods
245 }
246 """)
247
248 jvpp_facade_callback_method_template = Template("""
249     @Override
250     @SuppressWarnings("unchecked")
251     public void on$callback_dto(final $plugin_package.$dto_package.$callback_dto reply) {
252
253         $plugin_package.$callback_package.$callback callback;
254         final int replyId = reply.context;
255         if (LOG.isLoggable(java.util.logging.Level.FINE)) {
256             LOG.fine(String.format("Received $callback_dto event message: %s", reply));
257         }
258         synchronized(requests) {
259             callback = ($plugin_package.$callback_package.$callback) requests.remove(replyId);
260         }
261
262         if(callback != null) {
263             callback.on$callback_dto(reply);
264         }
265     }
266 """)
267
268 jvpp_facade_callback_notification_method_template = Template("""
269     @Override
270     @SuppressWarnings("unchecked")
271     public void on$callback_dto($plugin_package.$dto_package.$callback_dto notification) {
272         if (LOG.isLoggable(java.util.logging.Level.FINE)) {
273             LOG.fine(String.format("Received $callback_dto event message: %s", notification));
274         }
275         eventCallback.on$callback_dto(notification);
276     }
277 """)
278
279
280 def generate_callback(func_list, base_package, plugin_package, plugin_name, dto_package, callback_package, notification_package, callback_facade_package, inputfile):
281     callbacks = []
282     for func in func_list:
283         camel_case_name_with_suffix = util.underscore_to_camelcase_upper(func['name'])
284
285         if util.is_control_ping(camel_case_name_with_suffix):
286             # Skip control ping managed by jvpp registry.
287             continue
288         if util.is_dump(func['name']) or util.is_request(func['name'], func_list):
289             continue
290
291         # Generate callbacks for all messages except for dumps and requests (handled by vpp, not client).
292         if util.is_reply(camel_case_name_with_suffix):
293             request_method = camel_case_name_with_suffix
294             callbacks.append(jvpp_facade_callback_method_template.substitute(plugin_package=plugin_package,
295                                                                              dto_package=dto_package,
296                                                                              callback_package=callback_package,
297                                                                              callback=camel_case_name_with_suffix + callback_gen.callback_suffix,
298                                                                              callback_dto=request_method))
299         else:
300             callbacks.append(jvpp_facade_callback_notification_method_template.substitute(plugin_package=plugin_package,
301                                                                                           dto_package=dto_package,
302                                                                                           callback_package=callback_package,
303                                                                                           callback=camel_case_name_with_suffix + callback_gen.callback_suffix,
304                                                                                           callback_dto=camel_case_name_with_suffix))
305
306     jvpp_file = open(os.path.join(callback_facade_package, "CallbackJVpp%sFacadeCallback.java" % plugin_name), 'w')
307     jvpp_file.write(jvpp_facade_callback_template.substitute(inputfile=inputfile,
308                                                              base_package=base_package,
309                                                              plugin_package=plugin_package,
310                                                              plugin_name=plugin_name,
311                                                              dto_package=dto_package,
312                                                              notification_package=notification_package,
313                                                              callback_package=callback_package,
314                                                              methods="".join(callbacks),
315                                                              callback_facade_package=callback_facade_package))
316     jvpp_file.flush()
317     jvpp_file.close()
318
319
320 # Returns request name
321 def get_request_name(camel_case_dto_name):
322     return remove_suffix(camel_case_dto_name)
323
324
325 def remove_suffix(name):
326     if util.is_reply(name):
327         return util.remove_reply_suffix(name)
328     else:
329         if util.is_dump(name):
330             return util.remove_suffix(name, util.dump_suffix)
331         else:
332             return name