summaryrefslogtreecommitdiff
path: root/java/common/generate
blob: 145e3b66ed1c3b57e39babea3d45d1f3b4812ce6 (plain)
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/python

# Interim code generation script.

import sys, os
from cStringIO import StringIO

sys.path.append("../../python")

import mllib

out_dir=sys.argv[1]
out_pkg = sys.argv[2]
spec_file = sys.argv[3]
spec = mllib.xml_parse(spec_file)
major = spec["amqp/@major"]
minor = spec["amqp/@minor"]
isfx = "_v%s_%s" % (major, minor)

class Output:

  def __init__(self, dir, package, name):
    self.dir = dir
    self.package = package
    self.name = name
    self.lines = []

    self.line("package %s;" % self.package)
    self.line()
    self.line("import java.util.Map;")
    self.line("import java.util.UUID;")
    self.line()
    self.line()

  def line(self, l = ""):
    self.lines.append(l)

  def write(self):
    dir = os.path.join(self.dir, *self.package.split("."))
    if not os.path.exists(dir):
      os.makedirs(dir)
    file = os.path.join(dir, "%s.java" % self.name)
    out = open(file, "w")
    for l in self.lines:
      out.write(l)
      out.write(os.linesep)
    out.close()

TYPES = {
  "longstr": "String",
  "shortstr": "String",
  "longlong": "long",
  "long": "long",
  "short": "int",
  "octet": "short",
  "bit": "boolean",
  "table": "Map<String,?>",
  "timestamp": "long",
  "content": "String",
  "uuid": "UUID",
  "rfc1982-long-set": "Range<Long>[]"
  }

def camel(offset, *args):
  parts = []
  for a in args:
    parts.extend(a.split("-"))
  return "".join(parts[:offset] + [p.capitalize() for p in parts[offset:]])

def dromedary(s):
  return s[0].lower() + s[1:]

def scream(*args):
  return "_".join([a.replace("-", "_").upper() for a in args])

DOMAINS = {}
EXCLUDE = {"access-ticket": True}

for d in spec.query["amqp/domain"]:
  DOMAINS[d["@name"]] = d["@type"]

def resolve(type):
  if DOMAINS.has_key(type) and DOMAINS[type] != type:
    return resolve(DOMAINS[type])
  else:
    return type


OPTIONS = {}

class Struct:

  def __init__(self, type, name):
    self.type = type
    self.name = name
    self.fields = []

  def field(self, type, name):
    self.fields.append((type, name))

  def interface(self, out):
    out.line("public interface %s extends Method {" % self.name)
    out.line()
    out.line("    public static final int TYPE = %d;" % self.type)
    out.line()
    for type, name in self.fields:
      out.line("    %s %s();" % (TYPES[type], camel(1, "get", name)))
    out.line()
    out.line("}")

  def impl(self, out):
    out.line("class %s%s extends AbstractMethod implements %s {" %
             (self.name, isfx, self.name))

    out.line()
    out.line("    public int getEncodedType() {")
    out.line("        return TYPE;")
    out.line("    }")

    out.line()
    for type, name in self.fields:
      out.line("    private final %s %s;" % (TYPES[type], name))

    out.line()
    out.line("    %s%s(Decoder dec) {" % (self.name, isfx))
    for type, name in self.fields:
      out.line("        %s = dec.read%s();" % (name, camel(0, type)))
    out.line("    }")

    out.line()
    out.line("    %s%s(%s) {" % (self.name, isfx, self.parameters()))
    opts = False
    for type, name in self.fields:
      if not OPTIONS.has_key(name):
        out.line("        this.%s = %s;" % (name, name))
      else:
        opts = True
    if opts:
      for type, name in self.fields:
        if OPTIONS.has_key(name):
          out.line("        boolean _%s = false;" % name)
      out.line("        for (int i=0; i < _options.length; i++) {")
      out.line("            switch (_options[i]) {")
      for type, name in self.fields:
        if OPTIONS.has_key(name):
          out.line("            case %s: _%s=true; break;" % (OPTIONS[name], name))
      out.line('            default: throw new IllegalArgumentException'
               '("invalid option: " + _options[i]);')
      out.line("            }")
      out.line("        }")
      for type, name in self.fields:
        if OPTIONS.has_key(name):
          out.line("        this.%s = _%s;" % (name, name))
    out.line("    }")

    out.line()
    out.line("    public <C> void delegate(C context, Delegate<C> delegate) {")
    out.line("        delegate.%s(context, this);" % dromedary(self.name))
    out.line("    }")

    out.line()
    for type, name in self.fields:
      out.line("    public %s %s() {" % (TYPES[type], camel(1, "get", name)))
      out.line("        return %s;" % name)
      out.line("    }")

    out.line()
    out.line("    public void write(Encoder enc) {")
    for type, name in self.fields:
      out.line("        enc.write%s(%s);" % (camel(0, type), name))
    out.line("    }")

    out.line("}")


  def parameters(self):
    params = []
    var = False
    for type, name in self.fields:
      if OPTIONS.has_key(name):
        var = True
      else:
        params.append("%s %s" % (TYPES[type], name))
    if var:
      params.append("Option ... _options")
    return ", ".join(params)

  def arguments(self):
    args = []
    var = False
    for type, name in self.fields:
      if OPTIONS.has_key(name):
        var = True
      else:
        args.append(name)
    if var:
      args.append("_options")
    return ", ".join(args)

