jvpp: add support for enums (VPP-1153)
[vpp.git] / src / vpp-api / java / jvpp / gen / jvppgen / enums_gen.py
1 #!/usr/bin/env python2
2 #
3 # Copyright (c) 2016,2018 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 from string import Template
16
17 from jvpp_model import Enum
18
19
20 def generate_enums(work_dir, model, logger):
21     logger.debug("Generating enums for %s " % model.json_api_files)
22
23     for t in model.types:
24         if not isinstance(t, Enum):
25             continue
26         logger.debug("Generating DTO for enum %s", t)
27         type_class_name = t.java_name
28         type_class = _ENUM_TEMPLATE.substitute(
29             plugin_package=model.plugin_package,
30             c_type_name=t.name,
31             json_filename=model.json_api_files,
32             json_definition=t.doc,
33             java_enum_name=type_class_name,
34             constants=_generate_constants(t.constants),
35             value_type=t.value.type.java_name
36         )
37         with open("%s/%s.java" % (work_dir, type_class_name), "w") as f:
38             f.write(type_class)
39
40 _ENUM_TEMPLATE = Template("""
41 package $plugin_package.types;
42
43 /**
44  * <p>This class represents $c_type_name enum definition.
45  * <br>It was generated by enums_gen.py based on $json_filename:
46  * <pre>
47 $json_definition
48  * </pre>
49  */
50 public enum $java_enum_name {
51 $constants;
52
53     public final $value_type value;
54
55     $java_enum_name(final $value_type value) {
56         this.value = value;
57     }
58     
59     public static $java_enum_name forValue(final $value_type value) {
60         for ($java_enum_name enumeration : $java_enum_name.values()) {
61             if (value == enumeration.value) {
62                 return enumeration;
63             }
64         }
65         return null;
66     }
67 }
68 """)
69
70
71 def _generate_constants(constants):
72     return ",\n".join(_CONSTANT_TEMPLATE.substitute(name=c['name'], value=c['value']) for c in constants)
73
74 _CONSTANT_TEMPLATE = Template("""    $name($value)""")