-
Notifications
You must be signed in to change notification settings - Fork 7
/
generator.go
325 lines (275 loc) · 10.7 KB
/
generator.go
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
package main
import (
"bytes"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"strings"
)
type generator struct {
Request *plugin.CodeGeneratorRequest
Response *plugin.CodeGeneratorResponse
output *bytes.Buffer
indent string
}
func newGenerator(req *plugin.CodeGeneratorRequest) *generator {
return &generator{
Request: req,
Response: nil,
output: bytes.NewBuffer(nil),
indent: "",
}
}
func (g *generator) Generate() error {
g.Response = &plugin.CodeGeneratorResponse{}
for _, file := range g.getProtoFiles() {
err := g.processFile(file)
if err != nil {
return err
}
}
return nil
}
func (g *generator) processFile(file *descriptor.FileDescriptorProto) error {
if file.Options.GetJavaGenericServices() {
return fmt.Errorf("twirp_java_jaxrs cannot not work with java_generic_services option")
}
g.Response.File = append(g.Response.File, g.generateProvider(file))
for _, service := range file.GetService() {
out := g.generateServiceInterface(file, service)
g.Response.File = append(g.Response.File, out)
out = g.generateServiceClient(file, service)
g.Response.File = append(g.Response.File, out)
}
return nil
}
func (g *generator) generateProvider(file *descriptor.FileDescriptorProto) *plugin.CodeGeneratorResponse_File {
multi := file.Options.GetJavaMultipleFiles()
serviceName := "ProtoBufMessageProvider"
if multi {
pkg := getJavaPackage(file)
g.P(`// Code generated by protoc-gen-twirp_java_jaxrs, DO NOT EDIT.`)
g.P(`// source: `, file.GetName())
g.P()
if pkg != "" {
g.P(`package `, pkg, `;`)
g.P()
}
}
static := ""
if !multi {
static = "static "
}
g.P(`@javax.ws.rs.ext.Provider
@javax.ws.rs.Produces({"application/protobuf", "application/json"})
@javax.ws.rs.Consumes({"application/protobuf", "application/json"})
public `, static, `class `, serviceName, ` implements javax.ws.rs.ext.MessageBodyWriter<com.google.protobuf.Message>, javax.ws.rs.ext.MessageBodyReader<com.google.protobuf.Message> {
@Override
public boolean isWriteable(Class<?> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) {
return com.google.protobuf.Message.class.isAssignableFrom(type) && ("json".equals(mediaType.getSubtype()) || "protobuf".equals(mediaType.getSubtype()));
}
@Override
public long getSize(com.google.protobuf.Message t, Class<?> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) {
if (t == null) {
return -1;
}
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
try {
writeTo(t, type, genericType, annotations, mediaType, null, out);
} catch (java.io.IOException e) {
return -1;
}
return out.size();
}
@Override
public void writeTo(com.google.protobuf.Message t, Class<?> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, javax.ws.rs.core.MultivaluedMap<String, Object> httpHeaders, java.io.OutputStream entityStream) throws java.io.IOException, javax.ws.rs.WebApplicationException {
switch (mediaType.getSubtype()) {
case "protobuf":
t.writeTo(entityStream);
break;
case "json":
entityStream.write(com.google.protobuf.util.JsonFormat.printer().print(t).getBytes("UTF-8"));
break;
default:
throw new javax.ws.rs.WebApplicationException("MediaType not supported!");
}
}
@Override
public boolean isReadable(Class<?> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType) {
return com.google.protobuf.Message.class.isAssignableFrom(type) && ("json".equals(mediaType.getSubtype()) || "protobuf".equals(mediaType.getSubtype()));
}
@Override
public com.google.protobuf.Message readFrom(Class<com.google.protobuf.Message> type, java.lang.reflect.Type genericType, java.lang.annotation.Annotation[] annotations, javax.ws.rs.core.MediaType mediaType, javax.ws.rs.core.MultivaluedMap<String, String> httpHeaders, java.io.InputStream entityStream) throws java.io.IOException, javax.ws.rs.WebApplicationException {
try {
switch (mediaType.getSubtype()) {
case "protobuf":
java.lang.reflect.Method m = type.getMethod("parseFrom", java.io.InputStream.class);
return (com.google.protobuf.Message) m.invoke(null, entityStream);
case "json":
com.google.protobuf.Message.Builder msg = (com.google.protobuf.Message.Builder)type.getMethod("newBuilder").invoke(null);
com.google.protobuf.util.JsonFormat.parser().merge(new java.io.InputStreamReader(entityStream), msg);
return msg.build();
default:
throw new javax.ws.rs.WebApplicationException("MediaType not supported!");
}
} catch (Exception e) {
throw new javax.ws.rs.WebApplicationException(e);
}
}
}
`)
out := &plugin.CodeGeneratorResponse_File{}
out.Content = proto.String(g.output.String())
if multi {
out.Name = proto.String(getJavaServiceClientClassFileByString(file, serviceName))
} else {
out.Name = proto.String(getJavaOuterClassFile(file))
out.InsertionPoint = proto.String("outer_class_scope")
}
g.Reset()
return out
}
func (g *generator) generateServiceClient(file *descriptor.FileDescriptorProto, service *descriptor.ServiceDescriptorProto) *plugin.CodeGeneratorResponse_File {
multi := file.Options.GetJavaMultipleFiles()
if multi {
pkg := getJavaPackage(file)
g.P(`// Code generated by protoc-gen-twirp_java_jaxrs, DO NOT EDIT.`)
g.P(`// source: `, file.GetName())
g.P()
if pkg != "" {
g.P(`package `, pkg, `;`)
g.P()
}
}
// TODO add comment
serviceClass := getJavaServiceClientClassName(file, service)
servicePath := g.getServicePath(file, service)
interfaceClass := getJavaType(file, getJavaServiceClassName(file, service))
provider := getJavaType(file, "ProtoBufMessageProvider")
static := ""
if !multi {
static = "static "
}
g.P(`public `, static, `class `, serviceClass, ` implements `, interfaceClass, ` {`)
g.P(` private final javax.ws.rs.client.WebTarget target;`)
g.P()
g.P(` public `, serviceClass, `(javax.ws.rs.client.WebTarget target) {`)
g.P(` this.target = target.path("`, servicePath, `");`)
g.P(` this.target.register(new `, provider, `());`)
g.P(` }`)
g.P()
g.P(` private <R> R call(String path, com.google.protobuf.Message req, Class<R> responseClass) {`)
g.P(` javax.ws.rs.core.Response response = target.path(path)`)
g.P(` .request("application/protobuf")`)
g.P(` .post(javax.ws.rs.client.Entity.entity(req, "application/protobuf"));`)
g.P(` if (response.getStatusInfo().getFamily() == javax.ws.rs.core.Response.Status.Family.SUCCESSFUL) {`)
g.P(` R r = response.readEntity(responseClass);`)
g.P(` response.close();`)
g.P(` return r;`)
g.P(` } else {`)
g.P(` throw new javax.ws.rs.WebApplicationException(response);`)
g.P(` }`)
g.P(` }`)
g.P()
for _, method := range service.GetMethod() {
inputType := getJavaType(file, method.GetInputType())
outputType := getJavaType(file, method.GetOutputType())
methodName := lowerCamelCase(method.GetName())
methodPath := camelCase(method.GetName())
g.P()
// add comment
g.P(` @Override`)
g.P(` public `, outputType, ` `, methodName, `(`, inputType, ` request) {`)
g.P(` return call("/`, methodPath, `", request, `, outputType, `.class);`)
g.P(` }`)
}
g.P(`}`)
g.P()
out := &plugin.CodeGeneratorResponse_File{}
out.Content = proto.String(g.output.String())
if multi {
out.Name = proto.String(getJavaServiceClientClassFile(file, service))
} else {
out.Name = proto.String(getJavaOuterClassFile(file))
out.InsertionPoint = proto.String("outer_class_scope")
}
g.Reset()
return out
}
func (g *generator) generateServiceInterface(file *descriptor.FileDescriptorProto, service *descriptor.ServiceDescriptorProto) *plugin.CodeGeneratorResponse_File {
// TODO add comment
serviceClass := getJavaServiceClassName(file, service)
servicePath := g.getServicePath(file, service)
multi := file.Options.GetJavaMultipleFiles()
if multi {
pkg := getJavaPackage(file)
g.P(`// Code generated by protoc-gen-twirp_java_jaxrs, DO NOT EDIT.`)
g.P(`// source: `, file.GetName())
g.P()
if pkg != "" {
g.P(`package `, pkg, `;`)
g.P()
}
}
g.P(`@javax.ws.rs.Path( "/`, servicePath, `" )`)
g.P(`public interface `, serviceClass, ` {`)
for _, method := range service.GetMethod() {
inputType := getJavaType(file, method.GetInputType())
outputType := getJavaType(file, method.GetOutputType())
methodName := lowerCamelCase(method.GetName())
// add comment
g.P(` `, `@javax.ws.rs.POST`)
g.P(` `, `@javax.ws.rs.Path( "/`, strings.Title(methodName), `" )`)
g.P(` `, `@javax.ws.rs.Consumes({"application/protobuf", "application/json"})`)
g.P(` `, `@javax.ws.rs.Produces({"application/protobuf", "application/json"})`)
g.P(` `, outputType, ` `, methodName, `(`, inputType, ` request);`)
}
g.P(`}`)
g.P()
out := &plugin.CodeGeneratorResponse_File{}
out.Content = proto.String(g.output.String())
if multi {
out.Name = proto.String(getJavaServiceClassFile(file, service))
} else {
out.Name = proto.String(getJavaOuterClassFile(file))
out.InsertionPoint = proto.String("outer_class_scope")
}
g.Reset()
return out
}
func (g *generator) Reset() {
g.indent = ""
g.output.Reset()
}
func (g *generator) In() {
g.indent += " "
}
func (g *generator) Out() {
g.indent = g.indent[2:]
}
func (g *generator) P(str ...string) {
for _, v := range str {
g.output.WriteString(v)
}
g.output.WriteByte('\n')
}
func (g *generator) getProtoFiles() []*descriptor.FileDescriptorProto {
files := make([]*descriptor.FileDescriptorProto, 0)
for _, fname := range g.Request.GetFileToGenerate() {
for _, proto := range g.Request.GetProtoFile() {
if proto.GetName() == fname {
files = append(files, proto)
}
}
}
return files
}
func (g *generator) getServicePath(file *descriptor.FileDescriptorProto, service *descriptor.ServiceDescriptorProto) string {
name := camelCase(service.GetName())
pkg := file.GetPackage()
if pkg != "" {
name = pkg + "." + name
}
return name
}