-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
RestDefinition.java
1183 lines (1038 loc) · 41.7 KB
/
RestDefinition.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* http://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 org.apache.camel.model.rest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElementRef;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlTransient;
import org.apache.camel.CamelContext;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.model.OptionalIdentifiedDefinition;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.model.ToDefinition;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.NodeIdFactory;
import org.apache.camel.spi.Resource;
import org.apache.camel.spi.ResourceAware;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.URISupport;
import static org.apache.camel.support.CamelContextHelper.parseText;
/**
* Defines a rest service using the rest-dsl
*/
@Metadata(label = "rest")
@XmlRootElement(name = "rest")
@XmlAccessorType(XmlAccessType.FIELD)
public class RestDefinition extends OptionalIdentifiedDefinition<RestDefinition> implements ResourceAware {
public static final String MISSING_VERB = "Must add verb first, such as get/post/delete";
@XmlAttribute
private String path;
@XmlAttribute
private String consumes;
@XmlAttribute
private String produces;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean")
private String disabled;
@XmlAttribute
@Metadata(defaultValue = "off", enums = "off,auto,json,xml,json_xml")
private String bindingMode;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String skipBindingOnErrorCode;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String clientRequestValidation;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String enableCORS;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "false")
private String enableNoContentResponse;
@XmlAttribute
@Metadata(label = "advanced", javaType = "java.lang.Boolean", defaultValue = "true")
private String apiDocs;
@XmlAttribute
@Metadata(label = "advanced")
private String tag;
@XmlElement(name = "securityDefinitions") // use the name Swagger/OpenAPI uses
@Metadata(label = "security")
private RestSecuritiesDefinition securityDefinitions;
@XmlElement
@Metadata(label = "security")
private List<SecurityDefinition> securityRequirements = new ArrayList<>();
@XmlElementRef
private List<VerbDefinition> verbs = new ArrayList<>();
@XmlTransient
private Resource resource;
@Override
public String getShortName() {
return "rest";
}
@Override
public String getLabel() {
return "rest";
}
public String getPath() {
return path;
}
/**
* Path of the rest service, such as "/foo"
*/
public void setPath(String path) {
this.path = path;
}
public String getTag() {
return tag;
}
/**
* To configure a special tag for the operations within this rest definition.
*/
public void setTag(String tag) {
this.tag = tag;
}
public String getConsumes() {
return consumes;
}
/**
* To define the content type what the REST service consumes (accept as input), such as application/xml or
* application/json. This option will override what may be configured on a parent level
*/
public void setConsumes(String consumes) {
this.consumes = consumes;
}
public String getProduces() {
return produces;
}
/**
* To define the content type what the REST service produces (uses for output), such as application/xml or
* application/json This option will override what may be configured on a parent level
*/
public void setProduces(String produces) {
this.produces = produces;
}
public String getDisabled() {
return disabled;
}
/**
* Whether to disable this REST service from the route during build time. Once an REST service has been disabled
* then it cannot be enabled later at runtime.
*/
public void setDisabled(String disabled) {
this.disabled = disabled;
}
public String getBindingMode() {
return bindingMode;
}
/**
* Sets the binding mode to use. This option will override what may be configured on a parent level
* <p/>
* The default value is auto
*/
public void setBindingMode(String bindingMode) {
this.bindingMode = bindingMode;
}
public List<VerbDefinition> getVerbs() {
return verbs;
}
public RestSecuritiesDefinition getSecurityDefinitions() {
return securityDefinitions;
}
/**
* Sets the security definitions such as Basic, OAuth2 etc.
*/
public void setSecurityDefinitions(RestSecuritiesDefinition securityDefinitions) {
this.securityDefinitions = securityDefinitions;
}
public List<SecurityDefinition> getSecurityRequirements() {
return securityRequirements;
}
/**
* Sets the security requirement(s) for all endpoints.
*/
public void setSecurityRequirements(List<SecurityDefinition> securityRequirements) {
this.securityRequirements = securityRequirements;
}
/**
* The HTTP verbs this REST service accepts and uses
*/
public void setVerbs(List<VerbDefinition> verbs) {
this.verbs = verbs;
}
public String getSkipBindingOnErrorCode() {
return skipBindingOnErrorCode;
}
/**
* Whether to skip binding on output if there is a custom HTTP error code header. This allows to build custom error
* messages that do not bind to json / xml etc, as success messages otherwise will do. This option will override
* what may be configured on a parent level
*/
public void setSkipBindingOnErrorCode(String skipBindingOnErrorCode) {
this.skipBindingOnErrorCode = skipBindingOnErrorCode;
}
public String getClientRequestValidation() {
return clientRequestValidation;
}
/**
* Whether to enable validation of the client request to check:
*
* 1) Content-Type header matches what the Rest DSL consumes; returns HTTP Status 415 if validation error. 2) Accept
* header matches what the Rest DSL produces; returns HTTP Status 406 if validation error. 3) Missing required data
* (query parameters, HTTP headers, body); returns HTTP Status 400 if validation error. 4) Parsing error of the
* message body (JSon, XML or Auto binding mode must be enabled); returns HTTP Status 400 if validation error.
*/
public void setClientRequestValidation(String clientRequestValidation) {
this.clientRequestValidation = clientRequestValidation;
}
public String getEnableCORS() {
return enableCORS;
}
/**
* Whether to enable CORS headers in the HTTP response. This option will override what may be configured on a parent
* level
* <p/>
* The default value is false.
*/
public void setEnableCORS(String enableCORS) {
this.enableCORS = enableCORS;
}
public String getEnableNoContentResponse() {
return enableNoContentResponse;
}
/**
* Whether to return HTTP 204 with an empty body when a response contains an empty JSON object or XML root object.
* <p/>
* The default value is false.
*/
public void setEnableNoContentResponse(String enableNoContentResponse) {
this.enableNoContentResponse = enableNoContentResponse;
}
public String getApiDocs() {
return apiDocs;
}
/**
* Whether to include or exclude this rest operation in API documentation. This option will override what may be
* configured on a parent level.
* <p/>
* The default value is true.
*/
public void setApiDocs(String apiDocs) {
this.apiDocs = apiDocs;
}
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
// Fluent API
// -------------------------------------------------------------------------
/**
* To set the base path of this REST service
*/
public RestDefinition path(String path) {
setPath(path);
return this;
}
/**
* Disables this REST service from the route during build time. Once an REST service has been disabled then it
* cannot be enabled later at runtime.
*/
public RestDefinition disabled() {
disabled("true");
return this;
}
/**
* Whether to disable this REST service from the route during build time. Once an REST service has been disabled
* then it cannot be enabled later at runtime.
*/
public RestDefinition disabled(boolean disabled) {
disabled(disabled ? "true" : "false");
return this;
}
/**
* Whether to disable this REST service from the route during build time. Once an REST service has been disabled
* then it cannot be enabled later at runtime.
*/
public RestDefinition disabled(String disabled) {
if (getVerbs().isEmpty()) {
this.disabled = disabled;
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setDisabled(disabled);
}
return this;
}
/**
* To set the tag to use of this REST service
*/
public RestDefinition tag(String tag) {
setTag(tag);
return this;
}
public RestDefinition get() {
return addVerb("get", null);
}
public RestDefinition get(String uri) {
return addVerb("get", uri);
}
public RestDefinition post() {
return addVerb("post", null);
}
public RestDefinition post(String uri) {
return addVerb("post", uri);
}
public RestDefinition put() {
return addVerb("put", null);
}
public RestDefinition put(String uri) {
return addVerb("put", uri);
}
public RestDefinition patch() {
return addVerb("patch", null);
}
public RestDefinition patch(String uri) {
return addVerb("patch", uri);
}
public RestDefinition delete() {
return addVerb("delete", null);
}
public RestDefinition delete(String uri) {
return addVerb("delete", uri);
}
public RestDefinition head() {
return addVerb("head", null);
}
public RestDefinition head(String uri) {
return addVerb("head", uri);
}
public RestDefinition verb(String verb) {
return addVerb(verb, null);
}
public RestDefinition verb(String verb, String uri) {
return addVerb(verb, uri);
}
@Override
public RestDefinition id(String id) {
if (getVerbs().isEmpty()) {
super.id(id);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.id(id);
}
return this;
}
public RestDefinition routeId(String routeId) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setRouteId(routeId);
return this;
}
public RestDefinition deprecated() {
if (!getVerbs().isEmpty()) {
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setDeprecated("true");
}
return this;
}
@Override
public RestDefinition description(String description) {
if (getVerbs().isEmpty()) {
super.description(description);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.description(description);
}
return this;
}
public RestDefinition consumes(String mediaType) {
if (getVerbs().isEmpty()) {
this.consumes = mediaType;
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setConsumes(mediaType);
}
return this;
}
public ParamDefinition param() {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
return param(verb);
}
public RestDefinition param(ParamDefinition param) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.getParams().add(param);
return this;
}
public RestDefinition params(List<ParamDefinition> params) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.getParams().addAll(params);
return this;
}
public ParamDefinition param(VerbDefinition verb) {
return new ParamDefinition(verb);
}
public RestDefinition responseMessage(ResponseMessageDefinition msg) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.getResponseMsgs().add(msg);
return this;
}
public ResponseMessageDefinition responseMessage() {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
return responseMessage(verb);
}
public ResponseMessageDefinition responseMessage(VerbDefinition verb) {
return new ResponseMessageDefinition(verb);
}
public RestDefinition responseMessages(List<ResponseMessageDefinition> msgs) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.getResponseMsgs().addAll(msgs);
return this;
}
public RestDefinition responseMessage(int code, String message) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
ResponseMessageDefinition msg = responseMessage(verb);
msg.setCode(String.valueOf(code));
msg.setMessage(message);
return this;
}
public RestDefinition responseMessage(String code, String message) {
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
ResponseMessageDefinition response = responseMessage(verb);
response.setCode(code);
response.setMessage(message);
verb.getResponseMsgs().add(response);
return this;
}
/**
* To configure security definitions.
*/
public RestSecuritiesDefinition securityDefinitions() {
if (securityDefinitions == null) {
securityDefinitions = new RestSecuritiesDefinition(this);
}
return securityDefinitions;
}
public RestDefinition produces(String mediaType) {
if (getVerbs().isEmpty()) {
this.produces = mediaType;
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setProduces(mediaType);
}
return this;
}
public RestDefinition type(Class<?> classType) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setTypeClass(classType);
verb.setType(asTypeName(classType));
return this;
}
public RestDefinition outType(Class<?> classType) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setOutTypeClass(classType);
verb.setOutType(asTypeName(classType));
return this;
}
public RestDefinition bindingMode(RestBindingMode mode) {
return bindingMode(mode.name());
}
public RestDefinition bindingMode(String mode) {
if (getVerbs().isEmpty()) {
this.bindingMode = mode.toLowerCase();
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setBindingMode(mode.toLowerCase());
}
return this;
}
public RestDefinition skipBindingOnErrorCode(boolean skipBindingOnErrorCode) {
if (getVerbs().isEmpty()) {
this.skipBindingOnErrorCode = Boolean.toString(skipBindingOnErrorCode);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setSkipBindingOnErrorCode(Boolean.toString(skipBindingOnErrorCode));
}
return this;
}
public RestDefinition clientRequestValidation(boolean clientRequestValidation) {
if (getVerbs().isEmpty()) {
this.clientRequestValidation = Boolean.toString(clientRequestValidation);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setClientRequestValidation(Boolean.toString(clientRequestValidation));
}
return this;
}
public RestDefinition enableCORS(boolean enableCORS) {
if (getVerbs().isEmpty()) {
this.enableCORS = Boolean.toString(enableCORS);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setEnableCORS(Boolean.toString(enableCORS));
}
return this;
}
public RestDefinition enableNoContentResponse(boolean enableNoContentResponse) {
if (getVerbs().isEmpty()) {
this.enableNoContentResponse = Boolean.toString(enableNoContentResponse);
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setEnableNoContentResponse(Boolean.toString(enableNoContentResponse));
}
return this;
}
/**
* Include or exclude the current Rest Definition in API documentation.
* <p/>
* The default value is true.
*/
public RestDefinition apiDocs(Boolean apiDocs) {
if (getVerbs().isEmpty()) {
this.apiDocs = apiDocs != null ? apiDocs.toString() : null;
} else {
// add on last verb as that is how the Java DSL works
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setApiDocs(apiDocs != null ? apiDocs.toString() : null);
}
return this;
}
/**
* Sets the security setting for this verb.
*/
public RestDefinition security(String key) {
return security(key, null);
}
/**
* Sets the security setting for this verb.
*/
public RestDefinition security(String key, String scopes) {
// add to last verb
if (getVerbs().isEmpty()) {
SecurityDefinition requirement = securityRequirements
.stream().filter(r -> key.equals(r.getKey())).findFirst().orElse(null);
if (requirement == null) {
requirement = new SecurityDefinition();
securityRequirements.add(requirement);
requirement.setKey(key);
}
requirement.setScopes(scopes);
} else {
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
SecurityDefinition sd = new SecurityDefinition();
sd.setKey(key);
sd.setScopes(scopes);
verb.getSecurity().add(sd);
}
return this;
}
/**
* The Camel endpoint this REST service will call, such as a direct endpoint to link to an existing route that
* handles this REST call.
*
* @param uri the uri of the endpoint
* @return this builder
*/
public RestDefinition to(String uri) {
// add to last verb
if (getVerbs().isEmpty()) {
throw new IllegalArgumentException(MISSING_VERB);
}
ToDefinition to = new ToDefinition(uri);
VerbDefinition verb = getVerbs().get(getVerbs().size() - 1);
verb.setTo(to);
return this;
}
/**
* Build the from endpoint uri for the verb
*/
public String buildFromUri(CamelContext camelContext, VerbDefinition verb) {
return "rest:" + verb.asVerb() + ":" + buildUri(camelContext, verb);
}
// Implementation
// -------------------------------------------------------------------------
private RestDefinition addVerb(String verb, String uri) {
VerbDefinition answer;
if ("get".equals(verb)) {
answer = new GetDefinition();
} else if ("post".equals(verb)) {
answer = new PostDefinition();
} else if ("delete".equals(verb)) {
answer = new DeleteDefinition();
} else if ("head".equals(verb)) {
answer = new HeadDefinition();
} else if ("put".equals(verb)) {
answer = new PutDefinition();
} else if ("patch".equals(verb)) {
answer = new PatchDefinition();
} else {
throw new IllegalArgumentException("Verb " + verb + " not supported");
}
getVerbs().add(answer);
answer.setRest(this);
answer.setPath(uri);
return this;
}
/**
* Transforms this REST definition into a list of {@link org.apache.camel.model.RouteDefinition} which Camel routing
* engine can add and run. This allows us to define REST services using this REST DSL and turn those into regular
* Camel routes.
*
* @param camelContext The Camel context
*/
public List<RouteDefinition> asRouteDefinition(CamelContext camelContext) {
ObjectHelper.notNull(camelContext, "CamelContext");
List<RouteDefinition> answer = new ArrayList<>();
Boolean disabled = CamelContextHelper.parseBoolean(camelContext, this.disabled);
if (disabled != null && disabled) {
return answer; // all rest services are disabled
}
// only include enabled verbs
List<VerbDefinition> filter = new ArrayList<>();
for (VerbDefinition verb : verbs) {
disabled = CamelContextHelper.parseBoolean(camelContext, verb.getDisabled());
if (disabled == null || !disabled) {
filter.add(verb);
}
}
// sanity check this rest definition do not have duplicates
validateUniquePaths(filter);
RestConfiguration config = camelContext.getRestConfiguration();
if (config.isInlineRoutes()) {
// sanity check this rest definition do not have duplicates linked routes via direct endpoints
validateUniqueDirects(filter);
}
addRouteDefinition(camelContext, filter, answer, config.getComponent(), config.getProducerComponent());
return answer;
}
protected void validateUniquePaths(List<VerbDefinition> verbs) {
Set<String> paths = new HashSet<>();
for (VerbDefinition verb : verbs) {
String path = verb.asVerb();
if (verb.getPath() != null) {
path += ":" + verb.getPath();
}
if (!paths.add(path)) {
throw new IllegalArgumentException("Duplicate verb detected in rest-dsl: " + path);
}
}
}
protected void validateUniqueDirects(List<VerbDefinition> verbs) {
Set<String> directs = new HashSet<>();
for (VerbDefinition verb : verbs) {
ToDefinition to = verb.getTo();
if (to != null) {
String uri = to.getUri();
if (uri.startsWith("direct:")) {
if (!directs.add(uri)) {
throw new IllegalArgumentException("Duplicate to in rest-dsl: " + uri);
}
}
}
}
}
protected String asTypeName(Class<?> classType) {
// Workaround for https://issues.apache.org/jira/browse/CAMEL-15199
//
// The VerbDefinition::setType and VerbDefinition::setOutType require
// the class to be expressed as canonical with an optional [] to mark
// the type is an array but this i wrong as the canonical name can not
// be dynamically be loaded by the classloader thus this workaround
// that for nested classes generates a class name that does not respect
// any JLS convention.
//
// TODO: this probably need to be revisited
String type;
if (!classType.isPrimitive()) {
if (classType.isArray()) {
type = StringHelper.between(classType.getName(), "[L", ";") + "[]";
} else {
type = classType.getName();
}
} else {
type = classType.getCanonicalName();
}
return type;
}
/**
* Transforms the rest api configuration into a {@link org.apache.camel.model.RouteDefinition} which Camel routing
* engine uses to service the rest api docs.
*/
public static RouteDefinition asRouteApiDefinition(CamelContext camelContext, RestConfiguration configuration) {
RouteDefinition answer = new RouteDefinition();
// create the from endpoint uri which is using the rest-api component
String from = "rest-api:" + configuration.getApiContextPath();
String routeId = configuration.getApiContextRouteId();
if (routeId == null) {
routeId = answer.idOrCreate(camelContext.getCamelContextExtension().getContextPlugin(NodeIdFactory.class));
}
// append options
Map<String, Object> options = new HashMap<>();
if (configuration.getComponent() != null && !configuration.getComponent().isEmpty()) {
options.put("consumerComponentName", configuration.getComponent());
}
if (!options.isEmpty()) {
try {
from = URISupport.appendParametersToURI(from, options);
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
// we use the same uri as the producer (so we have a little route for
// the rest api)
String to = from;
answer.fromRest(from);
answer.id(routeId);
answer.to(to);
return answer;
}
@SuppressWarnings("rawtypes")
private void addRouteDefinition(
CamelContext camelContext, List<VerbDefinition> verbs, List<RouteDefinition> answer,
String component, String producerComponent) {
for (VerbDefinition verb : verbs) {
// use a route as facade for this REST service
RouteDefinition route = new RouteDefinition();
if (verb.getTo() == null) {
throw new IllegalArgumentException("Rest service: " + verb + " must have to endpoint configured.");
}
if (verb.getRouteId() != null) {
route.routeId(parseText(camelContext, verb.getRouteId()));
}
route.getOutputs().add(verb.getTo());
// add the binding
RestBindingDefinition binding = new RestBindingDefinition();
binding.setComponent(component);
binding.setType(parseText(camelContext, verb.getType()));
binding.setTypeClass(verb.getTypeClass());
binding.setOutType(parseText(camelContext, verb.getOutType()));
binding.setOutTypeClass(verb.getOutTypeClass());
// verb takes precedence over configuration on rest
if (verb.getBindingMode() != null) {
binding.setBindingMode(parseText(camelContext, verb.getBindingMode()));
} else {
binding.setBindingMode(getBindingMode());
}
if (verb.getConsumes() != null) {
binding.setConsumes(parseText(camelContext, verb.getConsumes()));
} else {
binding.setConsumes(getConsumes());
}
if (verb.getProduces() != null) {
binding.setProduces(parseText(camelContext, verb.getProduces()));
} else {
binding.setProduces(getProduces());
}
if (binding.getType() != null || binding.getOutType() != null && binding.getBindingMode() != null) {
// okay we have binding mode and in/out type defined - then we can infer consume/produces
String mode = binding.getBindingMode();
if ("json".equals(mode)) {
if (binding.getConsumes() == null && binding.getType() != null) {
binding.setConsumes("application/json");
}
if (binding.getProduces() == null && binding.getOutType() != null) {
binding.setProduces("application/json");
}
} else if ("xml".equals(mode)) {
if (binding.getConsumes() == null && binding.getType() != null) {
binding.setConsumes("application/xml");
}
if (binding.getProduces() == null && binding.getOutType() != null) {
binding.setProduces("application/xml");
}
} else if ("json_xml".equals(mode)) {
if (binding.getConsumes() == null && binding.getType() != null) {
binding.setConsumes("application/json;application/xml");
}
if (binding.getProduces() == null && binding.getOutType() != null) {
binding.setProduces("application/json;application/xml");
}
}
}
if (verb.getSkipBindingOnErrorCode() != null) {
binding.setSkipBindingOnErrorCode(parseText(camelContext, verb.getSkipBindingOnErrorCode()));
} else {
binding.setSkipBindingOnErrorCode(getSkipBindingOnErrorCode());
}
if (verb.getClientRequestValidation() != null) {
binding.setClientRequestValidation(parseText(camelContext, verb.getClientRequestValidation()));
} else {
binding.setClientRequestValidation(getClientRequestValidation());
}
if (verb.getEnableCORS() != null) {
binding.setEnableCORS(parseText(camelContext, verb.getEnableCORS()));
} else {
binding.setEnableCORS(getEnableCORS());
}
if (verb.getEnableNoContentResponse() != null) {
binding.setEnableNoContentResponse(parseText(camelContext, verb.getEnableNoContentResponse()));
} else {
binding.setEnableNoContentResponse(getEnableNoContentResponse());
}
for (ParamDefinition param : verb.getParams()) {
// register all the default values for the query and header parameters
RestParamType type = param.getType();
if ((RestParamType.query == type || RestParamType.header == type)
&& ObjectHelper.isNotEmpty(param.getDefaultValue())) {
binding.addDefaultValue(param.getName(), parseText(camelContext, param.getDefaultValue()));
}
// register which parameters are required
Boolean required = param.getRequired();
if (required != null && required) {
if (RestParamType.query == type) {
binding.addRequiredQueryParameter(param.getName());
} else if (RestParamType.header == type) {
binding.addRequiredHeader(param.getName());
} else if (RestParamType.body == type) {
binding.setRequiredBody(true);
}
}
}
route.setRestBindingDefinition(binding);
// append options
Map<String, Object> options = new HashMap<>();
if (binding.getConsumes() != null) {
options.put("consumes", binding.getConsumes());
}
if (binding.getProduces() != null) {