File: java_codegen.py

package info (click to toggle)
python-schema-salad 3.0.20181206233650-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 3,904 kB
  • sloc: python: 6,672; makefile: 181; sh: 6
file content (162 lines) | stat: -rw-r--r-- 5,740 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""Work-in-progress Java code generator for a given schema salad definition."""
import os
from typing import MutableSequence

from six import string_types
from six.moves import cStringIO, urllib
from typing_extensions import Text  # pylint: disable=unused-import
# move to a regular typing import when Python 3.3-3.6 is no longer supported

from . import schema
from .codegen_base import CodeGenBase, TypeDef


class JavaCodeGen(CodeGenBase):
    def __init__(self, base):
        # type: (Text) -> None

        super(JavaCodeGen, self).__init__()
        sp = urllib.parse.urlsplit(base)
        self.package = ".".join(list(reversed(sp.netloc.split("."))) + sp.path.strip("/").split("/"))
        self.outdir = self.package.replace(".", "/")

    def prologue(self):  # type: () -> None
        if not os.path.exists(self.outdir):
            os.makedirs(self.outdir)

    @staticmethod
    def safe_name(name):  # type: (Text) -> Text
        avn = schema.avro_name(name)
        if avn in ("class", "extends", "abstract"):
            # reserved words
            avn = avn+"_"
        return avn

    def interface_name(self, n):
        # type: (Text) -> Text
        return self.safe_name(n)

    def begin_class(self,
                    classname,    # type: Text
                    extends,      # type: MutableSequence[Text]
                    doc,          # type: Text
                    abstract,     # type: bool
                    field_names,  # type: MutableSequence[Text]
                    idfield       # type: Text
                   ):  # type: (...) -> None
        cls = self.interface_name(classname)
        self.current_class = cls
        self.current_class_is_abstract = abstract
        self.current_loader = cStringIO()
        self.current_fields = cStringIO()
        with open(os.path.join(self.outdir, "%s.java" % cls), "w") as f:
            if extends:
                ext = "extends " + ", ".join(self.interface_name(e) for e in extends)
            else:
                ext = ""
            f.write("""package {package};

public interface {cls} {ext} {{
""".
                    format(package=self.package,
                           cls=cls,
                           ext=ext))

        if self.current_class_is_abstract:
            return

        with open(os.path.join(self.outdir, "%sImpl.java" % cls), "w") as f:
            f.write("""package {package};

public class {cls}Impl implements {cls} {{
""".
                    format(package=self.package,
                           cls=cls,
                           ext=ext))
        self.current_loader.write("""
    void Load() {
""")

    def end_class(self, classname, field_names):
        with open(os.path.join(self.outdir, "%s.java" % self.current_class), "a") as f:
            f.write("""
}
""")
        if self.current_class_is_abstract:
            return

        self.current_loader.write("""
    }
""")

        with open(os.path.join(self.outdir, "%sImpl.java" % self.current_class), "a") as f:
            f.write(self.current_fields.getvalue())
            f.write(self.current_loader.getvalue())
            f.write("""
}
""")

    prims = {
        u"http://www.w3.org/2001/XMLSchema#string": TypeDef("String", "Support.StringLoader()"),
        u"http://www.w3.org/2001/XMLSchema#int": TypeDef("Integer", "Support.IntLoader()"),
        u"http://www.w3.org/2001/XMLSchema#long": TypeDef("Long", "Support.LongLoader()"),
        u"http://www.w3.org/2001/XMLSchema#float": TypeDef("Float", "Support.FloatLoader()"),
        u"http://www.w3.org/2001/XMLSchema#double": TypeDef("Double", "Support.DoubleLoader()"),
        u"http://www.w3.org/2001/XMLSchema#boolean": TypeDef("Boolean", "Support.BoolLoader()"),
        u"https://w3id.org/cwl/salad#null": TypeDef("null_type", "Support.NullLoader()"),
        u"https://w3id.org/cwl/salad#Any": TypeDef("Any_type", "Support.AnyLoader()")
    }

    def type_loader(self, type_declaration):
        if isinstance(type_declaration, MutableSequence) and len(type_declaration) == 2:
            if type_declaration[0] == "https://w3id.org/cwl/salad#null":
                type_declaration = type_declaration[1]
        if isinstance(type_declaration, string_types):
            if type_declaration in self.prims:
                return self.prims[type_declaration]
        return TypeDef("Object", "")

    def declare_field(self, name, fieldtype, doc, optional):
        fieldname = self.safe_name(name)
        with open(os.path.join(self.outdir, "%s.java" % self.current_class), "a") as f:
            f.write("""
    {type} get{capfieldname}();
""".
                    format(fieldname=fieldname,
                           capfieldname=fieldname[0].upper() + fieldname[1:],
                           type=fieldtype.name))

        if self.current_class_is_abstract:
            return

        self.current_fields.write("""
    private {type} {fieldname};
    public {type} get{capfieldname}() {{
        return this.{fieldname};
    }}
""".
                    format(fieldname=fieldname,
                           capfieldname=fieldname[0].upper() + fieldname[1:],
                           type=fieldtype.name))

        self.current_loader.write("""
        this.{fieldname} = null; // TODO: loaders
        """.
                                  format(fieldname=fieldname))


    def declare_id_field(self, name, fieldtype, doc, optional):
        pass

    def uri_loader(self, inner, scoped_id, vocab_term, ref_scope):
        return inner

    def idmap_loader(self, field, inner, map_subject, map_predicate):
        return inner

    def typedsl_loader(self, inner, ref_scope):
        return inner

    def epilogue(self, root_loader):

        pass