-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiClient.java
More file actions
1600 lines (1465 loc) · 46.8 KB
/
ApiClient.java
File metadata and controls
1600 lines (1465 loc) · 46.8 KB
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
/*
* STACKIT Network Load Balancer API
* This API offers an interface to provision and manage load balancing servers in your STACKIT project. It also has the possibility of pooling target servers for load balancing purposes. For each load balancer provided, two VMs are deployed in your OpenStack project subject to a fee.
*
* The version of the OpenAPI document: 2.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package cloud.stackit.sdk.loadbalancer;
import cloud.stackit.sdk.core.KeyFlowAuthenticator;
import cloud.stackit.sdk.core.config.CoreConfiguration;
import cloud.stackit.sdk.core.exception.ApiException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.*;
import okhttp3.*;
import okhttp3.internal.http.HttpMethod;
import okhttp3.internal.tls.OkHostnameVerifier;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.logging.HttpLoggingInterceptor.Level;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
/** ApiClient class. */
public class ApiClient {
protected String basePath = "https://load-balancer.api.stackit.cloud";
protected List<ServerConfiguration> servers =
new ArrayList<ServerConfiguration>(
Arrays.asList(
new ServerConfiguration(
"https://load-balancer.api.stackit.cloud",
"No description provided",
new HashMap<String, ServerVariable>() {
{
put(
"region",
new ServerVariable(
"No description provided",
"global",
new HashSet<String>()));
}
})));
protected Integer serverIndex = 0;
protected Map<String, String> serverVariables = null;
protected boolean debugging = false;
protected Map<String, String> defaultHeaderMap = new HashMap<String, String>();
protected Map<String, String> defaultCookieMap = new HashMap<String, String>();
protected String tempFolderPath = null;
protected DateFormat dateFormat;
protected DateFormat datetimeFormat;
protected boolean lenientDatetimeFormat;
protected int dateLength;
protected InputStream sslCaCert;
protected boolean verifyingSsl;
protected KeyManager[] keyManagers;
protected String tlsServerName;
protected OkHttpClient httpClient;
protected JSON json;
protected HttpLoggingInterceptor loggingInterceptor;
protected CoreConfiguration configuration;
/**
* Basic constructor for ApiClient.
*
* <p>Not recommended for production use, use the one with the OkHttpClient parameter instead.
*
* @throws IOException thrown when a file can not be found
*/
public ApiClient() throws IOException {
this(null, new CoreConfiguration());
}
/**
* Basic constructor for ApiClient
*
* <p>Not recommended for production use, use the one with the OkHttpClient parameter instead.
*
* @param config a {@link cloud.stackit.sdk.core.config.CoreConfiguration} object
* @throws IOException thrown when a file can not be found
*/
public ApiClient(CoreConfiguration config) throws IOException {
this(null, config);
}
/**
* Constructor for ApiClient with OkHttpClient parameter. Recommended for production use.
*
* @param httpClient a OkHttpClient object
* @throws IOException thrown when a file can not be found
*/
public ApiClient(OkHttpClient httpClient) throws IOException {
this(httpClient, new CoreConfiguration());
}
/**
* Constructor for ApiClient with OkHttpClient parameter. Recommended for production use.
*
* @param httpClient a OkHttpClient object
* @param config a {@link cloud.stackit.sdk.core.config.CoreConfiguration} object
* @throws IOException thrown when a file can not be found
*/
public ApiClient(OkHttpClient httpClient, CoreConfiguration config) throws IOException {
init();
if (config.getCustomEndpoint() != null && !config.getCustomEndpoint().trim().isEmpty()) {
basePath = config.getCustomEndpoint();
}
if (config.getDefaultHeader() != null) {
defaultHeaderMap = config.getDefaultHeader();
}
this.configuration = config;
if (httpClient == null) {
initHttpClient();
KeyFlowAuthenticator authenticator = new KeyFlowAuthenticator(this.httpClient, config);
this.httpClient = this.httpClient.newBuilder().authenticator(authenticator).build();
} else {
// Authorization has to be configured manually in case a custom http client object is
// passed
this.httpClient = httpClient;
}
}
protected void initHttpClient() {
initHttpClient(Collections.<Interceptor>emptyList());
}
protected void initHttpClient(List<Interceptor> interceptors) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addNetworkInterceptor(getProgressInterceptor());
for (Interceptor interceptor : interceptors) {
builder.addInterceptor(interceptor);
}
httpClient = builder.build();
}
protected void init() {
verifyingSsl = true;
json = new JSON();
// Set default User-Agent.
setUserAgent("stackit-sdk-java/loadbalancer");
}
/**
* Get base path
*
* @return Base path
*/
public String getBasePath() {
return basePath;
}
/**
* Set base path
*
* @param basePath Base path of the URL (e.g https://load-balancer.api.stackit.cloud)
* @return An instance of ApiClient
*/
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
this.serverIndex = null;
return this;
}
public List<ServerConfiguration> getServers() {
return servers;
}
public ApiClient setServers(List<ServerConfiguration> servers) {
this.servers = servers;
return this;
}
public Integer getServerIndex() {
return serverIndex;
}
public ApiClient setServerIndex(Integer serverIndex) {
this.serverIndex = serverIndex;
return this;
}
public Map<String, String> getServerVariables() {
return serverVariables;
}
public ApiClient setServerVariables(Map<String, String> serverVariables) {
this.serverVariables = serverVariables;
return this;
}
/**
* Get HTTP client
*
* @return An instance of OkHttpClient
*/
public OkHttpClient getHttpClient() {
return httpClient;
}
/**
* Get JSON
*
* @return JSON object
*/
public JSON getJSON() {
return json;
}
/**
* Set JSON
*
* @param json JSON object
* @return Api client
*/
public ApiClient setJSON(JSON json) {
this.json = json;
return this;
}
/**
* True if isVerifyingSsl flag is on
*
* @return True if isVerifySsl flag is on
*/
public boolean isVerifyingSsl() {
return verifyingSsl;
}
/**
* Configure whether to verify certificate and hostname when making https requests. Default to
* true. NOTE: Do NOT set to false in production code, otherwise you would face multiple types
* of cryptographic attacks.
*
* @param verifyingSsl True to verify TLS/SSL connection
* @return ApiClient
*/
public ApiClient setVerifyingSsl(boolean verifyingSsl) {
this.verifyingSsl = verifyingSsl;
applySslSettings();
return this;
}
/**
* Get SSL CA cert.
*
* @return Input stream to the SSL CA cert
*/
public InputStream getSslCaCert() {
return sslCaCert;
}
/**
* Configure the CA certificate to be trusted when making https requests. Use null to reset to
* default.
*
* @param sslCaCert input stream for SSL CA cert
* @return ApiClient
*/
public ApiClient setSslCaCert(InputStream sslCaCert) {
this.sslCaCert = sslCaCert;
applySslSettings();
return this;
}
/**
* Getter for the field <code>keyManagers</code>.
*
* @return an array of {@link javax.net.ssl.KeyManager} objects
*/
public KeyManager[] getKeyManagers() {
return keyManagers;
}
/**
* Configure client keys to use for authorization in an SSL session. Use null to reset to
* default.
*
* @param managers The KeyManagers to use
* @return ApiClient
*/
public ApiClient setKeyManagers(KeyManager[] managers) {
this.keyManagers = managers;
applySslSettings();
return this;
}
/**
* Get TLS server name for SNI (Server Name Indication).
*
* @return The TLS server name
*/
public String getTlsServerName() {
return tlsServerName;
}
/**
* Set TLS server name for SNI (Server Name Indication). This is used to verify the server
* certificate against a specific hostname instead of the hostname in the URL.
*
* @param tlsServerName The TLS server name to use for certificate verification
* @return ApiClient
*/
public ApiClient setTlsServerName(String tlsServerName) {
this.tlsServerName = tlsServerName;
applySslSettings();
return this;
}
/**
* Getter for the field <code>dateFormat</code>.
*
* @return a {@link java.text.DateFormat} object
*/
public DateFormat getDateFormat() {
return dateFormat;
}
/**
* Setter for the field <code>dateFormat</code>.
*
* @param dateFormat a {@link java.text.DateFormat} object
* @return a {@link cloud.stackit.sdk.loadbalancer.ApiClient} object
*/
public ApiClient setDateFormat(DateFormat dateFormat) {
JSON.setDateFormat(dateFormat);
return this;
}
/**
* Set SqlDateFormat.
*
* @param dateFormat a {@link java.text.DateFormat} object
* @return a {@link cloud.stackit.sdk.loadbalancer.ApiClient} object
*/
public ApiClient setSqlDateFormat(DateFormat dateFormat) {
JSON.setSqlDateFormat(dateFormat);
return this;
}
/**
* Set OffsetDateTimeFormat.
*
* @param dateFormat a {@link java.time.format.DateTimeFormatter} object
* @return a {@link cloud.stackit.sdk.loadbalancer.ApiClient} object
*/
public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
JSON.setOffsetDateTimeFormat(dateFormat);
return this;
}
/**
* Set LocalDateFormat.
*
* @param dateFormat a {@link java.time.format.DateTimeFormatter} object
* @return a {@link cloud.stackit.sdk.loadbalancer.ApiClient} object
*/
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
JSON.setLocalDateFormat(dateFormat);
return this;
}
/**
* Set LenientOnJson.
*
* @param lenientOnJson a boolean
* @return a {@link cloud.stackit.sdk.loadbalancer.ApiClient} object
*/
public ApiClient setLenientOnJson(boolean lenientOnJson) {
JSON.setLenientOnJson(lenientOnJson);
return this;
}
/**
* Set the User-Agent header's value (by adding to the default header map).
*
* @param userAgent HTTP request's user agent
* @return ApiClient
*/
public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent);
return this;
}
/**
* Add a default header.
*
* @param key The header's key
* @param value The header's value
* @return ApiClient
*/
public ApiClient addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
return this;
}
/**
* Add a default cookie.
*
* @param key The cookie's key
* @param value The cookie's value
* @return ApiClient
*/
public ApiClient addDefaultCookie(String key, String value) {
defaultCookieMap.put(key, value);
return this;
}
/**
* Check that whether debugging is enabled for this API client.
*
* @return True if debugging is enabled, false otherwise.
*/
public boolean isDebugging() {
return debugging;
}
/**
* Enable/disable debugging for this API client.
*
* @param debugging To enable (true) or disable (false) debugging
* @return ApiClient
*/
public ApiClient setDebugging(boolean debugging) {
if (debugging != this.debugging) {
if (debugging) {
loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(Level.BODY);
httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build();
} else {
final OkHttpClient.Builder builder = httpClient.newBuilder();
builder.interceptors().remove(loggingInterceptor);
httpClient = builder.build();
loggingInterceptor = null;
}
}
this.debugging = debugging;
return this;
}
/**
* The path of temporary folder used to store downloaded files from endpoints with file
* response. The default value is <code>null</code>, i.e. using the system's default temporary
* folder.
*
* @see <a
* href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempFile(java.lang.String,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...)">createTempFile</a>
* @return Temporary folder path
*/
public String getTempFolderPath() {
return tempFolderPath;
}
/**
* Set the temporary folder path (for downloading files)
*
* @param tempFolderPath Temporary folder path
* @return ApiClient
*/
public ApiClient setTempFolderPath(String tempFolderPath) {
this.tempFolderPath = tempFolderPath;
return this;
}
/**
* Get connection timeout (in milliseconds).
*
* @return Timeout in milliseconds
*/
public int getConnectTimeout() {
return httpClient.connectTimeoutMillis();
}
/**
* Sets the connect timeout (in milliseconds). A value of 0 means no timeout, otherwise values
* must be between 1 and {@link java.lang.Integer#MAX_VALUE}.
*
* @param connectionTimeout connection timeout in milliseconds
* @return Api client
*/
public ApiClient setConnectTimeout(int connectionTimeout) {
httpClient =
httpClient
.newBuilder()
.connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS)
.build();
return this;
}
/**
* Get read timeout (in milliseconds).
*
* @return Timeout in milliseconds
*/
public int getReadTimeout() {
return httpClient.readTimeoutMillis();
}
/**
* Sets the read timeout (in milliseconds). A value of 0 means no timeout, otherwise values must
* be between 1 and {@link java.lang.Integer#MAX_VALUE}.
*
* @param readTimeout read timeout in milliseconds
* @return Api client
*/
public ApiClient setReadTimeout(int readTimeout) {
httpClient =
httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build();
return this;
}
/**
* Get write timeout (in milliseconds).
*
* @return Timeout in milliseconds
*/
public int getWriteTimeout() {
return httpClient.writeTimeoutMillis();
}
/**
* Sets the write timeout (in milliseconds). A value of 0 means no timeout, otherwise values
* must be between 1 and {@link java.lang.Integer#MAX_VALUE}.
*
* @param writeTimeout connection timeout in milliseconds
* @return Api client
*/
public ApiClient setWriteTimeout(int writeTimeout) {
httpClient =
httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build();
return this;
}
/**
* Format the given parameter object into string.
*
* @param param Parameter
* @return String representation of the parameter
*/
public String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date
|| param instanceof OffsetDateTime
|| param instanceof LocalDate) {
// Serialize to json string and remove the " enclosing characters
String jsonStr = JSON.serialize(param);
return jsonStr.substring(1, jsonStr.length() - 1);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for (Object o : (Collection) param) {
if (b.length() > 0) {
b.append(",");
}
b.append(o);
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/**
* Formats the specified query parameter to a list containing a single {@code Pair} object.
*
* <p>Note that {@code value} must not be a collection.
*
* @param name The name of the parameter.
* @param value The value of the parameter.
* @return A list containing a single {@code Pair} object.
*/
public List<Pair> parameterToPair(String name, Object value) {
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null || value instanceof Collection) {
return params;
}
params.add(new Pair(name, parameterToString(value)));
return params;
}
/**
* Formats the specified collection query parameters to a list of {@code Pair} objects.
*
* <p>Note that the values of each of the returned Pair objects are percent-encoded.
*
* @param collectionFormat The collection format of the parameter.
* @param name The name of the parameter.
* @param value The value of the parameter.
* @return A list of {@code Pair} objects.
*/
public List<Pair> parameterToPairs(String collectionFormat, String name, Collection<?> value) {
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null || value.isEmpty()) {
return params;
}
// create the params based on the collection format
if ("multi".equals(collectionFormat)) {
for (Object item : value) {
params.add(new Pair(name, escapeString(parameterToString(item))));
}
return params;
}
// collectionFormat is assumed to be "csv" by default
String delimiter = ",";
// escape all delimiters except commas, which are URI reserved
// characters
if ("ssv".equals(collectionFormat)) {
delimiter = escapeString(" ");
} else if ("tsv".equals(collectionFormat)) {
delimiter = escapeString("\t");
} else if ("pipes".equals(collectionFormat)) {
delimiter = escapeString("|");
}
StringBuilder sb = new StringBuilder();
for (Object item : value) {
sb.append(delimiter);
sb.append(escapeString(parameterToString(item)));
}
params.add(new Pair(name, sb.substring(delimiter.length())));
return params;
}
/**
* Formats the specified free-form query parameters to a list of {@code Pair} objects.
*
* @param value The free-form query parameters.
* @return A list of {@code Pair} objects.
*/
public List<Pair> freeFormParameterToPairs(Object value) {
List<Pair> params = new ArrayList<>();
// preconditions
if (value == null || !(value instanceof Map)) {
return params;
}
@SuppressWarnings("unchecked")
final Map<String, Object> valuesMap = (Map<String, Object>) value;
for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
params.add(new Pair(entry.getKey(), parameterToString(entry.getValue())));
}
return params;
}
/**
* Formats the specified collection path parameter to a string value.
*
* @param collectionFormat The collection format of the parameter.
* @param value The value of the parameter.
* @return String representation of the parameter
*/
public String collectionPathParameterToString(String collectionFormat, Collection value) {
// create the value based on the collection format
if ("multi".equals(collectionFormat)) {
// not valid for path params
return parameterToString(value);
}
// collectionFormat is assumed to be "csv" by default
String delimiter = ",";
if ("ssv".equals(collectionFormat)) {
delimiter = " ";
} else if ("tsv".equals(collectionFormat)) {
delimiter = "\t";
} else if ("pipes".equals(collectionFormat)) {
delimiter = "|";
}
StringBuilder sb = new StringBuilder();
for (Object item : value) {
sb.append(delimiter);
sb.append(parameterToString(item));
}
return sb.substring(delimiter.length());
}
/**
* Sanitize filename by removing path. e.g. ../../sun.gif becomes sun.gif
*
* @param filename The filename to be sanitized
* @return The sanitized filename
*/
public String sanitizeFilename(String filename) {
return filename.replaceFirst("^.*[/\\\\]", "");
}
/**
* Check if the given MIME is a JSON MIME. JSON MIME examples: application/json
* application/json; charset=UTF8 APPLICATION/JSON application/vnd.company+json "* / *" is also
* default to JSON
*
* @param mime MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public boolean isJsonMime(String mime) {
String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$";
return mime != null && (mime.matches(jsonMime) || mime.equals("*/*"));
}
/**
* Select the Accept header's value from the given accepts array: if JSON exists in the given
* array, use it; otherwise use all of them (joining into a string)
*
* @param accepts The accepts array to select from
* @return The Accept header to use. If the given array is empty, null will be returned (not to
* set the Accept header explicitly).
*/
public String selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) {
return null;
}
for (String accept : accepts) {
if (isJsonMime(accept)) {
return accept;
}
}
return StringUtil.join(accepts, ",");
}
/**
* Select the Content-Type header's value from the given array: if JSON exists in the given
* array, use it; otherwise use the first one of the array.
*
* @param contentTypes The Content-Type array to select from
* @return The Content-Type header to use. If the given array is empty, returns null. If it
* matches "any", JSON will be used.
*/
public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) {
return null;
}
if (contentTypes[0].equals("*/*")) {
return "application/json";
}
for (String contentType : contentTypes) {
if (isJsonMime(contentType)) {
return contentType;
}
}
return contentTypes[0];
}
/**
* Escape the given string to be used as URL query value.
*
* @param str String to be escaped
* @return Escaped string
*/
public String escapeString(String str) {
try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
return str;
}
}
/**
* Deserialize response body to Java object, according to the return type and the Content-Type
* response header.
*
* @param <T> Type
* @param response HTTP response
* @param returnType The type of the Java object
* @return The deserialized Java object
* @throws cloud.stackit.sdk.core.exception.ApiException If fail to deserialize response body,
* i.e. cannot read response body or the Content-Type of the response is not supported.
*/
@SuppressWarnings("unchecked")
public <T> T deserialize(Response response, Type returnType) throws ApiException {
if (response == null || returnType == null) {
return null;
}
if ("byte[]".equals(returnType.toString())) {
// Handle binary response (byte array).
try {
return (T) response.body().bytes();
} catch (IOException e) {
throw new ApiException(e);
}
} else if (returnType.equals(File.class)) {
// Handle file downloading.
return (T) downloadFileFromResponse(response);
}
ResponseBody respBody = response.body();
if (respBody == null) {
return null;
}
String contentType = response.headers().get("Content-Type");
if (contentType == null) {
// ensuring a default content type
contentType = "application/json";
}
try {
if (isJsonMime(contentType)) {
if (returnType.equals(String.class)) {
String respBodyString = respBody.string();
if (respBodyString.isEmpty()) {
return null;
}
// Use String-based deserialize for String return type with fallback
return JSON.deserialize(respBodyString, returnType);
} else {
// Use InputStream-based deserialize which supports responses > 2GB
return JSON.deserialize(respBody.byteStream(), returnType);
}
} else if (returnType.equals(String.class)) {
String respBodyString = respBody.string();
if (respBodyString.isEmpty()) {
return null;
}
// Expecting string, return the raw response body.
return (T) respBodyString;
} else {
throw new ApiException(
"Content type \""
+ contentType
+ "\" is not supported for type: "
+ returnType,
response.code(),
response.headers().toMultimap(),
response.body().string());
}
} catch (IOException e) {
throw new ApiException(e);
}
}
/**
* Serialize the given Java object into request body according to the object's class and the
* request Content-Type.
*
* @param obj The Java object
* @param contentType The request Content-Type
* @return The serialized request body
* @throws cloud.stackit.sdk.core.exception.ApiException If fail to serialize the given object
*/
public RequestBody serialize(Object obj, String contentType) throws ApiException {
if (obj instanceof byte[]) {
// Binary (byte array) body parameter support.
return RequestBody.create((byte[]) obj, MediaType.parse(contentType));
} else if (obj instanceof File) {
// File body parameter support.
return RequestBody.create((File) obj, MediaType.parse(contentType));
} else if ("text/plain".equals(contentType) && obj instanceof String) {
return RequestBody.create((String) obj, MediaType.parse(contentType));
} else if (isJsonMime(contentType)) {
String content;
if (obj != null) {
content = JSON.serialize(obj);
} else {
content = null;
}
return RequestBody.create(content, MediaType.parse(contentType));
} else if (obj instanceof String) {
return RequestBody.create((String) obj, MediaType.parse(contentType));
} else {
throw new ApiException("Content type \"" + contentType + "\" is not supported");
}
}
/**
* Download file from the given response.
*
* @param response An instance of the Response object
* @throws cloud.stackit.sdk.core.exception.ApiException If fail to read file content from
* response and write to disk
* @return Downloaded file
*/
public File downloadFileFromResponse(Response response) throws ApiException {
try {
File file = prepareDownloadFile(response);
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(response.body().source());
sink.close();
return file;
} catch (IOException e) {
throw new ApiException(e);
}
}
/**
* Prepare file for download
*
* @param response An instance of the Response object
* @return Prepared file for the download
* @throws java.io.IOException If fail to prepare file for download
*/
public File prepareDownloadFile(Response response) throws IOException {
String filename = null;
String contentDisposition = response.header("Content-Disposition");
if (contentDisposition != null && !"".equals(contentDisposition)) {
// Get filename from the Content-Disposition header.
Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?");
Matcher matcher = pattern.matcher(contentDisposition);
if (matcher.find()) {
filename = sanitizeFilename(matcher.group(1));
}
}
String prefix = null;
String suffix = null;
if (filename == null) {
prefix = "download-";
suffix = "";
} else {
int pos = filename.lastIndexOf(".");
if (pos == -1) {
prefix = filename + "-";
} else {
prefix = filename.substring(0, pos) + "-";
suffix = filename.substring(pos);
}
// Files.createTempFile requires the prefix to be at least three characters long
if (prefix.length() < 3) prefix = "download-";
}
if (tempFolderPath == null) return Files.createTempFile(prefix, suffix).toFile();
else return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile();
}
/**
* {@link #execute(Call, Type)}
*
* @param <T> Type
* @param call An instance of the Call object
* @return ApiResponse<T>
* @throws cloud.stackit.sdk.core.exception.ApiException If fail to execute the call
*/
public <T> ApiResponse<T> execute(Call call) throws ApiException {
return execute(call, null);
}
/**
* Execute HTTP call and deserialize the HTTP response body into the given return type.
*
* @param returnType The return type used to deserialize HTTP response body
* @param <T> The return type corresponding to (same with) returnType
* @param call Call
* @return ApiResponse object containing response status, headers and data, which is a Java
* object deserialized from response body and would be null when returnType is null.
* @throws cloud.stackit.sdk.core.exception.ApiException If fail to execute the call
*/