CLASSES = {"file": False, "basic": False, "stream": False, "tunnel": False}
FIELDS = {"ticket": False}

opts = Output(out_dir, out_pkg, "Option")
opts.line("public enum Option {")
structs = []
for m in spec.query["amqp/class/method",
                    lambda m: CLASSES.get(m.parent["@name"], True)]:
  struct = Struct(int(m.parent["@index"])*256 + int(m["@index"]),
                  camel(0, m.parent["@name"], m["@name"]))
  for f in m.query["field", lambda f: FIELDS.get(f["@name"], True)]:
    type = resolve(f["@domain"])
    name = camel(1, f["@name"])
    struct.field(type, name)
    if type == "bit":
      opt_name = scream(f["@name"])
      if not OPTIONS.has_key(name):
        OPTIONS[name] = opt_name
        opts.line("    %s," % opt_name)
  structs.append(struct)
opts.line("}")
opts.write()

for s in structs:
  out = Output(out_dir, out_pkg, s.name)
  s.interface(out)
  out.write()
  iout = Output(out_dir, out_pkg, s.name + isfx)
  s.impl(iout)
  iout.write()

fct = Output(out_dir, out_pkg, "StructFactory")
fct.line("public interface StructFactory {")
fct.line("    Struct create(int type, Decoder dec);")
for s in structs:
  fct.line()
  fct.line("    %s new%s(Decoder dec);" % (s.name, s.name))
  fct.line("    %s new%s(%s);" % (s.name, s.name, s.parameters()))
fct.line("}")
fct.write()

ifct_name = "StructFactory%s" % isfx
ifct = Output(out_dir, out_pkg, ifct_name)
ifct.line("class %s implements StructFactory {" % ifct_name)
ifct.line("    public Struct create(int type, Decoder dec) {")
ifct.line("        switch (type) {")
for s in structs:
  ifct.line("        case %s.TYPE:" % s.name)
  ifct.line("            return new %s%s(dec);" % (s.name, isfx))
ifct.line("        default:")
ifct.line('            throw new IllegalArgumentException("type: " + type);')
ifct.line("        }")
ifct.line("    }")

for s in structs:
  ifct.line("    public %s new%s(Decoder dec) {" % (s.name, s.name))
  ifct.line("        return new %s%s(dec);" % (s.name, isfx))
  ifct.line("    }")

  ifct.line("    public %s new%s(%s) {" % (s.name, s.name, s.parameters()))
  ifct.line("        return new %s%s(%s);" % (s.name, isfx, s.arguments()))
  ifct.line("    }")

ifct.line("}");
ifct.write()

dlg = Output(out_dir, out_pkg, "Delegate")
dlg.line("public abstract class Delegate<C> {")
for s in structs:
  dlg.line("    public void %s(C context, %s struct) {}" %
           (dromedary(s.name), s.name))
dlg.line("}")
dlg.write()

inv = Output(out_dir, out_pkg, "Invoker")
inv.line("public abstract class Invoker {")
inv.line()
inv.line("    protected abstract void invoke(Method method);")
inv.line("    protected abstract void invoke(Method method, Handler<Struct> handler);")
inv.line("    protected abstract StructFactory getFactory();")
inv.line()
for s in structs:
  dname = dromedary(s.name)
  inv.line("    public void %s(%s) {" % (dname, s.parameters()))
  inv.line("        invoke(getFactory().new%s(%s));" % (s.name, s.arguments()))
  inv.line("    }")
inv.line("}")
inv.write()