forked from gitlab4j/gitlab4j-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGitLabApiClient.java
executable file
·1005 lines (893 loc) · 43.5 KB
/
GitLabApiClient.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.gitlab4j.api;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import org.gitlab4j.api.Constants.TokenType;
import org.gitlab4j.api.GitLabApi.ApiVersion;
import org.gitlab4j.api.utils.JacksonJson;
import org.gitlab4j.api.utils.MaskingLoggingFilter;
import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.JerseyClientBuilder;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.media.multipart.BodyPart;
import org.glassfish.jersey.media.multipart.Boundary;
import org.glassfish.jersey.media.multipart.FormDataBodyPart;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart;
/**
* This class utilizes the Jersey client package to communicate with a GitLab API endpoint.
*/
public class GitLabApiClient implements AutoCloseable {
protected static final String PRIVATE_TOKEN_HEADER = "PRIVATE-TOKEN";
protected static final String SUDO_HEADER = "Sudo";
protected static final String AUTHORIZATION_HEADER = "Authorization";
protected static final String X_GITLAB_TOKEN_HEADER = "X-Gitlab-Token";
private ClientConfig clientConfig;
private Client apiClient;
private String baseUrl;
private String hostUrl;
private TokenType tokenType = TokenType.PRIVATE;
private Supplier<String> authToken;
private String secretToken;
private boolean ignoreCertificateErrors;
private SSLContext openSslContext;
private HostnameVerifier openHostnameVerifier;
private Long sudoAsId;
private Integer connectTimeout;
private Integer readTimeout;
/**
* Construct an instance to communicate with a GitLab API server using the specified GitLab API version,
* server URL, private token, and secret token.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL to the GitLab API server
* @param privateToken the private token to authenticate with
*/
public GitLabApiClient(ApiVersion apiVersion, String hostUrl, String privateToken) {
this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, null);
}
/**
* Construct an instance to communicate with a GitLab API server using the specified GitLab API version,
* server URL, auth token type, private or access token, and secret token.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL to the GitLab API server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the token to authenticate with
*/
public GitLabApiClient(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken) {
this(apiVersion, hostUrl, tokenType, authToken, null);
}
/**
* Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified
* server URL, private token, and secret token.
*
* @param hostUrl the URL to the GitLab API server
* @param privateToken the private token to authenticate with
*/
public GitLabApiClient(String hostUrl, String privateToken) {
this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, null);
}
/**
* Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified
* server URL, private token, and secret token.
*
* @param hostUrl the URL to the GitLab API server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the token to authenticate with
*/
public GitLabApiClient(String hostUrl, TokenType tokenType, String authToken) {
this(ApiVersion.V4, hostUrl, tokenType, authToken, null);
}
/**
* Construct an instance to communicate with a GitLab API server using the specified GitLab API version,
* server URL, private token, and secret token.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL to the GitLab API server
* @param privateToken the private token to authenticate with
* @param secretToken use this token to validate received payloads
*/
public GitLabApiClient(ApiVersion apiVersion, String hostUrl, String privateToken, String secretToken) {
this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, secretToken, null);
}
/**
* Construct an instance to communicate with a GitLab API server using the specified GitLab API version,
* server URL, private token, and secret token.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL to the GitLab API server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the token to authenticate with
* @param secretToken use this token to validate received payloads
*/
public GitLabApiClient(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken) {
this(apiVersion, hostUrl, tokenType, authToken, secretToken, null);
}
/**
* Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified
* server URL, private token, and secret token.
*
* @param hostUrl the URL to the GitLab API server
* @param privateToken the private token to authenticate with
* @param secretToken use this token to validate received payloads
*/
public GitLabApiClient(String hostUrl, String privateToken, String secretToken) {
this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, secretToken, null);
}
/**
* Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified
* server URL, private token, and secret token.
*
* @param hostUrl the URL to the GitLab API server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the token to authenticate with
* @param secretToken use this token to validate received payloads
*/
public GitLabApiClient(String hostUrl, TokenType tokenType, String authToken, String secretToken) {
this(ApiVersion.V4, hostUrl, tokenType, authToken, secretToken, null);
}
/**
* Construct an instance to communicate with a GitLab API server using GitLab API version 4, and the specified
* server URL and private token.
*
* @param hostUrl the URL to the GitLab API server
* @param privateToken the private token to authenticate with
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties the properties given to Jersey's clientconfig
*/
public GitLabApiClient(String hostUrl, String privateToken, String secretToken, Map<String, Object> clientConfigProperties) {
this(ApiVersion.V4, hostUrl, TokenType.PRIVATE, privateToken, secretToken, clientConfigProperties);
}
/**
* Construct an instance to communicate with a GitLab API server using the specified GitLab API version,
* server URL and private token.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL to the GitLab API server
* @param privateToken the private token to authenticate with
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties the properties given to Jersey's clientconfig
*/
public GitLabApiClient(ApiVersion apiVersion, String hostUrl, String privateToken, String secretToken, Map<String, Object> clientConfigProperties) {
this(apiVersion, hostUrl, TokenType.PRIVATE, privateToken, secretToken, clientConfigProperties);
}
/**
* Construct an instance to communicate with a GitLab API server using the specified GitLab API version,
* server URL and private token.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL to the GitLab API server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the private token to authenticate with
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties the properties given to Jersey's clientconfig
*/
public GitLabApiClient(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken, Map<String, Object> clientConfigProperties) {
this(apiVersion, hostUrl, tokenType, authToken, secretToken, clientConfigProperties, false);
}
/**
* Construct an instance to communicate with a GitLab API server using the specified GitLab API version,
* server URL and private token.
*
* @param apiVersion the ApiVersion specifying which version of the API to use
* @param hostUrl the URL to the GitLab API server
* @param tokenType the type of auth the token is for, PRIVATE or ACCESS
* @param authToken the private token to authenticate with
* @param secretToken use this token to validate received payloads
* @param clientConfigProperties the properties given to Jersey's clientconfig
* @param debugging log http requests and responses
*/
public GitLabApiClient(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken, Map<String, Object> clientConfigProperties, boolean debugging) {
// Remove the trailing "/" from the hostUrl if present
this.hostUrl = (hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl);
this.baseUrl = this.hostUrl;
this.hostUrl += apiVersion.getApiNamespace();
this.tokenType = tokenType;
this.authToken = () -> authToken;
if (secretToken != null) {
secretToken = secretToken.trim();
secretToken = (secretToken.length() > 0 ? secretToken : null);
}
this.secretToken = secretToken;
clientConfig = new ClientConfig();
if (clientConfigProperties != null) {
if (clientConfigProperties.containsKey(ClientProperties.PROXY_URI)) {
clientConfig.connectorProvider(new ApacheConnectorProvider());
}
for (Map.Entry<String, Object> propertyEntry : clientConfigProperties.entrySet()) {
clientConfig.property(propertyEntry.getKey(), propertyEntry.getValue());
}
}
if (debugging) {
clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024 * 50 /* Log payloads up to 50K */));
clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY);
}
// Disable auto-discovery of feature and services lookup, this will force Jersey
// to use the features and services explicitly configured by gitlab4j
clientConfig.property(ClientProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
clientConfig.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);
clientConfig.register(JacksonJson.class);
clientConfig.register(JacksonFeature.class);
clientConfig.register(MultiPartFeature.class);
}
/**
* Close the underlying {@link Client} and its associated resources.
*/
@Override
public void close() {
if (apiClient != null) {
apiClient.close();
}
}
/**
* Enable the logging of the requests to and the responses from the GitLab server API.
*
* @param logger the Logger instance to log to
* @param level the logging level (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST)
* @param maxEntityLength maximum number of entity bytes to be logged. When logging if the maxEntitySize
* is reached, the entity logging will be truncated at maxEntitySize and "...more..." will be added at
* the end of the log entry. If maxEntitySize is <= 0, entity logging will be disabled
* @param maskedHeaderNames a list of header names that should have the values masked
*/
void enableRequestResponseLogging(Logger logger, Level level, int maxEntityLength, List<String> maskedHeaderNames) {
MaskingLoggingFilter loggingFilter = new MaskingLoggingFilter(logger, level, maxEntityLength, maskedHeaderNames);
clientConfig.register(loggingFilter);
// Recreate the Client instance if already created.
if (apiClient != null) {
createApiClient();
}
}
/**
* Sets the per request connect and read timeout.
*
* @param connectTimeout the per request connect timeout in milliseconds, can be null to use default
* @param readTimeout the per request read timeout in milliseconds, can be null to use default
*/
void setRequestTimeout(Integer connectTimeout, Integer readTimeout) {
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
}
/**
* Get the auth token being used by this client.
*
* @return the auth token being used by this client
*/
String getAuthToken() {
return (authToken.get());
}
/**
* Get the secret token.
*
* @return the secret token
*/
String getSecretToken() {
return (secretToken);
}
/**
* Get the TokenType this client is using.
*
* @return the TokenType this client is using
*/
TokenType getTokenType() {
return (tokenType);
}
/**
* Set the ID of the user to sudo as.
*
*/
Long getSudoAsId() {
return (sudoAsId);
}
/**
* Set the ID of the user to sudo as.
*
* @param sudoAsId the ID of the user to sudo as
*/
void setSudoAsId(Long sudoAsId) {
this.sudoAsId = sudoAsId;
}
/**
* Construct a REST URL with the specified path arguments.
*
* @param pathArgs variable list of arguments used to build the URI
* @return a REST URL with the specified path arguments
* @throws IOException if an error occurs while constructing the URL
*/
protected URL getApiUrl(Object... pathArgs) throws IOException {
String url = appendPathArgs(this.hostUrl, pathArgs);
return (new URL(url));
}
/**
* Construct a REST URL with the specified path arguments using
* Gitlab base url.
*
* @param pathArgs variable list of arguments used to build the URI
* @return a REST URL with the specified path arguments
* @throws IOException if an error occurs while constructing the URL
*/
protected URL getUrlWithBase(Object... pathArgs) throws IOException {
String url = appendPathArgs(this.baseUrl, pathArgs);
return (new URL(url));
}
private String appendPathArgs(String url, Object... pathArgs) {
StringBuilder urlBuilder = new StringBuilder(url);
for (Object pathArg : pathArgs) {
if (pathArg != null) {
urlBuilder.append("/");
urlBuilder.append(pathArg.toString());
}
}
return urlBuilder.toString();
}
/**
* Validates the secret token (X-GitLab-Token) header against the expected secret token, returns true if valid,
* otherwise returns false.
*
* @param response the Response instance sent from the GitLab server
* @return true if the response's secret token is valid, otherwise returns false
*/
protected boolean validateSecretToken(Response response) {
if (this.secretToken == null)
return (true);
String secretToken = response.getHeaderString(X_GITLAB_TOKEN_HEADER);
if (secretToken == null)
return (false);
return (this.secretToken.equals(secretToken));
}
/**
* Perform an HTTP GET call with the specified query parameters and path objects, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response get(MultivaluedMap<String, String> queryParams, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return (get(queryParams, url));
}
/**
* Perform an HTTP GET call with the specified query parameters and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param url the fully formed path to the GitLab API endpoint
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response get(MultivaluedMap<String, String> queryParams, URL url) {
return (invocation(url, queryParams).get());
}
/**
* Perform an HTTP GET call with the specified query parameters and path objects, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param accepts if non-empty will set the Accepts header to this value
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response getWithAccepts(MultivaluedMap<String, String> queryParams, String accepts, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return (getWithAccepts(queryParams, url, accepts));
}
/**
* Perform an HTTP GET call with the specified query parameters and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param url the fully formed path to the GitLab API endpoint
* @param accepts if non-empty will set the Accepts header to this value
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response getWithAccepts(MultivaluedMap<String, String> queryParams, URL url, String accepts) {
return (invocation(url, queryParams, accepts).get());
}
/**
* Perform an HTTP HEAD call with the specified query parameters and path objects, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response head(MultivaluedMap<String, String> queryParams, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return (head(queryParams, url));
}
/**
* Perform an HTTP HEAD call with the specified query parameters and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param url the fully formed path to the GitLab API endpoint
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response head(MultivaluedMap<String, String> queryParams, URL url) {
return (invocation(url, queryParams).head());
}
/**
* Perform an HTTP PATCH call with the specified query parameters and path objects, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response patch(MultivaluedMap<String, String> queryParams, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return (patch(queryParams, url));
}
/**
* Perform an HTTP PATCH call with the specified query parameters and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param url the fully formed path to the GitLab API endpoint
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response patch(MultivaluedMap<String, String> queryParams, URL url) {
Entity<?> empty = Entity.text("");
// use "X-HTTP-Method-Override" header on POST to override to unsupported PATCH
return (invocation(url, queryParams)
.header("X-HTTP-Method-Override", "PATCH").post(empty));
}
/**
* Perform an HTTP POST call with the specified form data and path objects, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param formData the Form containing the name/value pairs
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response post(Form formData, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return post(formData, url);
}
/**
* Perform an HTTP POST call with the specified form data and path objects, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param pathArgs variable list of arguments used to build the URI
* @return a Response instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response post(MultivaluedMap<String, String> queryParams, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return post(queryParams, url);
}
/**
* Perform an HTTP POST call with the specified form data and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param formData the Form containing the name/value pairs
* @param url the fully formed path to the GitLab API endpoint
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response post(Form formData, URL url) {
if (formData instanceof GitLabApiForm) {
return (invocation(url, null).post(Entity.entity(formData.asMap(), MediaType.APPLICATION_FORM_URLENCODED_TYPE)));
} else if (formData != null) {
return (invocation(url, null).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE)));
} else {
return (invocation(url, null).post(Entity.entity(new Form(), MediaType.APPLICATION_FORM_URLENCODED_TYPE)));
}
}
/**
* Perform an HTTP POST call with the specified form data and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parametersformData the Form containing the name/value pairs
* @param url the fully formed path to the GitLab API endpoint
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response post(MultivaluedMap<String, String> queryParams, URL url) {
return (invocation(url, queryParams).post(Entity.entity(new Form(), MediaType.APPLICATION_FORM_URLENCODED_TYPE)));
}
/**
* Perform an HTTP POST call with the specified payload object and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param payload the object instance that will be serialized to JSON and used as the POST data
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response post(Object payload, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
Entity<?> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
return (invocation(url, null).post(entity));
}
/**
* Perform an HTTP POST call with the specified StreamingOutput, MediaType, and path objects, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param stream the StreamingOutput instance that contains the POST data
* @param mediaType the content-type of the POST data
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response post(StreamingOutput stream, String mediaType, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return (invocation(url, null).post(Entity.entity(stream, mediaType)));
}
/**
* Perform a file upload using the specified media type, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param name the name for the form field that contains the file name
* @param fileToUpload a File instance pointing to the file to upload
* @param mediaTypeString unused; will be removed in the next major version
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response upload(String name, File fileToUpload, String mediaTypeString, Object... pathArgs) throws IOException {
return upload(name, fileToUpload, mediaTypeString, null, pathArgs);
}
/**
* Perform a file upload using the specified media type, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param name the name for the form field that contains the file name
* @param fileToUpload a File instance pointing to the file to upload
* @param mediaTypeString unused; will be removed in the next major version
* @param formData the Form containing the name/value pairs
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response upload(String name, File fileToUpload, String mediaTypeString, Form formData, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return (upload(name, fileToUpload, mediaTypeString, formData, url));
}
/**
* Perform a file upload using multipart/form-data, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param name the name for the form field that contains the file name
* @param fileToUpload a File instance pointing to the file to upload
* @param mediaTypeString unused; will be removed in the next major version
* @param formData the Form containing the name/value pairs
* @param url the fully formed path to the GitLab API endpoint
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response upload(String name, File fileToUpload, String mediaTypeString, Form formData, URL url) throws IOException {
FileDataBodyPart filePart = new FileDataBodyPart(name, fileToUpload);
return upload(filePart, formData, url);
}
protected Response upload(String name, InputStream inputStream, String filename, String mediaTypeString, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return (upload(name, inputStream, filename, mediaTypeString, null, url));
}
protected Response upload(String name, InputStream inputStream, String filename, String mediaTypeString, Form formData, URL url) throws IOException {
StreamDataBodyPart streamDataBodyPart = new StreamDataBodyPart(name, inputStream, filename);
return upload(streamDataBodyPart, formData, url);
}
protected Response upload(BodyPart bodyPart, Form formData, URL url) throws IOException {
try (FormDataMultiPart multiPart = new FormDataMultiPart()) {
if (formData != null) {
formData.asMap().forEach((key, values) -> {
if (values != null) {
values.forEach(value -> multiPart.field(key, value));
}
});
}
multiPart.bodyPart(bodyPart);
final Entity<?> entity = Entity.entity(multiPart, Boundary.addBoundary(multiPart.getMediaType()));
return (invocation(url, null).post(entity));
}
}
/**
* Perform a file upload using multipart/form-data using the HTTP PUT method, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param name the name for the form field that contains the file name
* @param fileToUpload a File instance pointing to the file to upload
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response putUpload(String name, File fileToUpload, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return (putUpload(name, fileToUpload, url));
}
/**
* Perform a file upload using multipart/form-data using the HTTP PUT method, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param name the name for the form field that contains the file name
* @param fileToUpload a File instance pointing to the file to upload
* @param url the fully formed path to the GitLab API endpoint
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response putUpload(String name, File fileToUpload, URL url) throws IOException {
try (MultiPart multiPart = new FormDataMultiPart()) {
if(fileToUpload == null) {
multiPart.bodyPart(new FormDataBodyPart(name, "", MediaType.APPLICATION_OCTET_STREAM_TYPE));
} else {
multiPart.bodyPart(new FileDataBodyPart(name, fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE));
}
final Entity<?> entity = Entity.entity(multiPart, Boundary.addBoundary(multiPart.getMediaType()));
return (invocation(url, null).put(entity));
}
}
/**
* Perform an HTTP PUT call with the specified form data and path objects, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response put(MultivaluedMap<String, String> queryParams, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return (put(queryParams, url));
}
/**
* Perform an HTTP PUT call with the specified form data and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param url the fully formed path to the GitLab API endpoint
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response put(MultivaluedMap<String, String> queryParams, URL url) {
if (queryParams == null || queryParams.isEmpty()) {
Entity<?> empty = Entity.text("");
return (invocation(url, null).put(empty));
} else {
return (invocation(url, null).put(Entity.entity(queryParams, MediaType.APPLICATION_FORM_URLENCODED_TYPE)));
}
}
/**
* Perform an HTTP PUT call with the specified form data and path objects, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param formData the Form containing the name/value pairs
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response put(Form formData, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
return put(formData, url);
}
/**
* Perform an HTTP PUT call with the specified form data and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param formData the Form containing the name/value pairs
* @param url the fully formed path to the GitLab API endpoint
* @return a ClientResponse instance with the data returned from the endpoint
*/
protected Response put(Form formData, URL url) {
if (formData instanceof GitLabApiForm)
return (invocation(url, null).put(Entity.entity(formData.asMap(), MediaType.APPLICATION_FORM_URLENCODED_TYPE)));
else
return (invocation(url, null).put(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED_TYPE)));
}
/**
* Perform an HTTP PUT call with the specified payload object and URL, returning
* a ClientResponse instance with the data returned from the endpoint.
*
* @param payload the object instance that will be serialized to JSON and used as the PUT data
* @param pathArgs variable list of arguments used to build the URI
* @return a ClientResponse instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response put(Object payload, Object... pathArgs) throws IOException {
URL url = getApiUrl(pathArgs);
Entity<?> entity = Entity.entity(payload, MediaType.APPLICATION_JSON);
return (invocation(url, null).put(entity));
}
/**
* Perform an HTTP DELETE call with the specified form data and path objects, returning
* a Response instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param pathArgs variable list of arguments used to build the URI
* @return a Response instance with the data returned from the endpoint
* @throws IOException if an error occurs while constructing the URL
*/
protected Response delete(MultivaluedMap<String, String> queryParams, Object... pathArgs) throws IOException {
return (delete(queryParams, getApiUrl(pathArgs)));
}
/**
* Perform an HTTP DELETE call with the specified form data and URL, returning
* a Response instance with the data returned from the endpoint.
*
* @param queryParams multivalue map of request parameters
* @param url the fully formed path to the GitLab API endpoint
* @return a Response instance with the data returned from the endpoint
*/
protected Response delete(MultivaluedMap<String, String> queryParams, URL url) {
return (invocation(url, queryParams).delete());
}
protected Invocation.Builder invocation(URL url, MultivaluedMap<String, String> queryParams) {
return (invocation(url, queryParams, MediaType.APPLICATION_JSON));
}
protected Client createApiClient() {
// Explicitly use an instance of the JerseyClientBuilder, this allows this
// library to work when both Jersey and Resteasy are present
ClientBuilder clientBuilder = new JerseyClientBuilder().withConfig(clientConfig);
// Register JacksonJson as the ObjectMapper provider.
clientBuilder.register(JacksonJson.class);
clientBuilder.register(JacksonFeature.class);
if (ignoreCertificateErrors) {
clientBuilder.sslContext(openSslContext).hostnameVerifier(openHostnameVerifier);
}
apiClient = clientBuilder.build();
return (apiClient);
}
protected Invocation.Builder invocation(URL url, MultivaluedMap<String, String> queryParams, String accept) {
if (apiClient == null) {
createApiClient();
}
WebTarget target = apiClient.target(url.toExternalForm()).property(ClientProperties.FOLLOW_REDIRECTS, true);
if (queryParams != null) {
for (Map.Entry<String, List<String>> param : queryParams.entrySet()) {
target = target.queryParam(param.getKey(), param.getValue().toArray());
}
}
String authHeader = (tokenType == TokenType.OAUTH2_ACCESS ? AUTHORIZATION_HEADER : PRIVATE_TOKEN_HEADER);
String authValue = (tokenType == TokenType.OAUTH2_ACCESS ? "Bearer " + authToken.get() : authToken.get());
Invocation.Builder builder = target.request();
if (accept == null || accept.trim().length() == 0) {
builder = builder.header(authHeader, authValue);
} else {
builder = builder.header(authHeader, authValue).accept(accept);
}
// If sudo as ID is set add the Sudo header
if (sudoAsId != null && sudoAsId.intValue() > 0)
builder = builder.header(SUDO_HEADER, sudoAsId);
// Set the per request connect timeout
if (connectTimeout != null) {
builder.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
}
// Set the per request read timeout
if (readTimeout != null) {
builder.property(ClientProperties.READ_TIMEOUT, readTimeout);
}
return (builder);
}
/**
* Used to set the host URL to be used by OAUTH2 login in GitLabApi.
*/
void setHostUrlToBaseUrl() {
this.hostUrl = this.baseUrl;
}
/**
* Returns true if the API is setup to ignore SSL certificate errors, otherwise returns false.
*
* @return true if the API is setup to ignore SSL certificate errors, otherwise returns false
*/
public boolean getIgnoreCertificateErrors() {
return (ignoreCertificateErrors);
}
/**
* Sets up the Jersey system ignore SSL certificate errors or not.
*
* @param ignoreCertificateErrors if true will set up the Jersey system ignore SSL certificate errors
*/
public void setIgnoreCertificateErrors(boolean ignoreCertificateErrors) {
if (this.ignoreCertificateErrors == ignoreCertificateErrors) {
return;
}
if (!ignoreCertificateErrors) {
this.ignoreCertificateErrors = false;
openSslContext = null;
openHostnameVerifier = null;
apiClient = null;
} else {
if (setupIgnoreCertificateErrors()) {
this.ignoreCertificateErrors = true;
apiClient = null;
} else {
this.ignoreCertificateErrors = false;
apiClient = null;
throw new RuntimeException("Unable to ignore certificate errors.");
}
}
}
/**
* Sets up Jersey client to ignore certificate errors.
*
* @return true if successful at setting up to ignore certificate errors, otherwise returns false.
*/
private boolean setupIgnoreCertificateErrors() {
// Create a TrustManager that trusts all certificates
TrustManager[] trustAllCerts = new TrustManager[] { new X509ExtendedTrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
openSslContext = sslContext;
openHostnameVerifier = hostnameVerifier;
} catch (GeneralSecurityException ex) {
openSslContext = null;
openHostnameVerifier = null;
return (false);
}
return (true);
}
/**
* Set auth token supplier for gitlab api client.
* @param authTokenSupplier - supplier which provide actual auth token