-
Notifications
You must be signed in to change notification settings - Fork 22
/
RestVerticle.java
1586 lines (1456 loc) · 67.2 KB
/
RestVerticle.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.folio.rest;
import io.vertx.core.Promise;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.mail.MessagingException;
import javax.mail.internet.InternetHeaders;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.apache.commons.lang3.StringUtils;
import org.folio.rest.annotations.Stream;
import org.folio.rest.jaxrs.model.Error;
import org.folio.rest.jaxrs.model.Errors;
import org.folio.rest.jaxrs.model.Metadata;
import org.folio.rest.jaxrs.model.Parameter;
import org.folio.rest.persist.PostgresClient;
import org.folio.rest.tools.AnnotationGrabber;
import org.folio.rest.tools.ClientGenerator;
import org.folio.rest.tools.PomReader;
import org.folio.rest.tools.RTFConsts;
import org.folio.rest.tools.client.test.HttpClientMock2;
import org.folio.rest.tools.codecs.PojoEventBusCodec;
import org.folio.rest.tools.messages.MessageConsts;
import org.folio.rest.tools.messages.Messages;
import org.folio.rest.tools.utils.AsyncResponseResult;
import org.folio.rest.tools.utils.BinaryOutStream;
import org.folio.rest.tools.utils.InterfaceToImpl;
import org.folio.rest.tools.utils.JsonUtils;
import org.folio.rest.tools.utils.JwtUtils;
import org.folio.rest.tools.utils.LogUtil;
import org.folio.rest.tools.utils.ObjectMapperTool;
import org.folio.rest.tools.utils.OutStream;
import org.folio.rest.tools.utils.ResponseImpl;
import org.folio.rest.tools.utils.ValidationHelper;
import org.folio.rest.tools.utils.VertxUtils;
import org.apache.log4j.MDC;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.google.common.base.Joiner;
import com.google.common.io.ByteStreams;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerFileUpload;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.dropwizard.MetricsService;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.StaticHandler;
public class RestVerticle extends AbstractVerticle {
public static final String DEFAULT_UPLOAD_BUS_ADDRS = "admin.uploaded.files";
public static final String DEFAULT_TEMP_DIR = System.getProperty("java.io.tmpdir");
public static final String JSON_URL_MAPPINGS = "API_PATH_MAPPINGS";
public static final String OKAPI_HEADER_TENANT = ClientGenerator.OKAPI_HEADER_TENANT;
public static final String OKAPI_HEADER_TOKEN = "x-okapi-token";
public static final String OKAPI_HEADER_PERMISSIONS = "X-Okapi-Permissions";
public static final String OKAPI_HEADER_PREFIX = "x-okapi";
public static final String OKAPI_USERID_HEADER = "X-Okapi-User-Id";
public static final String OKAPI_REQUESTID_HEADER = "X-Okapi-Request-Id";
public static final String STREAM_ID = "STREAMED_ID";
public static final String STREAM_COMPLETE = "COMPLETE";
public static final String STREAM_ABORT = "STREAMED_ABORT";
public static final Map<String, String> MODULE_SPECIFIC_ARGS = new HashMap<>(); //NOSONAR
private static final String UPLOAD_PATH_TO_HANDLE = "/admin/upload";
private static final String CORS_ALLOW_HEADER = "Access-Control-Allow-Origin";
private static final String CORS_ALLOW_ORIGIN = "Access-Control-Allow-Headers";
private static final String CORS_ALLOW_METHODS_HEADER = "Access-Control-Allow-Methods";
private static final String CORS_ALLOW_METHODS_VALUE = "POST, GET, OPTIONS , PUT, DELETE";
private static final String CORS_ALLOW_HEADER_VALUE = "*";
private static final String CORS_ALLOW_ORIGIN_VALUE = "Origin, Authorization, X-Requested-With, Content-Type, Accept, x-okapi-tenant";
private static final String SUPPORTED_CONTENT_TYPE_FORMDATA = "multipart/form-data";
private static final String SUPPORTED_CONTENT_TYPE_JSON_DEF = "application/json";
private static final String SUPPORTED_CONTENT_TYPE_JSON_API_DEF = "application/vnd.api+json";
private static final String SUPPORTED_CONTENT_TYPE_TEXT_DEF = "text/plain";
private static final String SUPPORTED_CONTENT_TYPE_XML_DEF = "application/xml";
private static final String SUPPORTED_CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
private static final String FILE_UPLOAD_PARAM = "javax.mail.internet.MimeMultipart";
private static final String HTTP_PORT_SETTING = "http.port";
private static MetricsService serverMetrics = null;
private static String className = RestVerticle.class.getName();
private static final Logger log = LoggerFactory.getLogger(className);
private static final ObjectMapper MAPPER = ObjectMapperTool.getMapper();
private static final String DEFAULT_SCHEMA = "public";
/**
* Minimum java version used for runtime check.
*
* For compile time check see raml-module-builder/pom.xml maven-enforcer-plugin requireJavaVersion.
*/
private static final String MINIMUM_JAVA_VERSION = "1.8.0_101";
private static ValidatorFactory validationFactory;
private static String deploymentId = "";
private final Messages messages = Messages.getInstance();
private EventBus eventBus;
// this is only to run via IDE - otherwise see pom which runs the verticle and
// requires passing -cluster and preferable -cluster-home args
public static void main(String[] args) {
Vertx vertx = VertxUtils.getVertxWithExceptionHandler();
vertx.deployVerticle(new RestVerticle());
}
static {
//validationFactory used to validate the pojos which are created from the json
//passed in the request body in put and post requests. The constraints validated by this factory
//are the ones in the json schemas accompanying the raml files
validationFactory = Validation.buildDefaultValidatorFactory();
checkJavaVersion(System.getProperty("java.runtime.version"));
}
/**
* Compare java version strings of the form 1.8.0_191
*/
static int compareJavaVersion(String versionA, String versionB) {
String [] a = versionA.split("[^0-9]+");
String [] b = versionB.split("[^0-9]+");
for (int i=0; i<4; i++) {
int compare = Integer.compare(Integer.parseInt(a[i]), Integer.parseInt(b[i]));
if (compare != 0) {
return compare;
}
}
return 0;
}
/**
* @throws InternalError if javaVersion is less than {@link #MINIMUM_JAVA_VERSION}
*/
static void checkJavaVersion(String javaVersion) {
if (compareJavaVersion(javaVersion, MINIMUM_JAVA_VERSION) < 0) {
throw new InternalError("Minimum java version is " + MINIMUM_JAVA_VERSION + " but found " + javaVersion);
}
}
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
// first match - no q val check
static String acceptCheck(JsonArray l, String h) {
String []hl = h.split(",");
String hBest = null;
for (int i = 0; i < hl.length; i++) {
String mediaRange = hl[i].split(";")[0].trim();
for (int j = 0; j < l.size(); j++) {
String c = l.getString(j);
if (mediaRange.compareTo("*/*") == 0 || c.equalsIgnoreCase(mediaRange)) {
hBest = c;
break;
}
}
}
return hBest;
}
@Override
public void start(Promise<Void> startPromise) throws Exception {
readInGitProps();
//process cmd line arguments
cmdProcessing();
deploymentId = UUID.randomUUID().toString();
LogUtil.formatLogMessage(className, "start", "metrics enabled: " + vertx.isMetricsEnabled());
serverMetrics = MetricsService.create(vertx);
// maps paths found in raml to the generated functions to route to when the paths are requested
MappedClasses mappedURLs = populateConfig();
// set of exposed urls as declared in the raml
Set<String> urlPaths = mappedURLs.getAvailURLs();
// create a map of regular expression to url path
Map<String, Pattern> regex2Pattern = mappedURLs.buildURLRegex();
// Create a router object.
Router router = Router.router(vertx);
eventBus = vertx.eventBus();
log.info(context.getInstanceCount() + " verticles deployed ");
try {
//register codec to be able to pass pojos on the event bus
eventBus.registerCodec(new PojoEventBusCodec());
} catch (Exception e3) {
if (e3.getMessage().startsWith("Already a codec registered with name")) {
//needed in case we run multiple verticle instances
//in this vertx instace - re-registering the same codec twice throws an
//exception
log.info("Attempt to register PojoEventBusCodec again... this is acceptable ");
}
else{
throw e3;
}
}
// needed so that we get the body content of the request - note that this
// will read the entire body into memory
final BodyHandler handler = BodyHandler.create();
// IMPORTANT!!!
// the body of the request will be read into memory for ALL PUT requests
// and for POST requests with the content-types below ONLY!!!
// multipart, for example will not be read by the body handler as vertx saves
// multiparts and www-encoded to disk - hence multiparts will be handled differently
// see uploadHandler further down
router.put().handler(handler);
router.post().consumes(SUPPORTED_CONTENT_TYPE_JSON_DEF).handler(handler);
router.post().consumes(SUPPORTED_CONTENT_TYPE_JSON_API_DEF).handler(handler);
router.post().consumes(SUPPORTED_CONTENT_TYPE_TEXT_DEF).handler(handler);
router.post().consumes(SUPPORTED_CONTENT_TYPE_XML_DEF).handler(handler);
router.post().consumes(SUPPORTED_CONTENT_TYPE_FORM).handler(handler);
// run pluggable startup code in a class implementing the InitAPI interface
// in the "org.folio.rest.impl" package
runHook(vv -> {
if (((Future<?>) vv).failed()) {
String reason = ((Future<?>) vv).cause().getMessage();
log.error( messages.getMessage("en", MessageConsts.InitializeVerticleFail, reason));
startPromise.fail(reason);
vertx.close();
System.exit(-1);
} else {
log.info("init succeeded.......");
try {
// startup periodic impl if exists
runPeriodicHook();
} catch (Exception e2) {
log.error(e2.getMessage(), e2);
}
//single handler for all url calls other then documentation
//which is handled separately
router.routeWithRegex("^(?!.*apidocs).*$").handler(rc -> route(mappedURLs, urlPaths, regex2Pattern, rc));
// routes requests on “/assets/*” to resources stored in the “assets”
// directory.
router.route("/assets/*").handler(StaticHandler.create("assets"));
// In the following example all requests to paths starting with
// /apidocs/ will get served from the directory resources/apidocs:
// example:
// http://localhost:8181/apidocs/index.html?raml=raml/_patrons.raml
router.route("/apidocs/*").handler(StaticHandler.create("apidocs"));
// startup http server on port 8181 to serve documentation
String portS = System.getProperty(HTTP_PORT_SETTING);
int port;
if (portS != null) {
port = Integer.parseInt(portS);
config().put(HTTP_PORT_SETTING, port);
} else {
// we are here if port was not passed via cmd line
port = config().getInteger(HTTP_PORT_SETTING, 8081);
}
//check if mock mode requested and set sys param so that http client factory
//can config itself accordingly
String mockMode = config().getString(HttpClientMock2.MOCK_MODE);
if(mockMode != null){
System.setProperty(HttpClientMock2.MOCK_MODE, mockMode);
}
//if client includes an Accept-Encoding header which includes
//the supported compressions - deflate or gzip.
HttpServerOptions serverOptions = new HttpServerOptions();
serverOptions.setCompressionSupported(true);
HttpServer server = vertx.createHttpServer(serverOptions);
server.requestHandler(router)
// router object (declared in the beginning of the atrt function accepts request and will pass to next handler for
// specified path
.listen(port,
// Retrieve the port from the configuration file - file needs to
// be passed as arg to command line,
// for example: -conf src/main/conf/my-application-conf.json
// default to 8181.
result -> {
if (result.failed()) {
startPromise.fail(new RuntimeException("Listening on port " + port, result.cause()));
} else {
try {
runPostDeployHook( res2 -> {
if(!res2.succeeded()){
log.error(res2.cause().getMessage(), res2.cause());
}
});
} catch (Exception e) {
log.error(e.getMessage(), e);
}
LogUtil.formatLogMessage(className, "start", "http server for apis and docs started on port " + port + ".");
LogUtil.formatLogMessage(className, "start", "Documentation available at: " + "http://localhost:" + port + "/apidocs/");
startPromise.complete();
}
});
}
});
}
/**
* Handler for all url calls other then documentation.
* @param mappedURLs maps paths found in raml to the generated functions to route to when the paths are requested
* @param urlPaths set of exposed urls as declared in the raml
* @param regex2Pattern create a map of regular expression to url path
* @param rc RoutingContext of this URL
*/
void route(MappedClasses mappedURLs, Set<String> urlPaths, Map<String, Pattern> regex2Pattern,
RoutingContext rc) {
long start = System.nanoTime();
try {
//list of regex urls created from urls declared in the raml
Iterator<String> iter = urlPaths.iterator();
boolean validPath = false;
boolean[] validRequest = { true };
// loop over regex patterns and try to match them against the requested
// URL if no match is found, then the requested url is not supported by
// the ramls and we return an error - this has positive security implications as well
while (iter.hasNext()) {
String regexURL = iter.next();
//try to match the requested url to each regex pattern created from the urls in the raml
Matcher m = regex2Pattern.get(regexURL).matcher(rc.request().path());
if (m.find()) {
validPath = true;
// get the function that should be invoked for the requested
// path + requested http_method pair
JsonObject ret = mappedURLs.getMethodbyPath(regexURL, rc.request().method().toString());
// if a valid path was requested but no function was found
if (ret == null) {
// if the path is valid and the http method is options
// assume a cors request
if (rc.request().method() == HttpMethod.OPTIONS) {
rc.response().end();
return;
}
// the url exists but the http method requested does not match a function
// meaning url+http method != a function
endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.HTTPMethodNotSupported),
validRequest);
return;
}
Class<?> aClass;
try {
if (validRequest[0]) {
int groups = m.groupCount();
//pathParams are the place holders in the raml query string
//for example /admin/{admin_id}/yyy/{yyy_id} - the content in between the {} are path params
//they are replaced with actual values and are passed to the function which the url is mapped to
String[] pathParams = new String[groups];
for (int i = 0; i < groups; i++) {
pathParams[i] = m.group(i + 1);
}
//create okapi headers map and inject into function
Map<String, String> okapiHeaders = new CaseInsensitiveMap<>();
String []tenantId = new String[]{null};
getOkapiHeaders(rc, okapiHeaders, tenantId);
String reqId = okapiHeaders.get(OKAPI_REQUESTID_HEADER);
if(reqId != null){
MDC.put("reqId", "reqId="+reqId);
}
if(tenantId[0] == null && !rc.request().path().startsWith("/admin")){
//if tenant id is not passed in and this is not an /admin request, return error
endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.UnableToProcessRequest)
+ " Tenant must be set", validRequest);
}
if (validRequest[0]) {
//get interface mapped to this url
String iClazz = ret.getString(AnnotationGrabber.CLASS_NAME);
// convert from interface to an actual class implementing it, which appears in the impl package
aClass = InterfaceToImpl.convert2Impl(RTFConsts.PACKAGE_OF_IMPLEMENTATIONS, iClazz, false).get(0);
Object o = null;
// call back the constructor of the class - gives a hook into the class not based on the apis
// passing the vertx and context objects in to it.
try {
o = aClass.getConstructor(Vertx.class, String.class).newInstance(vertx, tenantId[0]);
} catch (Exception e) {
// if no such constructor was implemented call the
// default no param constructor to create the object to be used to call functions on
o = aClass.newInstance();
}
final Object instance = o;
// function to invoke for the requested url
String function = ret.getString(AnnotationGrabber.FUNCTION_NAME);
// parameters for the function to invoke
JsonObject params = ret.getJsonObject(AnnotationGrabber.METHOD_PARAMS);
// all methods in the class whose function is mapped to the called url
// needed so that we can get a reference to the Method object and call it via reflection
Method[] methods = aClass.getMethods();
// what the api will return as output (Accept)
JsonArray produces = ret.getJsonArray(AnnotationGrabber.PRODUCES);
// what the api expects to get (content-type)
JsonArray consumes = ret.getJsonArray(AnnotationGrabber.CONSUMES);
HttpServerRequest request = rc.request();
//check that the accept and content-types passed in the header of the request
//are as described in the raml
checkAcceptContentType(produces, consumes, rc, validRequest);
// create the array and then populate it by parsing the url parameters which are needed to invoke the function mapped
//to the requested URL - array will be populated by parseParams() function
Iterator<Map.Entry<String, Object>> paramList = params.iterator();
Object[] paramArray = new Object[params.size()];
parseParams(rc, paramList, validRequest, consumes, paramArray, pathParams, okapiHeaders);
//Get method in class to be run for this requested API endpoint
Method[] method2Run = new Method[]{null};
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(function)) {
method2Run[0] = methods[i];
break;
}
}
//is function annotated to receive data in chunks as they come in.
//Note that the function controls the logic to this if this is the case
boolean streamData = isStreamed(method2Run[0].getAnnotations());
// check if we are dealing with a file upload , currently only multipart/form-data and application/octet
//in the raml definition for such a function
final boolean[] isContentUpload = new boolean[] { false };
final int[] uploadParamPosition = new int[] { -1 };
params.forEach(param -> {
if (((JsonObject) param.getValue()).getString("type").equals(FILE_UPLOAD_PARAM)) {
isContentUpload[0] = true;
uploadParamPosition[0] = ((JsonObject) param.getValue()).getInteger("order");
}
else if(((JsonObject) param.getValue()).getString("type").equals("java.io.InputStream")){
//application/octet-stream passed - this is handled in a stream like manner
//and the corresponding function called must annotate with a @Stream - and be able
//to handle the function being called repeatedly on parts of the data
uploadParamPosition[0] = ((JsonObject) param.getValue()).getInteger("order");
isContentUpload[0] = true;
}
});
// file upload requested (multipart/form-data) but the url is not to the /admin/upload
// meaning, an implementing module is using its own upload handling, so read the content and
// pass to implementing function just like any other call
if (isContentUpload[0] && !streamData) {
//if file upload - set needed handlers
// looks something like -> multipart/form-data; boundary=----WebKitFormBoundaryzeZR8KqAYJyI2jPL
if (consumes != null && consumes.contains(SUPPORTED_CONTENT_TYPE_FORMDATA)) {
//multipart
handleMultipartUpload(rc, request, uploadParamPosition, paramArray, validRequest);
request.endHandler( a -> {
if (validRequest[0]) {
//if request is valid - invoke it
try {
invoke(method2Run[0], paramArray, instance, rc, tenantId, okapiHeaders, new StreamStatus(), v -> {
LogUtil.formatLogMessage(className, "start", " invoking " + function);
sendResponse(rc, v, start, tenantId[0]);
});
} catch (Exception e1) {
log.error(e1.getMessage(), e1);
rc.response().end();
}
}
});
}
else {
//assume input stream
handleInputStreamUpload(method2Run[0], rc, request, instance, tenantId, okapiHeaders,
uploadParamPosition, paramArray, validRequest, start);
}
}
else if(streamData){
handleStream(method2Run[0], rc, request, instance, tenantId, okapiHeaders,
uploadParamPosition, paramArray, validRequest, start);
}
else{
if (validRequest[0]) {
//if request is valid - invoke it
try {
invoke(method2Run[0], paramArray, instance, rc, tenantId, okapiHeaders, new StreamStatus(), v -> {
LogUtil.formatLogMessage(className, "start", " invoking " + function);
sendResponse(rc, v, start, tenantId[0]);
});
} catch (Exception e1) {
log.error(e1.getMessage(), e1);
rc.response().end();
}
}
}
}
else{
endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.UnableToProcessRequest),
validRequest);
return;
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
endRequestWithError(rc, 400, true, messages.getMessage("en", MessageConsts.UnableToProcessRequest) + e.getMessage(),
validRequest);
return;
}
}
}
if (!validPath) {
// invalid path
endRequestWithError(rc, 400, true,
messages.getMessage("en", MessageConsts.InvalidURLPath, rc.request().path()), validRequest);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
endRequestWithError(rc, 500, true, "Server error", new boolean[] { true });
}
}
private void handleStream(Method method2Run, RoutingContext rc, HttpServerRequest request,
Object instance, String[] tenantId, Map<String, String> okapiHeaders,
int[] uploadParamPosition, Object[] paramArray, boolean[] validRequest, long start){
request.handler(new Handler<Buffer>() {
@Override
public void handle(Buffer buff) {
try {
StreamStatus stat = new StreamStatus();
stat.setStatus(0);
paramArray[uploadParamPosition[0]] =
new ByteArrayInputStream( buff.getBytes() );
invoke(method2Run, paramArray, instance, rc, tenantId, okapiHeaders, stat, v -> {
LogUtil.formatLogMessage(className, "start", " invoking " + method2Run);
});
} catch (Exception e1) {
log.error(e1.getMessage(), e1);
rc.response().end();
}
}
});
request.endHandler( e -> {
StreamStatus stat = new StreamStatus();
stat.setStatus(1);
paramArray[uploadParamPosition[0]] = new ByteArrayInputStream(new byte [0]);
invoke(method2Run, paramArray, instance, rc, tenantId, okapiHeaders, stat, v -> {
LogUtil.formatLogMessage(className, "start", " invoking " + method2Run);
//all data has been stored in memory - not necessarily all processed
sendResponse(rc, v, start, tenantId[0]);
});
});
request.exceptionHandler(new Handler<Throwable>() {
@Override
public void handle(Throwable event) {
StreamStatus stat = new StreamStatus();
stat.setStatus(2);
paramArray[uploadParamPosition[0]] = new ByteArrayInputStream(new byte[0]);
invoke(method2Run, paramArray, instance, rc, tenantId, okapiHeaders, stat, v
-> LogUtil.formatLogMessage(className, "start", " invoking " + method2Run)
);
endRequestWithError(rc, 400, true, "unable to upload file " + event.getMessage(), validRequest);
}
});
}
/**
* @param method2Run
* @param rc
* @param request
* @param okapiHeaders
* @param tenantId
* @param instance
* @param uploadParamPosition
* @param paramArray
* @param validRequest
* @param start
*/
private void handleInputStreamUpload(Method method2Run, RoutingContext rc, HttpServerRequest request,
Object instance, String[] tenantId, Map<String, String> okapiHeaders,
int[] uploadParamPosition, Object[] paramArray, boolean[] validRequest, long start) {
final Buffer content = Buffer.buffer();
request.handler(new Handler<Buffer>() {
@Override
public void handle(Buffer buff) {
content.appendBuffer(buff);
}
});
request.endHandler( e -> {
paramArray[uploadParamPosition[0]] = new ByteArrayInputStream(content.getBytes());
try {
invoke(method2Run, paramArray, instance, rc, tenantId, okapiHeaders, new StreamStatus(), v -> {
LogUtil.formatLogMessage(className, "start", " invoking " + method2Run);
sendResponse(rc, v, start, tenantId[0]);
});
} catch (Exception e1) {
log.error(e1.getMessage(), e1);
rc.response().end();
}
});
request.exceptionHandler(new Handler<Throwable>(){
@Override
public void handle(Throwable event) {
endRequestWithError(rc, 400, true, event.getMessage(), validRequest);
}
});
}
private void readInGitProps(){
InputStream in = getClass().getClassLoader().getResourceAsStream("git.properties");
if (in != null) {
try {
Properties prop = new Properties();
prop.load(in);
in.close();
log.info("git: " + prop.getProperty("git.remote.origin.url")
+ " " + prop.getProperty("git.commit.id"));
} catch (Exception e) {
log.warn(e.getMessage());
}
}
}
/**
* @param request
* @param uploadParamPosition
* @param paramArray
* @param validRequest
*/
private void handleMultipartUpload(RoutingContext rc,
HttpServerRequest request, int[] uploadParamPosition, Object[] paramArray, boolean[] validRequest) {
request.setExpectMultipart(true);
MimeMultipart mmp = new MimeMultipart();
//place the mmp as an argument to the 'to be called' function - at the correct position
paramArray[uploadParamPosition[0]] = mmp;
request.uploadHandler(new MultiPartHandler(rc, mmp, validRequest));
}
class MultiPartHandler implements Handler<io.vertx.core.http.HttpServerFileUpload> {
MimeMultipart mmp;
RoutingContext rc;
boolean[] validRequest;
Buffer content = Buffer.buffer();
public MultiPartHandler(RoutingContext rc, MimeMultipart mmp, boolean[] validRequest){
this.rc = rc;
this.mmp = mmp;
this.validRequest = validRequest;
}
@Override
public void handle(HttpServerFileUpload upload) {
upload.handler(new Handler<Buffer>() {
@Override
public void handle(Buffer buff) { /** called as data comes in */
if(content == null){
content = Buffer.buffer();
}
content.appendBuffer(buff);
}
});
upload.exceptionHandler(new Handler<Throwable>() {
@Override
public void handle(Throwable event) {
endRequestWithError(rc, 400, true, "unable to upload file " + event.getMessage(), validRequest);
}
});
/** endHandler called for each part in the multipart, so if uploading 2 files - will be called twice */
upload.endHandler(new Handler<Void>() {
@Override
public void handle(Void event) {
InternetHeaders headers = new InternetHeaders();
MimeBodyPart mbp = null;
try {
mbp = new MimeBodyPart(headers, content.getBytes());
mbp.setFileName(upload.filename());
mmp.addBodyPart(mbp);
content = null;
} catch (MessagingException e) {
log.error(e.getMessage(), e);
}
}
});
}
}
/**
* @param annotations
* @return
*/
private boolean isStreamed(Annotation[] annotations) {
for (int i = 0; i < annotations.length; i++) {
if(annotations[i].annotationType().equals(Stream.class)){
return true;
}
}
return false;
}
/**
* Send the result as response.
*
* @param rc
* - where to send the result
* @param v
* - the result to send
* @param start
* - request's start time, using JVM's high-resolution time source, in nanoseconds
*/
private void sendResponse(RoutingContext rc, AsyncResult<Response> v, long start, String tenantId) {
Response result = ((Response) ((AsyncResult<?>) v).result());
if (result == null) {
// catch all
endRequestWithError(rc, 500, true, "Server error", new boolean[] { true });
return;
}
Object entity = null;
try {
HttpServerResponse response = rc.response();
int statusCode = result.getStatus();
// 204 means no content returned in the response, so passing
// a chunked Transfer header is not allowed
if (statusCode != 204) {
response.setChunked(true);
}
response.setStatusCode(statusCode);
// !!!!!!!!!!!!!!!!!!!!!! CORS commented OUT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// response.putHeader("Access-Control-Allow-Origin", "*");
copyHeadersJoin(result.getStringHeaders(), response.headers());
entity = result.getEntity();
/* entity is of type OutStream - and will be written as a string */
if (entity instanceof OutStream) {
response.write(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(((OutStream) entity).getData()));
}
/* entity is of type BinaryOutStream - and will be written as a buffer */
else if(entity instanceof BinaryOutStream){
response.write(Buffer.buffer(((BinaryOutStream) entity).getData()));
}
/* data is a string so just push it out, no conversion needed */
else if(entity instanceof String){
response.write(Buffer.buffer((String)entity));
}
/* catch all - anything else will be assumed to be a pojo which needs converting to json */
else if (entity != null) {
response.write(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(entity));
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
rc.response().end();
}
long end = System.nanoTime();
StringBuilder sb = new StringBuilder();
if (log.isDebugEnabled()) {
try {
sb.append(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(entity));
} catch (Exception e) {
String name = "null";
if (entity != null) {
name = entity.getClass().getName();
}
log.error("writeValueAsString(" + name + ")", e);
}
}
LogUtil.formatStatsLogMessage(rc.request().remoteAddress().toString(), rc.request().method().toString(),
rc.request().version().toString(), rc.response().getStatusCode(), (((end - start) / 1000000)), rc.response().bytesWritten(),
rc.request().path(), rc.request().query(), rc.response().getStatusMessage(), tenantId, sb.toString());
}
/**
* Copy the headers from source to destination. Join several headers of same key using "; ".
*/
private void copyHeadersJoin(MultivaluedMap<String,String> source, MultiMap destination) {
for (Entry<String, List<String>> entry : source.entrySet()) {
String jointValue = Joiner.on("; ").join(entry.getValue());
try {
destination.add(entry.getKey(), jointValue);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
e.getMessage() + ": " + entry.getKey() + " - " + jointValue, e);
}
}
}
void endRequestWithError(RoutingContext rc, int status, boolean chunked, String message, boolean[] isValid) {
if (isValid[0]) {
HttpServerResponse response = rc.response();
if (!response.closed()) {
response.setChunked(chunked);
response.setStatusCode(status);
if (status == 422) {
response.putHeader("Content-type", SUPPORTED_CONTENT_TYPE_JSON_DEF);
} else {
response.putHeader("Content-type", SUPPORTED_CONTENT_TYPE_TEXT_DEF);
}
if (message != null) {
response.write(message);
} else {
message = "";
}
response.end();
}
LogUtil.formatStatsLogMessage(rc.request().remoteAddress().toString(), rc.request().method().toString(),
rc.request().version().toString(), response.getStatusCode(), -1, rc.response().bytesWritten(),
rc.request().path(), rc.request().query(), response.getStatusMessage(), null, message);
}
// once we are here the call is not valid
isValid[0] = false;
}
private void getOkapiHeaders(RoutingContext rc, Map<String, String> headers, String[] tenantId){
MultiMap mm = rc.request().headers();
Consumer<Map.Entry<String,String>> consumer = entry -> {
String headerKey = entry.getKey().toLowerCase();
if(headerKey.startsWith(OKAPI_HEADER_PREFIX)){
if(headerKey.equalsIgnoreCase(ClientGenerator.OKAPI_HEADER_TENANT)){
tenantId[0] = entry.getValue();
}
headers.put(headerKey, entry.getValue());
}
};
mm.forEach(consumer);
}
private void invoke(Method method, Object[] params, Object o, RoutingContext rc, String[] tenantId,
Map<String,String> headers, StreamStatus streamed, Handler<AsyncResult<Response>> resultHandler) {
String generateRCforFunc = PomReader.INSTANCE.getProps().getProperty("generate_routing_context");
boolean addRCParam = false;
if(generateRCforFunc != null){
String []addRC = generateRCforFunc.split(",");
for (int i = 0; i < addRC.length; i++) {
if(addRC[i].equals(rc.request().path())){
addRCParam = true;
}
}
}
//if streaming is requested the status will be 0 (streaming started)
//or 1 streaming data complete
//or 2 streaming aborted
//otherwise it will be -1 and flags wont be set
if(streamed.status == 0){
headers.put(STREAM_ID, String.valueOf(rc.hashCode()));
}
else if(streamed.status == 1){
headers.put(STREAM_ID, String.valueOf(rc.hashCode()));
headers.put(STREAM_COMPLETE, String.valueOf(rc.hashCode()));
}
else if (streamed.status == 2){
headers.put(STREAM_ID, String.valueOf(rc.hashCode()));
headers.put(STREAM_ABORT, String.valueOf(rc.hashCode()));
}
Object[] newArray = new Object[params.length];
int size = 3;
int pos = 0;
//this endpoint indicated it wants to receive the routing context as a parameter
if(addRCParam){
//the amount of extra params added is 4 not 3
size = 4;
//the first param of the extra params is the injected RC
newArray[params.length - size] = rc;
pos = 1;
}
for (int i = 0; i < params.length - size; i++) {
newArray[i] = params[i];
}
//inject call back handler into each function
newArray[params.length - (size-(pos+1))] = resultHandler;
//inject vertx context into each function
newArray[params.length - (size-(pos+2))] = getVertx().getOrCreateContext();
/* if(tenantId[0] == null){
headers.put(OKAPI_HEADER_TENANT, DEFAULT_SCHEMA);
}*/
newArray[params.length - (size-pos)] = headers;
try {
method.invoke(o, newArray);
// response.setChunked(true);
// response.setStatusCode(((Response)result).getStatus());
} catch (Exception e) {
log.error(e.getMessage(), e);
String message;
try {
// catch exception for now in case of null point and show generic
// message
message = e.getCause().getMessage();
} catch (Throwable ee) {
message = messages.getMessage("en", MessageConsts.UnableToProcessRequest);
}
endRequestWithError(rc, 400, true, message, new boolean[]{true});
}
}
public JsonObject loadConfig(String configFile) {
try {
byte[] jsonData = ByteStreams.toByteArray(getClass().getClassLoader().getResourceAsStream(configFile));
return new JsonObject(new String(jsonData));
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return new JsonObject();
}
private MappedClasses populateConfig() {
MappedClasses mappedURLs = new MappedClasses();
JsonObject jObjClasses = new JsonObject();
try {
jObjClasses.mergeIn(AnnotationGrabber.generateMappings());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// loadConfig(JSON_URL_MAPPINGS);
Set<String> classURLs = jObjClasses.fieldNames();
classURLs.forEach(classURL -> {
log.info(classURL);
JsonObject jObjMethods = jObjClasses.getJsonObject(classURL);
Set<String> methodURLs = jObjMethods.fieldNames();
jObjMethods.fieldNames();
methodURLs.forEach(methodURL -> {
Object val = jObjMethods.getValue(methodURL);
if (val instanceof JsonArray) {
((JsonArray) val).forEach(entry -> {
String pathRegex = ((JsonObject) entry).getString("regex2method");
((JsonObject) entry).put(AnnotationGrabber.CLASS_NAME, jObjMethods.getString(AnnotationGrabber.CLASS_NAME));
((JsonObject) entry).put(AnnotationGrabber.INTERFACE_NAME, jObjMethods.getString(AnnotationGrabber.INTERFACE_NAME));
mappedURLs.addPath(pathRegex, (JsonObject) entry);
});
}
});
});
return mappedURLs;
}
@Override
public void stop(Promise<Void> stopPromise) throws Exception {
super.stop();