3 # Copyright (c) 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:
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 from string import Template
18 from jvpp_common_gen import generate_hash_code, generate_equals, generate_to_string, generate_fields
19 from jvpp_model import Union
22 def generate_unions(work_dir, model, logger):
23 logger.debug("Generating unions for %s " % model.json_api_files)
26 if not isinstance(t, Union):
28 logger.debug("Generating DTO for union %s", t)
29 java_union_name = t.java_name
31 type_class = _UNION_TEMPLATE.substitute(
32 plugin_package=model.plugin_package,
34 json_filename=model.json_api_files,
35 json_definition=t.doc,
36 java_union_name=java_union_name,
37 fields=generate_fields(fields, access_modifier="private"),
38 constructors=_generate_constructors(java_union_name, fields),
39 getters=_generate_getters(fields),
40 hash_code=generate_hash_code(fields),
41 equals=generate_equals(java_union_name, fields),
42 to_string=generate_to_string(java_union_name, fields)
44 with open("%s/%s.java" % (work_dir, java_union_name), "w") as f:
47 _UNION_TEMPLATE = Template("""
48 package ${plugin_package}.types;
51 * <p>This class represents ${c_type_name} union definition.
52 * <br>It was generated by unions_gen.py based on ${json_filename}:
57 public class ${java_union_name} {
58 private final int _activeMember;
60 private ${java_union_name}() {
61 // Constructor for JNI usage. All members can be read.
73 def _generate_constructors(union_name, fields):
76 .substitute(union_name=union_name,
77 field_type=f.type.java_name_fqn,
78 field_name=f.java_name,
79 field_index=i) for i, f in enumerate(fields))
81 _CONSTRUCTOR_TEMPLATE = Template("""
82 public ${union_name}(${field_type} ${field_name}) {
83 this.${field_name} = java.util.Objects.requireNonNull(${field_name}, "${field_name} should not be null");
84 _activeMember = $field_index;
88 def _generate_getters(fields):
89 return "".join(_GETTER_TEMPLATE.substitute(
90 type=f.type.java_name_fqn,
91 getter_name=f.java_name_upper,
92 field_name=f.java_name
95 _GETTER_TEMPLATE = Template("""
96 public ${type} get${getter_name}() {