/
ApiClient.java
1845 lines (1653 loc) · 65.7 KB
/
ApiClient.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 com.docusign.esign.client;
import com.docusign.esign.client.auth.*;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.migcomponents.migbase64.Base64;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.HttpUrlConnectorProvider;
import org.glassfish.jersey.client.spi.Connector;
import org.glassfish.jersey.client.spi.ConnectorProvider;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.media.multipart.*;
import javax.net.ssl.*;
import jakarta.ws.rs.client.*;
import jakarta.ws.rs.core.*;
import jakarta.ws.rs.core.Response.Status;
import jakarta.ws.rs.core.Response.Status.Family;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import org.glassfish.jersey.logging.LoggingFeature;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ApiClient class.
*
**/
public class ApiClient {
protected Map<String, String> defaultHeaderMap = new HashMap<String, String>();
// Rest API base path constants
/** live/production base path. */
public final static String PRODUCTION_REST_BASEPATH = "https://www.docusign.net/restapi";
/** sandbox/demo base path. */
public final static String DEMO_REST_BASEPATH = "https://demo.docusign.net/restapi";
/** stage base path. */
public final static String STAGE_REST_BASEPATH = "https://stage.docusign.net/restapi";
private String basePath = DEMO_REST_BASEPATH;
private String oAuthBasePath = OAuth.PRODUCTION_OAUTH_BASEPATH;
protected boolean debugging = false;
protected int connectionTimeout = 0;
private int readTimeout = 0;
protected Client httpClient;
protected JSON json;
protected String tempFolderPath = null;
protected Map<String, Authentication> authentications;
private int statusCode;
private Map<String, List<String>> responseHeaders;
protected DateFormat dateFormat;
private SSLContext sslContext = null;
/**
* ApiClient constructor.
*
**/
public ApiClient() {
json = new JSON();
httpClient = buildHttpClient(debugging);
this.dateFormat = new RFC3339DateFormat();
String javaVersion = System.getProperty("java.version");
// Set default User-Agent.
setUserAgent("Swagger-Codegen/v2.1/5.0.0-RC1/Java/" + javaVersion);
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
authentications.put("docusignAccessCode", new OAuth());
// Derive the OAuth base path from the Rest API base url
this.deriveOAuthBasePathFromRestBasePath();
}
/**
* buildDefaultDateFormat method.
*
* @return DateFormat
**/
public static DateFormat buildDefaultDateFormat() {
return new RFC3339DateFormat();
}
/**
* ApiClient constructor.
*
* @param basePath The base path to create the client with
**/
public ApiClient(String basePath) {
this();
this.basePath = basePath;
this.deriveOAuthBasePathFromRestBasePath();
}
/**
* ApiClient constructor.
*
* @param oAuthBasePath The base path to create the client with
* @param authNames The authentication names
**/
public ApiClient(String oAuthBasePath, String[] authNames) {
this();
this.setOAuthBasePath(oAuthBasePath);
for(String authName : authNames) {
Authentication auth;
if ("docusignAccessCode".equals(authName)) {
auth = new OAuth(httpClient, OAuthFlow.accessCode, oAuthBasePath + "/oauth/auth", oAuthBasePath + "/oauth/token", "all");
} else if ("docusignApiKey".equals(authName)) {
auth = new ApiKeyAuth("header", "docusignApiKey");
} else {
throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");
}
addAuthorization(authName, auth);
}
}
/**
* Basic constructor for single auth name.
* @param oAuthBasePath the basepath
* @param authName the auth name
*/
public ApiClient(String oAuthBasePath, String authName) {
this(oAuthBasePath, new String[]{authName});
}
/**
* Helper constructor for OAuth2.
* @param oAuthBasePath The API base path
* @param authName the authentication method name ("oauth" or "api_key")
* @param clientId OAuth2 Client ID
* @param secret OAuth2 Client secret
*/
public ApiClient(String oAuthBasePath, String authName, String clientId, String secret) {
this(oAuthBasePath, authName);
this.getTokenEndPoint()
.setClientId(clientId)
.setClientSecret(secret);
}
/**
* Build the Client used to make HTTP requests with the latest settings,
* i.e. objectMapper and debugging.
* TODO: better to use the Builder Pattern?
* @return API client
*/
public ApiClient rebuildHttpClient() {
return setDebugging(debugging);
}
/**
* Returns the current object mapper used for JSON serialization/deserialization.
* <p>
* Note: If you make changes to the object mapper, remember to set it back via
* <code>setObjectMapper</code> in order to trigger HTTP client rebuilding.
* </p>
* @return Object mapper
*/
public ObjectMapper getObjectMapper() {
return json.getObjectMapper();
}
/**
* Set the object mapper of client.
*
* @return API client
*/
public ApiClient setObjectMapper(ObjectMapper objectMapper) {
json.setObjectMapper(objectMapper);
// Need to rebuild the Client as it depends on object mapper.
rebuildHttpClient();
return this;
}
/**
* Gets the JSON instance to do JSON serialization and deserialization.
* @return JSON
*/
public JSON getJSON() {
return json;
}
/**
* Gets the API client.
*
* @return Client
*/
public Client getHttpClient() {
return httpClient;
}
/**
* Sets the API client.
*
* @return ApiClient
*/
public ApiClient setHttpClient(Client httpClient) {
this.httpClient = httpClient;
return this;
}
/**
* Gets the basepath.
*
* @return String
*/
public String getBasePath() {
return basePath;
}
/**
* Sets the basepath.
*
* @return ApiClient
*/
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
this.deriveOAuthBasePathFromRestBasePath();
return this;
}
/**
* Gets the status code of the previous request.
* @return Status code
*/
public int getStatusCode() {
return statusCode;
}
/**
* Gets the response headers of the previous request.
* @return Response headers
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get authentications (key: authentication name, value: authentication).
* @return Map of authentication object
*/
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);
}
/**
* Adds authorization.
*/
public void addAuthorization(String authName, Authentication auth) {
authentications.put(authName, auth);
}
/**
* 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.
*/
public void updateAccessToken() {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
try {
((OAuth) auth).updateAccessToken();
} catch (ApiException e) {
throw new RuntimeException(e.getMessage());
}
return;
}
}
throw new RuntimeException("No OAuth2 authentication configured!");
}
/**
* Helper method to preset the OAuth access token of the first OAuth found in the apiAuthorizations (there should be only one).
* @param accessToken OAuth access token
* @param expiresIn Validity period of the access token in seconds
*/
public void setAccessToken(final String accessToken, final Long expiresIn) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
((OAuth) auth).setAccessToken(accessToken, expiresIn);
return;
}
}
OAuth oAuth = new OAuth(null, null, null);
oAuth.setAccessToken(accessToken, expiresIn);
addAuthorization("docusignAccessCode", oAuth);
}
/**
* Gets the access token.
*
* @return String
*/
public String getAccessToken() {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
return ((OAuth) auth).getAccessToken();
}
}
return null;
}
/**
* Set the User-Agent header's value (by adding to the default header map).
* @param userAgent Http user agent
* @return API client
*/
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 API client
*/
public ApiClient addDefaultHeader(String key, String value) {
defaultHeaderMap.put(key, value);
return this;
}
/**
* Check that whether debugging is enabled for this API client.
* @return True if debugging is switched on
*/
public boolean isDebugging() {
return debugging;
}
/**
* Enable/disable debugging for this API client.
*
* @param debugging To enable (true) or disable (false) debugging
* @return API client
*/
public ApiClient setDebugging(boolean debugging) {
this.debugging = debugging;
// Rebuild HTTP Client according to the new "debugging" value.
this.httpClient = buildHttpClient(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.
*
* @return Temp folder path
*/
public String getTempFolderPath() {
return tempFolderPath;
}
/**
* Set temp folder path.
* @param tempFolderPath Temp folder path
* @return API client
*/
public ApiClient setTempFolderPath(String tempFolderPath) {
this.tempFolderPath = tempFolderPath;
return this;
}
/**
* Connect timeout (in milliseconds).
* @return Connection timeout
*/
public int getConnectTimeout() {
return connectionTimeout;
}
/**
* Set 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) {
this.connectionTimeout = connectionTimeout;
httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout);
return this;
}
/**
* read timeout (in milliseconds).
* @return Read timeout
*/
public int getReadTimeout() {
return readTimeout;
}
/**
* Set 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) {
this.readTimeout = readTimeout;
httpClient.property(ClientProperties.READ_TIMEOUT, readTimeout);
return this;
}
/**
* Get the date format used to parse/format date parameters.
* @return Date format
*/
public DateFormat getDateFormat() {
return dateFormat;
}
/**
* Set the date format used to parse/format date parameters.
* @param dateFormat Date format
* @return API client
*/
public ApiClient setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
// also set the date format for model (de)serialization with Date properties
this.json.setDateFormat((DateFormat) dateFormat.clone());
return this;
}
/**
* Helper method to configure the token endpoint of the first oauth found in the authentications (there should be only one).
* @return
*/
public TokenRequestBuilder getTokenEndPoint() {
for(Authentication auth : getAuthentications().values()) {
if (auth instanceof OAuth) {
OAuth oauth = (OAuth) auth;
return oauth.getTokenRequestBuilder();
}
}
return null;
}
/**
* Helper method to configure authorization endpoint of the first oauth found in the authentications (there should be only one).
* @return
*/
public AuthenticationRequestBuilder getAuthorizationEndPoint() {
for(Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
OAuth oauth = (OAuth) auth;
return oauth.getAuthenticationRequestBuilder();
}
}
return null;
}
/**
* Helper method to configure the OAuth accessCode/implicit flow parameters.
* @param clientId OAuth2 client ID
* @param clientSecret OAuth2 client secret
* @param redirectURI OAuth2 redirect uri
*/
public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
for(Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
OAuth oauth = (OAuth) auth;
oauth.getTokenRequestBuilder()
.setClientId(clientId)
.setClientSecret(clientSecret)
.setRedirectURI(redirectURI);
oauth.getAuthenticationRequestBuilder()
.setClientId(clientId)
.setRedirectURI(redirectURI);
return;
}
}
}
public String getAuthorizationUri() throws OAuthSystemException {
return getAuthorizationEndPoint().buildQueryMessage().getLocationUri();
}
/**
* Helper method to configure the OAuth accessCode/implicit flow parameters.
*
* @param clientId OAuth2 client ID: Identifies the client making the request.
* Client applications may be scoped to a limited set of system access.
* @param scopes the list of requested scopes. Values include {@link OAuth#Scope_SIGNATURE}, {@link OAuth#Scope_EXTENDED}, {@link OAuth#Scope_IMPERSONATION}. You can also pass any advanced scope.
* @param redirectUri this determines where to deliver the response containing the authorization code or access token.
* @param responseType determines the response type of the authorization request.
* <br><i>Note</i>: these response types are mutually exclusive for a client application.
* A public/native client application may only request a response type of "token";
* a private/trusted client application may only request a response type of "code".
* @param state Allows for arbitrary state that may be useful to your application.
* The value in this parameter will be round-tripped along with the response so you can make sure it didn't change.
*/
public URI getAuthorizationUri(String clientId, java.util.List<String> scopes, String redirectUri, String responseType, String state) throws IllegalArgumentException, UriBuilderException {
String formattedScopes = (scopes == null || scopes.size() < 1) ? "" : scopes.get(0);
StringBuilder sb = new StringBuilder(formattedScopes);
for (int i = 1; i < scopes.size(); i++) {
sb.append("%20" + scopes.get(i));
}
UriBuilder builder = UriBuilder.fromUri(getOAuthBasePath())
.scheme("https")
.path("/oauth/auth")
.queryParam("response_type", responseType)
.queryParam("scope", sb.toString())
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectUri);
if (state != null) {
builder = builder.queryParam("state", state);
}
return builder.build();
}
/**
* Helper method to configure the OAuth accessCode/implicit flow parameters.
*
* @param clientId OAuth2 client ID: Identifies the client making the request.
* Client applications may be scoped to a limited set of system access.
* @param scopes the list of requested scopes. Values include {@link OAuth#Scope_SIGNATURE}, {@link OAuth#Scope_EXTENDED}, {@link OAuth#Scope_IMPERSONATION}. You can also pass any advanced scope.
* @param redirectUri this determines where to deliver the response containing the authorization code or access token.
* @param responseType determines the response type of the authorization request.
* <br><i>Note</i>: these response types are mutually exclusive for a client application.
* A public/native client application may only request a response type of "token";
* a private/trusted client application may only request a response type of "code".
*/
public URI getAuthorizationUri(String clientId, java.util.List<String> scopes, String redirectUri, String responseType) throws IllegalArgumentException, UriBuilderException {
return this.getAuthorizationUri(clientId, scopes, redirectUri, responseType, null);
}
private void deriveOAuthBasePathFromRestBasePath() {
if (this.basePath == null) { // this case should not happen but just in case
this.oAuthBasePath = OAuth.DEMO_OAUTH_BASEPATH;
} else if (this.basePath.startsWith("https://demo") || this.basePath.startsWith("http://demo") || this.basePath.startsWith("https://apps-d") || this.basePath.startsWith("http://apps-d")) {
this.oAuthBasePath = OAuth.DEMO_OAUTH_BASEPATH;
} else if (this.basePath.startsWith("https://stage") || this.basePath.startsWith("http://stage") || this.basePath.startsWith("https://apps-s") || this.basePath.startsWith("http://apps-s")) {
this.oAuthBasePath = OAuth.STAGE_OAUTH_BASEPATH;
} else {
this.oAuthBasePath = OAuth.PRODUCTION_OAUTH_BASEPATH;
}
}
private String getOAuthBasePath() {
return this.oAuthBasePath;
}
/**
* Sets the OAuth base path. Values include {@link OAuth#PRODUCTION_OAUTH_BASEPATH}, {@link OAuth#DEMO_OAUTH_BASEPATH} and custom (e.g. "account-s.docusign.com").
* @param oAuthBasePath the new value for the OAuth base path
* @return this instance of the ApiClient updated with the new OAuth base path
*/
public ApiClient setOAuthBasePath(String oAuthBasePath) {
this.oAuthBasePath = oAuthBasePath;
return this;
}
/**
* Helper method to configure the OAuth accessCode/implicit flow parameters.
*
* @param clientId OAuth2 client ID: Identifies the client making the request.
* Client applications may be scoped to a limited set of system access.
* @param clientSecret the secret key you generated when you set up the integration in DocuSign Admin console.
* @param code The authorization code that you received from the <i>getAuthorizationUri</i> callback.
* @return OAuth.OAuthToken object.
* @throws ApiException if the HTTP call status is different than 2xx.
* @throws IOException if there is a problem while parsing the reponse object.
* @see OAuth.OAuthToken
*/
public OAuth.OAuthToken generateAccessToken(String clientId, String clientSecret, String code) throws ApiException, IOException {
String clientStr = (clientId == null ? "" : clientId) + ":" + (clientSecret == null ? "" : clientSecret);
java.util.Map<String, Object> form = new java.util.HashMap<>();
form.put("code", code);
form.put("grant_type", "authorization_code");
Client client = buildHttpClient(debugging);
WebTarget target = client.target("https://" + getOAuthBasePath() + "/oauth/token");
Invocation.Builder invocationBuilder = target.request();
invocationBuilder = invocationBuilder
.header("Authorization", "Basic " + Base64.encodeToString(clientStr.getBytes("UTF-8"), false))
.header("Cache-Control", "no-store")
.header("Pragma", "no-cache");
Entity<?> entity = serialize(null, form, MediaType.APPLICATION_FORM_URLENCODED);
Response response = null;
try {
response = invocationBuilder.post(entity);
if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = String.valueOf(response.readEntity(String.class));
message = "Error while requesting server, received a non successful HTTP code " + response.getStatusInfo().getStatusCode() + " with response Body: '" + respBody + "'";
} catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message,
buildResponseHeaders(response),
respBody);
}
GenericType<OAuth.OAuthToken> returnType = new GenericType<OAuth.OAuthToken>() {};
return deserialize(response, returnType);
} finally {
try {
if (response != null) {
response.close();
}
} catch (Exception e) {
// it's not critical, since the response object is local in method invokeAPI; that's fine, just continue
}
}
}
/**
* Gets the user info.
*
* @param accessToken the bearer token to use to authenticate for this call.
* @return OAuth UserInfo model
* @throws ApiException if the HTTP call status is different than 2xx.
* @see OAuth.UserInfo
*/
public OAuth.UserInfo getUserInfo(String accessToken) throws IllegalArgumentException, ApiException {
if (accessToken == null || "".equals(accessToken)) {
throw new IllegalArgumentException("Cannot find a valid access token. Make sure OAuth is configured before you try again.");
}
Client client = buildHttpClient(debugging);
WebTarget target = client.target("https://" + getOAuthBasePath() + "/oauth/userinfo");
Invocation.Builder invocationBuilder = target.request();
invocationBuilder = invocationBuilder
.header("Authorization", "Bearer " + accessToken)
.header("Cache-Control", "no-store")
.header("Pragma", "no-cache");
Response response = null;
try {
response = invocationBuilder.get();
if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = String.valueOf(response.readEntity(String.class));
message = "Error while requesting server, received a non successful HTTP code " + response.getStatusInfo().getStatusCode() + " with response Body: '" + respBody + "'";
} catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message,
buildResponseHeaders(response),
respBody);
}
GenericType<OAuth.UserInfo> returnType = new GenericType<OAuth.UserInfo>() {};
return deserialize(response, returnType);
} finally {
try {
if (response != null) {
response.close();
}
} catch (Exception e) {
// it's not critical, since the response object is local in method invokeAPI; that's fine, just continue
}
}
}
/**
* Configures a listener which is notified when a new access token is received.
* @param accessTokenListener access token listener
*/
public void registerAccessTokenListener(AccessTokenListener accessTokenListener) {
for(Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
OAuth oauth = (OAuth) auth;
oauth.registerAccessTokenListener(accessTokenListener);
return;
}
}
}
/**
* Helper method to build the OAuth JWT grant uri (used once to get a user consent for impersonation).
* @param clientId OAuth2 client ID
* @param redirectURI OAuth2 redirect uri
* @return the OAuth JWT grant uri as a String
*/
public String getJWTUri(String clientId, String redirectURI, String oAuthBasePath) {
return UriBuilder.fromUri(oAuthBasePath)
.scheme("https")
.path("/oauth/auth")
.queryParam("response_type", "code")
.queryParam("scope", "signature%20impersonation")
.queryParam("client_id", clientId)
.queryParam("redirect_uri", redirectURI)
.build().toString();
}
/**
* Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign.
* @param publicKeyFilename the filename of the RSA public key
* @param privateKeyFilename the filename of the RSA private key
* @param oAuthBasePath DocuSign OAuth base path (account-d.docusign.com for the developer sandbox
and account.docusign.com for the production platform)
* @param clientId DocuSign OAuth Client Id (AKA Integrator Key)
* @param userId DocuSign user Id to be impersonated (This is a UUID)
* @param expiresIn number of seconds remaining before the JWT assertion is considered as invalid
* @throws ApiException if there is an error while exchanging the JWT with an access token
* @throws IOException if there is an issue with either the public or private file
* @deprecated As of release 2.7.0, replaced by {@link #requestJWTUserToken(String, String, List, byte[], long)} ()} and {@link #requestJWTApplicationToken(String, List, byte[], long)}
*/
@Deprecated public void configureJWTAuthorizationFlow(String publicKeyFilename, String privateKeyFilename, String oAuthBasePath, String clientId, String userId, long expiresIn) throws ApiException, IOException {
String assertion = JWTUtils.generateJWTAssertion(publicKeyFilename, privateKeyFilename, oAuthBasePath, clientId, userId, expiresIn);
java.util.Map<String, Object> form = new java.util.HashMap<>();
form.put("assertion", assertion);
form.put("grant_type", OAuth.GRANT_TYPE_JWT);
Client client = buildHttpClient(debugging);
WebTarget target = client.target("https://" + oAuthBasePath + "/oauth/token");
Invocation.Builder invocationBuilder = target.request();
invocationBuilder = invocationBuilder
.header("Cache-Control", "no-store")
.header("Pragma", "no-cache");
Entity<?> entity = serialize(null, form, MediaType.APPLICATION_FORM_URLENCODED);
Response response = null;
try {
response = invocationBuilder.post(entity);
if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = String.valueOf(response.readEntity(String.class));
message = "Error while requesting server, received a non successful HTTP code " + response.getStatusInfo().getStatusCode() + " with response Body: '" + respBody + "'";
} catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message,
buildResponseHeaders(response),
respBody);
}
GenericType<JsonNode> returnType = new GenericType<JsonNode>() {};
JsonNode responseJson = deserialize(response, returnType);
if (!responseJson.has("access_token") || !responseJson.has("expires_in")) {
throw new ApiException("Error while requesting an access token: " + responseJson);
}
String accessToken = responseJson.get("access_token").asText();
expiresIn = responseJson.get("expires_in").asLong();
setAccessToken(accessToken, expiresIn);
} finally {
try {
if (response != null) {
response.close();
}
} catch (Exception e) {
// it's not critical, since the response object is local in method invokeAPI; that's fine, just continue
}
}
}
/**
* Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign.
* @param clientId DocuSign OAuth Client Id (AKA Integrator Key)
* @param userId DocuSign user Id to be impersonated (This is a UUID)
* @param scopes the list of requested scopes. Values include {@link OAuth#Scope_SIGNATURE}, {@link OAuth#Scope_EXTENDED}, {@link OAuth#Scope_IMPERSONATION}. You can also pass any advanced scope.
* @param rsaPrivateKey the byte contents of the RSA private key
* @param expiresIn number of seconds remaining before the JWT assertion is considered as invalid
* @return OAuth.OAuthToken object.
* @throws IllegalArgumentException if one of the arguments is invalid
* @throws ApiException if there is an error while exchanging the JWT with an access token
* @throws IOException if there is an issue with either the public or private file
*/
public OAuth.OAuthToken requestJWTUserToken(String clientId, String userId, java.util.List<String>scopes, byte[] rsaPrivateKey, long expiresIn) throws IllegalArgumentException, ApiException, IOException {
String formattedScopes = (scopes == null || scopes.size() < 1) ? "" : scopes.get(0);
StringBuilder sb = new StringBuilder(formattedScopes);
for (int i = 1; i < scopes.size(); i++) {
sb.append(" " + scopes.get(i));
}
String assertion = JWTUtils.generateJWTAssertionFromByteArray(rsaPrivateKey, getOAuthBasePath(), clientId, userId, expiresIn, sb.toString());
java.util.Map<String, Object> form = new java.util.HashMap<>();
form.put("assertion", assertion);
form.put("grant_type", OAuth.GRANT_TYPE_JWT);
Client client = buildHttpClient(debugging);
WebTarget target = client.target("https://" + getOAuthBasePath() + "/oauth/token");
Invocation.Builder invocationBuilder = target.request();
invocationBuilder = invocationBuilder
.header("Cache-Control", "no-store")
.header("Pragma", "no-cache");
Entity<?> entity = serialize(null, form, MediaType.APPLICATION_FORM_URLENCODED);
Response response = null;
try {
response = invocationBuilder.post(entity);
if (response.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = String.valueOf(response.readEntity(String.class));
message = "Error while requesting server, received a non successful HTTP code " + response.getStatusInfo().getStatusCode() + " with response Body: '" + respBody + "'";
} catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message,
buildResponseHeaders(response),
respBody);
}
GenericType<OAuth.OAuthToken> returnType = new GenericType<OAuth.OAuthToken>() {};
OAuth.OAuthToken oAuthToken = deserialize(response, returnType);
if (oAuthToken.getAccessToken() == null || "".equals(oAuthToken.getAccessToken()) || oAuthToken.getExpiresIn() <= 0) {
throw new ApiException("Error while requesting an access token: " + response.toString());
}
return oAuthToken;
} finally {
try {
if (response != null) {
response.close();
}
} catch (Exception e) {
// it's not critical, since the response object is local in method invokeAPI; that's fine, just continue
}
}
}
/**
* <b>RESERVED FOR PARTNERS</b> Request JWT Application Token.
* Configures the current instance of ApiClient with a fresh OAuth JWT access token from DocuSign
* @param clientId DocuSign OAuth Client Id (AKA Integrator Key)
* @param scopes the list of requested scopes. Values include {@link OAuth#Scope_SIGNATURE}, {@link OAuth#Scope_EXTENDED}, {@link OAuth#Scope_IMPERSONATION}. You can also pass any advanced scope.
* @param rsaPrivateKey the byte contents of the RSA private key
* @param expiresIn number of seconds remaining before the JWT assertion is considered as invalid
* @return OAuth.OAuthToken object.
* @throws IllegalArgumentException if one of the arguments is invalid
* @throws IOException if there is an issue with either the public or private file
* @throws ApiException if there is an error while exchanging the JWT with an access token
*/
public OAuth.OAuthToken requestJWTApplicationToken(String clientId, java.util.List<String>scopes, byte[] rsaPrivateKey, long expiresIn) throws IllegalArgumentException, IOException, ApiException {
return this.requestJWTUserToken(clientId, null, scopes, rsaPrivateKey, expiresIn);
}
/**
* Parse the given string into Date object.
* @param str String
* @return Date
*/
public Date parseDate(String str) {
try {
return dateFormat.parse(str);
} catch (java.text.ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Format the given Date object into string.
* @param date Date
* @return Date in string format
*/
public String formatDate(Date date) {
return dateFormat.format(date);
}
/**
* Format the given parameter object into string.
* @param param Object
* @return Object in string format
*/
public String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDate((Date) param);