/
ApiClient.mustache
1615 lines (1465 loc) · 58.3 KB
/
ApiClient.mustache
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
{{>licenseInfo}}
package {{invokerPackage}};
{{#dynamicOperations}}
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.Parameter.StyleEnum;
import io.swagger.v3.parser.OpenAPIV3Parser;
{{/dynamicOperations}}
import okhttp3.*;
import okhttp3.internal.http.HttpMethod;
import okhttp3.internal.tls.OkHostnameVerifier;
import okhttp3.logging.HttpLoggingInterceptor;
import okhttp3.logging.HttpLoggingInterceptor.Level;
import okio.BufferedSink;
import okio.Okio;
{{#joda}}
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;
{{/joda}}
{{#threetenbp}}
import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;
{{/threetenbp}}
{{#hasOAuthMethods}}
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.common.message.types.GrantType;
{{/hasOAuthMethods}}
import javax.net.ssl.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URLConnection;
import java.net.URLEncoder;
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.security.cert.X509Certificate;
import java.text.DateFormat;
{{#java8}}
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
{{/java8}}
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import {{invokerPackage}}.auth.Authentication;
import {{invokerPackage}}.auth.HttpBasicAuth;
import {{invokerPackage}}.auth.HttpBearerAuth;
import {{invokerPackage}}.auth.ApiKeyAuth;
{{#hasOAuthMethods}}
import {{invokerPackage}}.auth.OAuth;
import {{invokerPackage}}.auth.RetryingOAuth;
import {{invokerPackage}}.auth.OAuthFlow;
{{/hasOAuthMethods}}
public class ApiClient {
private String basePath = "{{{basePath}}}";
private boolean debugging = false;
private Map<String, String> defaultHeaderMap = new HashMap<String, String>();
private Map<String, String> defaultCookieMap = new HashMap<String, String>();
private String tempFolderPath = null;
private Map<String, Authentication> authentications;
private DateFormat dateFormat;
private DateFormat datetimeFormat;
private boolean lenientDatetimeFormat;
private int dateLength;
private InputStream sslCaCert;
private boolean verifyingSsl;
private KeyManager[] keyManagers;
private OkHttpClient httpClient;
private JSON json;
private HttpLoggingInterceptor loggingInterceptor;
{{#dynamicOperations}}
private Map<String, ApiOperation> operationLookupMap = new HashMap<>();
{{/dynamicOperations}}
/*
* Basic constructor for ApiClient
*/
public ApiClient() {
init();
initHttpClient();
// Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
/*
* Basic constructor with custom OkHttpClient
*/
public ApiClient(OkHttpClient client) {
init();
httpClient = client;
// Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}}
authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
{{#hasOAuthMethods}}
{{#oauthMethods}}
{{#-first}}
/*
* Constructor for ApiClient to support access token retry on 401/403 configured with client ID
*/
public ApiClient(String clientId) {
this(clientId, null, null);
}
/*
* Constructor for ApiClient to support access token retry on 401/403 configured with client ID and additional parameters
*/
public ApiClient(String clientId, Map<String, String> parameters) {
this(clientId, null, parameters);
}
/*
* Constructor for ApiClient to support access token retry on 401/403 configured with client ID, secret, and additional parameters
*/
public ApiClient(String clientId, String clientSecret, Map<String, String> parameters) {
this(null, clientId, clientSecret, parameters);
}
/*
* Constructor for ApiClient to support access token retry on 401/403 configured with base path, client ID, secret, and additional parameters
*/
public ApiClient(String basePath, String clientId, String clientSecret, Map<String, String> parameters) {
init();
if (basePath != null) {
this.basePath = basePath;
}
{{#hasOAuthMethods}}
String tokenUrl = "{{tokenUrl}}";
if (!"".equals(tokenUrl) && !URI.create(tokenUrl).isAbsolute()) {
URI uri = URI.create(getBasePath());
tokenUrl = uri.getScheme() + ":" +
(uri.getAuthority() != null ? "//" + uri.getAuthority() : "") +
tokenUrl;
if (!URI.create(tokenUrl).isAbsolute()) {
throw new IllegalArgumentException("OAuth2 token URL must be an absolute URL");
}
}
RetryingOAuth retryingOAuth = new RetryingOAuth(tokenUrl, clientId, OAuthFlow.{{flow}}, clientSecret, parameters);
authentications.put(
"{{name}}",
retryingOAuth
);
initHttpClient(Collections.<Interceptor>singletonList(retryingOAuth));
{{/hasOAuthMethods}}
// Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}}
authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{/authMethods}}
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
{{/-first}}
{{/oauthMethods}}
{{/hasOAuthMethods}}
private void initHttpClient() {
initHttpClient(Collections.<Interceptor>emptyList());
}
private void initHttpClient(List<Interceptor> interceptors) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addNetworkInterceptor(getProgressInterceptor());
for (Interceptor interceptor: interceptors) {
builder.addInterceptor(interceptor);
}
{{#useGzipFeature}}
// Enable gzip request compression
builder.addInterceptor(new GzipRequestInterceptor());
{{/useGzipFeature}}
httpClient = builder.build();
}
private void init() {
verifyingSsl = true;
json = new JSON();
// Set default User-Agent.
setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}");
authentications = new HashMap<String, Authentication>();
{{#dynamicOperations}}
OpenAPI openAPI = new OpenAPIV3Parser().read("openapi/openapi.yaml");
createOperationLookupMap(openAPI);
{{/dynamicOperations}}
}
/**
* Get base path
*
* @return Base path
*/
public String getBasePath() {
return basePath;
}
/**
* Set base path
*
* @param basePath Base path of the URL (e.g {{{basePath}}}
* @return An instance of OkHttpClient
*/
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
/**
* Get HTTP client
*
* @return An instance of OkHttpClient
*/
public OkHttpClient getHttpClient() {
return httpClient;
}
/**
* Set HTTP client, which must never be null.
*
* @param newHttpClient An instance of OkHttpClient
* @return Api Client
* @throws NullPointerException when newHttpClient is null
*/
public ApiClient setHttpClient(OkHttpClient newHttpClient) {
this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!");
return this;
}
/**
* 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;
}
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;
}
public DateFormat getDateFormat() {
return dateFormat;
}
public ApiClient setDateFormat(DateFormat dateFormat) {
this.json.setDateFormat(dateFormat);
return this;
}
public ApiClient setSqlDateFormat(DateFormat dateFormat) {
this.json.setSqlDateFormat(dateFormat);
return this;
}
{{#joda}}
public ApiClient setDateTimeFormat(DateTimeFormatter dateFormat) {
this.json.setDateTimeFormat(dateFormat);
return this;
}
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
this.json.setLocalDateFormat(dateFormat);
return this;
}
{{/joda}}
{{#jsr310}}
public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
this.json.setOffsetDateTimeFormat(dateFormat);
return this;
}
public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) {
this.json.setLocalDateFormat(dateFormat);
return this;
}
{{/jsr310}}
public ApiClient setLenientOnJson(boolean lenientOnJson) {
this.json.setLenientOnJson(lenientOnJson);
return this;
}
/**
* Get authentications (key: authentication name, value: authentication).
*
* @return Map of authentication objects
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
{{#hasHttpBearerMethods}}
/**
* Helper method to set access token for the first Bearer authentication.
* @param bearerToken Bearer token
*/
public void setBearerToken(String bearerToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBearerAuth) {
((HttpBearerAuth) auth).setBearerToken(bearerToken);
return;
}
}
throw new RuntimeException("No Bearer authentication configured!");
}
{{/hasHttpBearerMethods}}
/**
* Helper method to set username for the first HTTP basic authentication.
*
* @param username Username
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication.
*
* @param password Password
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
*
* @param apiKey API key
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
*
* @param apiKeyPrefix API key prefix
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set access token for the first OAuth2 authentication.
*
* @param accessToken Access token
*/
public void setAccessToken(String accessToken) {
{{#hasOAuthMethods}}
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
((OAuth) auth).setAccessToken(accessToken);
return;
}
}
{{/hasOAuthMethods}}
throw new RuntimeException("No OAuth2 authentication configured!");
}
/**
* 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 tempopary folder.
*
* @see <a href="https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile">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 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 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 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;
}
{{#hasOAuthMethods}}
/**
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
*
* @return Token request builder
*/
public TokenRequestBuilder getTokenEndPoint() {
for (Authentication apiAuth : authentications.values()) {
if (apiAuth instanceof RetryingOAuth) {
RetryingOAuth retryingOAuth = (RetryingOAuth) apiAuth;
return retryingOAuth.getTokenRequestBuilder();
}
}
return null;
}
{{/hasOAuthMethods}}
/**
* 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 {{#joda}}|| param instanceof DateTime || param instanceof LocalDate{{/joda}}{{#jsr310}}|| param instanceof OffsetDateTime || param instanceof LocalDate{{/jsr310}}) {
//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(String.valueOf(o));
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/**
* Formats the specified query parameter to a list containing a single {@code Pair} object.
*
* 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;
}
{{^dynamicOperations}}
/**
* Formats the specified collection query parameters to a list of {@code Pair} objects.
*
* 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;
}
{{/dynamicOperations}}
{{#dynamicOperations}}
public List<Pair> parameterToPairs(Parameter param, Collection value) {
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (param == null || param.getName() == null || param.getName().isEmpty() || value == null) {
return params;
}
// create the params based on the collection format
if (StyleEnum.FORM.equals(param.getStyle()) && Boolean.TRUE.equals(param.getExplode())) {
for (Object item : value) {
params.add(new Pair(param.getName(), 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 (StyleEnum.SPACEDELIMITED.equals(param.getStyle())) {
delimiter = escapeString(" ");
} else if (StyleEnum.PIPEDELIMITED.equals(param.getStyle())) {
delimiter = escapeString("|");
}
StringBuilder sb = new StringBuilder();
for (Object item : value) {
sb.append(delimiter);
sb.append(escapeString(parameterToString(item)));
}
params.add(new Pair(param.getName(), sb.substring(delimiter.length())));
return params;
}
{{/dynamicOperations}}
/**
* 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.replaceAll(".*[/\\\\]", "");
}
/**
* 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,
* or matches "any", JSON will be used.
*/
public String selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0 || 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 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);
}
String respBody;
try {
if (response.body() != null)
respBody = response.body().string();
else
respBody = null;
} catch (IOException e) {
throw new ApiException(e);
}
if (respBody == null || "".equals(respBody)) {
return null;
}
String contentType = response.headers().get("Content-Type");
if (contentType == null) {
// ensuring a default content type
contentType = "application/json";
}
if (isJsonMime(contentType)) {
return json.deserialize(respBody, returnType);
} else if (returnType.equals(String.class)) {
// Expecting string, return the raw response body.
return (T) respBody;
} else {
throw new ApiException(
"Content type \"" + contentType + "\" is not supported for type: " + returnType,
response.code(),
response.headers().toMultimap(),
respBody);
}
}
/**