/
UploadController.java
512 lines (456 loc) · 19.5 KB
/
UploadController.java
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
* Copyright 2017-2020 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.upload;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.annotation.Body;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Part;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.multipart.CompletedFileUpload;
import io.micronaut.http.multipart.CompletedPart;
import io.micronaut.http.multipart.PartData;
import io.micronaut.http.multipart.StreamingFileUpload;
import io.micronaut.http.server.multipart.MultipartBody;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import io.micronaut.core.async.annotation.SingleResult;
import jakarta.inject.Singleton;
import reactor.core.Exceptions;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.Mono;
import reactor.core.publisher.ReplayProcessor;
import reactor.core.publisher.Sinks;
import reactor.core.scheduler.Schedulers;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Function;
/**
* @author Graeme Rocher
* @since 1.0
*/
@Singleton
@Controller("/upload")
public class UploadController {
@Post(value = "/receive-json", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
public String receiveJson(Data data, String title) {
return title + ": " + data.toString();
}
@Post(value = "/receive-plain", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
public String receivePlain(String data, String title) {
return title + ": " + data;
}
@Post(value = "/receive-bytes", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
public String receiveBytes(byte[] data, String title) {
return title + ": " + data.length;
}
@Post(value = "/receive-multipart", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
public String receiveMultipart(@Body Data data) {
return data.toString();
}
@Post(value = "/receive-file-upload", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
public Publisher<MutableHttpResponse<?>> receiveFileUpload(StreamingFileUpload data, String title) {
long size = data.getDefinedSize();
return Flux.from(data.transferTo(title + ".json"))
.map(success -> success ? HttpResponse.ok( "Uploaded " + size ) : HttpResponse.status(HttpStatus.INTERNAL_SERVER_ERROR, "Something bad happened"))
.onErrorReturn((MutableHttpResponse<?>) HttpResponse.status(HttpStatus.INTERNAL_SERVER_ERROR, "Something bad happened"));
}
@Post(value = "/receive-completed-file-upload", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
public String receiveCompletedFileUpload(CompletedFileUpload data) {
try {
return data.getFilename() + ": " + data.getBytes().length;
} catch (IOException e) {
return e.getMessage();
}
}
@Post(value = "/receive-completed-file-upload-stream", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
public String receiveCompletedFileUploadStream(CompletedFileUpload data) {
try {
InputStream is = data.getInputStream();
int size = 1024;
byte[] buf = new byte[size];
int total = 0;
int len;
while ((len = is.read(buf, 0, size)) != -1) {
total += len;
}
is.close();
is.close(); //intentionally close the stream twice to ensure it doesn't throw an exception
return data.getFilename() + ": " + total;
} catch (IOException e) {
return e.getMessage();
}
}
@Post(value = "/receive-publisher", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<HttpResponse> receivePublisher(Publisher<byte[]> data) {
return Flux.from(data).reduce(new StringBuilder(), (stringBuilder, bytes) ->
{
StringBuilder append = stringBuilder.append(new String(bytes));
System.out.println("bytes.length = " + bytes.length);
return append;
}
)
.map((Function<StringBuilder, HttpResponse>) stringBuilder ->
{
System.out.println("stringBuilder.length() = " + stringBuilder.length());
MutableHttpResponse<String> res = HttpResponse.ok(stringBuilder.toString());
System.out.println("res = " + res);
return res;
}
);
}
@Post(value = "/receive-flow-parts", consumes = MediaType.MULTIPART_FORM_DATA)
@SingleResult
public Publisher<HttpResponse> receiveFlowParts(Publisher<PartData> data) {
return Flux.from(data).collectList().doOnSuccess(parts -> {
for (PartData part : parts) {
try {
part.getBytes(); //intentionally releasing the parts after all data has been received
} catch (IOException e) {
e.printStackTrace();
}
}
}).map(parts -> HttpResponse.ok());
}
@Post(value = "/receive-flow-data", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
public Publisher<HttpResponse> receiveFlowData(Data data) {
return Flux.just(HttpResponse.ok(data.toString()));
}
@Post(value = "/receive-multiple-flow-data", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<HttpResponse> receiveMultipleFlowData(Publisher<Data> data) {
return Mono.create(emitter -> {
data.subscribe(new Subscriber<Data>() {
private Subscription s;
List<Data> datas = new ArrayList<>();
@Override
public void onSubscribe(Subscription s) {
this.s = s;
s.request(1);
}
@Override
public void onNext(Data data) {
datas.add(data);
s.request(1);
}
@Override
public void onError(Throwable t) {
emitter.error(t);
}
@Override
public void onComplete() {
emitter.success(HttpResponse.ok(datas.toString()));
}
});
});
}
@Post(value = "/receive-two-flow-parts", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
public Publisher<HttpResponse> receiveTwoFlowParts(
@Part("data") Publisher<String> dataPublisher,
@Part("title") Publisher<String> titlePublisher) {
return Flux.from(titlePublisher).zipWith(dataPublisher, (title, data) -> HttpResponse.ok( title + ": " + data ));
}
@Post(value = "/receive-multiple-completed", consumes = MediaType.MULTIPART_FORM_DATA)
public Publisher<HttpResponse> receiveMultipleCompleted(
Publisher<CompletedFileUpload> data,
String title) {
List<Map> results = new ArrayList<>();
ReplayProcessor<HttpResponse> subject = ReplayProcessor.create();
Flux.from(data).subscribeOn(Schedulers.boundedElastic())
.subscribe(new Subscriber<CompletedFileUpload>() {
Subscription subscription;
@Override
public void onSubscribe(Subscription s) {
s.request(1);
this.subscription = s;
}
@Override
public void onNext(CompletedFileUpload upload) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("name", upload.getFilename());
result.put("size", upload.getSize());
results.add(result);
subscription.request(1);
}
@Override
public void onError(Throwable t) {
subject.onError(t);
}
@Override
public void onComplete() {
Map<String, Object> body = new LinkedHashMap<>();
body.put("files", results);
body.put("title", title);
subject.onNext(HttpResponse.ok(body));
subject.onComplete();
}
});
return subject.asFlux();
}
@Post(value = "/receive-multiple-streaming", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<HttpResponse> receiveMultipleStreaming(
Publisher<StreamingFileUpload> data) {
return Flux.from(data).subscribeOn(Schedulers.boundedElastic()).flatMap((StreamingFileUpload upload) -> {
return Flux.from(upload)
.map((pd) -> {
try {
return pd.getBytes();
} catch (IOException e) {
throw Exceptions.propagate(e);
}
});
}).collect(LongAdder::new, (adder, bytes) -> adder.add((long)bytes.length))
.map((adder) -> {
return HttpResponse.ok(adder.longValue());
});
}
@Post(value = "/receive-partdata", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<HttpResponse> receivePartdata(
Publisher<PartData> data) {
return Flux.from(data).subscribeOn(Schedulers.boundedElastic())
.map((pd) -> {
try {
final byte[] bytes = pd.getBytes();
System.out.println("received " + bytes.length + " bytes");
return bytes;
} catch (IOException e) {
System.out.println("caught exception");
System.out.println(e);
throw Exceptions.propagate(e);
}
})
.collect(LongAdder::new, (adder, bytes) -> adder.add((long)bytes.length))
.map((adder) -> {
return HttpResponse.ok(adder.longValue());
});
}
@Post(value = "/receive-multiple-publishers", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<HttpResponse> receiveMultiplePublishers(Publisher<Publisher<byte[]>> data) {
return Flux.from(data)
.subscribeOn(Schedulers.boundedElastic())
.flatMap((Publisher<byte[]> upload) -> {
return Flux.from(upload).map((bytes) -> bytes);
}).collect(LongAdder::new, (adder, bytes) -> adder.add((long)bytes.length))
.map((adder) -> {
return HttpResponse.ok(adder.longValue());
});
}
@Post(value = "/receive-flow-control", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<String> go(Map json, Publisher<byte[]> file) {
return Mono.create(singleEmitter -> {
file.subscribe(new Subscriber<byte[]>() {
private Subscription subscription;
private LongAdder longAdder = new LongAdder();
@Override
public void onSubscribe(Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
@Override
public void onNext(byte[] bytes) {
longAdder.add(bytes.length);
subscription.request(1);
}
@Override
public void onError(Throwable throwable) {
singleEmitter.error(throwable);
}
@Override
public void onComplete() {
singleEmitter.success(Long.toString(longAdder.longValue()));
}
});
});
}
@Post(value = "/receive-big-attribute", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<HttpResponse> receiveBigAttribute(Publisher<PartData> data) {
return Mono.create(emitter -> {
data.subscribe(new Subscriber<PartData>() {
private Subscription s;
List<String> datas = new ArrayList<>();
@Override
public void onSubscribe(Subscription s) {
this.s = s;
s.request(1);
}
@Override
public void onNext(PartData data) {
try {
datas.add(new String(data.getBytes(), StandardCharsets.UTF_8));
s.request(1);
} catch (IOException e) {
s.cancel();
emitter.error(e);
}
}
@Override
public void onError(Throwable t) {
emitter.error(t);
}
@Override
public void onComplete() {
emitter.success(HttpResponse.ok(String.join("", datas)));
}
});
});
}
@Post(value = "/receive-multipart-body", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<String> go(@Body MultipartBody multipartBody) {
return Mono.create(emitter -> {
multipartBody.subscribe(new Subscriber<CompletedPart>() {
private Subscription s;
List<String> datas = new ArrayList<>();
@Override
public void onSubscribe(Subscription s) {
this.s = s;
s.request(1);
}
@Override
public void onNext(CompletedPart data) {
try {
datas.add(new String(data.getBytes(), StandardCharsets.UTF_8));
s.request(1);
} catch (IOException e) {
s.cancel();
emitter.error(e);
}
}
@Override
public void onError(Throwable t) {
emitter.error(t);
}
@Override
public void onComplete() {
emitter.success(String.join("|", datas));
}
});
});
}
@Post(value = "/receive-multipart-body-principal", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<String> multipartBodyWithPrincipal(Principal principal, @Body MultipartBody multipartBody) {
return Mono.create(emitter -> {
multipartBody.subscribe(new Subscriber<CompletedPart>() {
private Subscription s;
List<String> datas = new ArrayList<>();
@Override
public void onSubscribe(Subscription s) {
this.s = s;
s.request(1);
}
@Override
public void onNext(CompletedPart data) {
try {
datas.add(new String(data.getBytes(), StandardCharsets.UTF_8));
s.request(1);
} catch (IOException e) {
s.cancel();
emitter.error(e);
}
}
@Override
public void onError(Throwable t) {
emitter.error(t);
}
@Override
public void onComplete() {
emitter.success(String.join("|", datas));
}
});
});
}
@Post(value = "/publisher-completedpart", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<String> publisherCompletedPart(Publisher<CompletedPart> recipients) {
return Mono.create(emitter -> {
recipients.subscribe(new Subscriber<CompletedPart>() {
private Subscription s;
List<String> datas = new ArrayList<>();
@Override
public void onSubscribe(Subscription s) {
this.s = s;
s.request(1);
}
@Override
public void onNext(CompletedPart data) {
try {
datas.add(new String(data.getBytes(), StandardCharsets.UTF_8));
s.request(1);
} catch (IOException e) {
s.cancel();
emitter.error(e);
}
}
@Override
public void onError(Throwable t) {
emitter.error(t);
}
@Override
public void onComplete() {
emitter.success(String.join("|", datas));
}
});
});
}
@Post(uri = "/receive-multipart-body-as-mono", consumes = MediaType.MULTIPART_FORM_DATA, produces = MediaType.TEXT_PLAIN)
@SingleResult
public Publisher<String> multipartAsSingle(@Body io.micronaut.http.server.multipart.MultipartBody body) {
//This will throw an exception because it caches the first result and does not emit it until
//the publisher completes. By this time the data has been freed. The data is freed immediately
//after the onNext call to prevent memory leaks
return Mono.from(body).map(single -> {
try {
return single.getBytes() == null ? "FAIL" : "OK";
} catch (IOException e) {
e.printStackTrace();
}
return "FAIL";
});
}
public static class Data {
String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Data{" +
"title='" + title + '\'' +
'}';
}
}
}