1"""
2An example how to generate java code from textX model using jinja2
3template engine (http://jinja.pocoo.org/docs/dev/)
4"""
5from os import mkdir
6from os.path import exists, dirname, join
7import jinja2
8from entity_test import get_entity_mm
9
10
11def main(debug=False):
12
13    this_folder = dirname(__file__)
14
15    entity_mm = get_entity_mm(debug)
16
17    # Build Person model from person.ent file
18    person_model = entity_mm.model_from_file(join(this_folder, 'person.ent'))
19
20    def javatype(s):
21        """
22        Maps type names from PrimitiveType to Java.
23        """
24        return {
25            'integer': 'int',
26            'string': 'String'
27        }.get(s.name, s.name)
28
29    # Create output folder
30    srcgen_folder = join(this_folder, 'srcgen')
31    if not exists(srcgen_folder):
32        mkdir(srcgen_folder)
33
34    # Initialize template engine.
35    jinja_env = jinja2.Environment(
36        loader=jinja2.FileSystemLoader(this_folder),
37        trim_blocks=True,
38        lstrip_blocks=True)
39
40    # Register filter for mapping Entity type names to Java type names.
41    jinja_env.filters['javatype'] = javatype
42
43    # Load Java template
44    template = jinja_env.get_template('java.template')
45
46    for entity in person_model.entities:
47        # For each entity generate java file
48        with open(join(srcgen_folder,
49                       "%s.java" % entity.name.capitalize()), 'w') as f:
50            f.write(template.render(entity=entity))
51
52
53if __name__ == "__main__":
54    main()
55