-
Notifications
You must be signed in to change notification settings - Fork 285
Expand file tree
/
Copy pathAbstractClient.java
More file actions
1128 lines (1047 loc) · 47 KB
/
AbstractClient.java
File metadata and controls
1128 lines (1047 loc) · 47 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
/*
* Copyright (c) 2018 Tencent. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.tencentcloudapi.common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.http.HttpConnection;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import okhttp3.*;
import okhttp3.Headers.Builder;
import javax.crypto.Mac;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* AbstractClient provides the basic functionalities for interacting with Tencent Cloud services.
* It handles request signing, sending, and response processing.
*/
public abstract class AbstractClient {
public static final int HTTP_RSP_OK = 200;
public static final String SDK_VERSION = "SDK_JAVA_3.1.1337";
public Gson gson;
// User's security credentials (SecretId, SecretKey, Token).
private Credential credential;
// Client configuration (e.g., timeout, endpoint).
private ClientProfile profile;
// API endpoint URL.
private String endpoint;
// Service name (e.g., "cvm").
private String service;
// Region (e.g., "ap-guangzhou").
private String region;
// API request path (usually "/").
private String path;
// SDK version string.
private String sdkVersion;
// API version string.
private String apiVersion;
// Logger for debugging and information.
private TCLog log;
// Handles HTTP connections.
private HttpConnection httpConnection;
// Circuit breaker for handling region failures.
private CircuitBreaker regionBreaker;
/**
* Constructor for AbstractClient with default client profile.
*
* @param endpoint API endpoint URL.
* @param version API version.
* @param credential User credentials.
* @param region Region.
*/
public AbstractClient(String endpoint, String version, Credential credential, String region) {
this(endpoint, version, credential, region, new ClientProfile());
}
/**
* Constructor for AbstractClient with a custom client profile.
*
* @param endpoint API endpoint URL.
* @param version API version.
* @param credential User credentials.
* @param region Region.
* @param profile Client configuration profile.
*/
public AbstractClient(
String endpoint,
String version,
Credential credential,
String region,
ClientProfile profile) {
this.credential = credential;
this.profile = profile;
this.endpoint = endpoint;
this.service = endpoint.split("\\.")[0];
this.region = region;
int pathIdx = endpoint.indexOf('/');
if (pathIdx >= 0) {
this.path = endpoint.substring(pathIdx);
} else {
this.path = "/";
}
this.sdkVersion = AbstractClient.SDK_VERSION;
this.apiVersion = version;
this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
this.log = new TCLog(getClass().getName(), profile.isDebug());
this.httpConnection = new HttpConnection(
this.profile.getHttpProfile().getConnTimeout(),
this.profile.getHttpProfile().getReadTimeout(),
this.profile.getHttpProfile().getWriteTimeout()
);
this.httpConnection.addInterceptors(this.log);
this.trySetProxy(this.httpConnection);
this.trySetSSLSocketFactory(this.httpConnection);
this.trySetRegionBreaker();
this.trySetHostnameVerifier(this.httpConnection);
this.trySetHttpClient();
warmup();
}
/**
* Gets the region.
*
* @return The region.
*/
public String getRegion() {
return this.region;
}
/**
* Sets the region.
*
* @param region The region to set.
*/
public void setRegion(String region) {
this.region = region;
}
/**
* Gets the client profile.
*
* @return The client profile.
*/
public ClientProfile getClientProfile() {
return this.profile;
}
/**
* Sets the client profile.
*
* @param profile The client profile to set.
*/
public void setClientProfile(ClientProfile profile) {
this.profile = profile;
}
/**
* Gets the credential.
*
* @return The credential.
*/
public Credential getCredential() {
return this.credential;
}
/**
* Sets the credential.
*
* @param credential The credential to set.
*/
public void setCredential(Credential credential) {
this.credential = credential;
}
/**
* Calls an API action with JSON payload using the TC3-HMAC-SHA256 signature.
* Ignores the request method and signature method defined in the profile.
*
* @param action Name of the API action.
* @param jsonPayload JSON string containing the request parameters.
* @return Raw response from the API.
* @throws TencentCloudSDKException If an error occurs during the API call.
*/
public String call(String action, String jsonPayload) throws TencentCloudSDKException {
HashMap<String, String> headers = this.getHeaders();
headers.put("X-TC-Action", action);
headers.put("Content-Type", "application/json; charset=utf-8");
byte[] requestPayload = jsonPayload.getBytes(StandardCharsets.UTF_8);
String authorization = this.getAuthorization(headers, requestPayload);
headers.put("Authorization", authorization);
String url = this.profile.getHttpProfile().getProtocol() + this.getEndpoint();
return this.getResponseBody(url, headers, requestPayload);
}
/**
* Calls an API action with binary payload using the TC3-HMAC-SHA256 signature.
* Ignores the request method and signature method defined in the profile.
*
* @param action Name of the API action.
* @param headers HTTP headers to include in the request.
* @param body Binary payload (octet-stream).
* @return Raw response from the API.
* @throws TencentCloudSDKException If an error occurs during the API call.
*/
public String callOctetStream(String action, HashMap<String, String> headers, byte[] body)
throws TencentCloudSDKException {
headers.putAll(this.getHeaders());
headers.put("X-TC-Action", action);
headers.put("Content-Type", "application/octet-stream; charset=utf-8");
String authorization = this.getAuthorization(headers, body);
headers.put("Authorization", authorization);
String url = this.profile.getHttpProfile().getProtocol() + this.getEndpoint();
return this.getResponseBody(url, headers, body);
}
/**
* Generates common HTTP headers for Tencent Cloud API requests.
*
* @return A HashMap containing the headers.
*/
private HashMap<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<String, String>();
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
headers.put("X-TC-Timestamp", timestamp);
headers.put("X-TC-Version", this.apiVersion);
headers.put("X-TC-Region", this.getRegion());
headers.put("X-TC-RequestClient", SDK_VERSION);
headers.put("Host", this.getHost());
String token = this.credential.getToken();
if (token != null && !token.isEmpty()) {
headers.put("X-TC-Token", token);
}
if (this.profile.isUnsignedPayload()) {
headers.put("X-TC-Content-SHA256", "UNSIGNED-PAYLOAD");
}
if (null != this.profile.getLanguage()) {
headers.put("X-TC-Language", this.profile.getLanguage().getValue());
}
return headers;
}
/**
* Generates the authorization header for TC3-HMAC-SHA256 signature.
*
* @param headers HTTP headers.
* @param body Request payload.
* @return The authorization header string.
* @throws TencentCloudSDKException If an error occurs during signature generation.
*/
private String getAuthorization(HashMap<String, String> headers, byte[] body)
throws TencentCloudSDKException {
String host = this.getHost();
// always use post tc3-hmac-sha256 signature process
// okhttp always set charset even we don't specify it,
// to ensure signature be correct, we have to set it here as well.
String contentType = headers.get("Content-Type");
byte[] requestPayload = body;
String canonicalUri = "/";
String canonicalQueryString = "";
String canonicalHeaders = "content-type:" + contentType + "\nhost:" + host + "\n";
String signedHeaders = "content-type;host";
String hashedRequestPayload = "";
if (this.profile.isUnsignedPayload()) {
hashedRequestPayload = Sign.sha256Hex("UNSIGNED-PAYLOAD".getBytes(StandardCharsets.UTF_8));
} else {
hashedRequestPayload = Sign.sha256Hex(requestPayload);
}
String canonicalRequest =
HttpProfile.REQ_POST
+ "\n"
+ canonicalUri
+ "\n"
+ canonicalQueryString
+ "\n"
+ canonicalHeaders
+ "\n"
+ signedHeaders
+ "\n"
+ hashedRequestPayload;
String timestamp = headers.get("X-TC-Timestamp");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String date = sdf.format(new Date(Long.valueOf(timestamp + "000")));
String service = host.split("\\.")[0];
String credentialScope = date + "/" + service + "/" + "tc3_request";
String hashedCanonicalRequest =
Sign.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
String stringToSign =
"TC3-HMAC-SHA256\n" + timestamp + "\n" + credentialScope + "\n" + hashedCanonicalRequest;
String secretId = this.credential.getSecretId();
String secretKey = this.credential.getSecretKey();
byte[] secretDate = Sign.hmac256(("TC3" + secretKey).getBytes(StandardCharsets.UTF_8), date);
byte[] secretService = Sign.hmac256(secretDate, service);
byte[] secretSigning = Sign.hmac256(secretService, "tc3_request");
String signature =
DatatypeConverter.printHexBinary(Sign.hmac256(secretSigning, stringToSign)).toLowerCase();
return "TC3-HMAC-SHA256 "
+ "Credential="
+ secretId
+ "/"
+ credentialScope
+ ", "
+ "SignedHeaders="
+ signedHeaders
+ ", "
+ "Signature="
+ signature;
}
/**
* Sends the HTTP request and retrieves the response body.
*
* @param url The request URL.
* @param headers HTTP headers.
* @param body Request payload.
* @return The response body as a string.
* @throws TencentCloudSDKException If an error occurs during the request or response processing.
*/
private String getResponseBody(String url, HashMap<String, String> headers, byte[] body)
throws TencentCloudSDKException {
Builder hb = new Headers.Builder();
for (String key : headers.keySet()) {
hb.add(key, headers.get(key));
}
Response resp = null;
try {
resp = this.httpConnection.postRequest(url, body, hb.build());
} catch (IOException e) {
throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage(), e);
}
if (resp.code() != AbstractClient.HTTP_RSP_OK) {
String msg = "response code is " + resp.code() + ", not 200";
log.info(msg);
throw new TencentCloudSDKException(msg, "", "ServerSideError");
}
String respbody = null;
try {
respbody = resp.body().string();
} catch (IOException e) {
String msg =
"Cannot transfer response body to string, because Content-Length is too large, or Content-Length " +
"and stream length disagree.";
log.info(msg);
throw new TencentCloudSDKException(msg, e);
}
JsonResponseModel<JsonResponseErrModel> errResp = null;
try {
Type errType = new TypeToken<JsonResponseModel<JsonResponseErrModel>>() {
}.getType();
errResp = gson.fromJson(respbody, errType);
} catch (JsonSyntaxException e) {
String msg = "json is not a valid representation for an object of type";
log.info(msg);
throw new TencentCloudSDKException(msg, e);
}
if (errResp.response.error != null) {
throw new TencentCloudSDKException(
errResp.response.error.message, errResp.response.requestId, errResp.response.error.code);
}
return respbody;
}
private void trySetProxy(HttpConnection conn) {
String host = this.profile.getHttpProfile().getProxyHost();
int port = this.profile.getHttpProfile().getProxyPort();
if (host == null || host.isEmpty()) {
return;
}
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
conn.setProxy(proxy);
final String username = this.profile.getHttpProfile().getProxyUsername();
final String password = this.profile.getHttpProfile().getProxyPassword();
if (username == null || username.isEmpty()) {
return;
}
conn.setProxyAuthenticator(
new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(username, password);
return response
.request()
.newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
});
}
private void trySetSSLSocketFactory(HttpConnection conn) {
SSLSocketFactory sslSocketFactory = this.profile.getHttpProfile().getSslSocketFactory();
X509TrustManager trustManager = this.profile.getHttpProfile().getX509TrustManager();
if (sslSocketFactory != null) {
if (trustManager != null) {
this.httpConnection.setSSLSocketFactory(sslSocketFactory, trustManager);
} else {
this.httpConnection.setSSLSocketFactory(sslSocketFactory);
}
}
}
private void trySetHostnameVerifier(HttpConnection conn) {
HostnameVerifier hostnameVerifier = this.profile.getHttpProfile().getHostnameVerifier();
if (hostnameVerifier != null) {
this.httpConnection.setHostnameVerifier(hostnameVerifier);
}
}
private void trySetRegionBreaker() {
String ep = profile.getBackupEndpoint();
if (ep != null && !ep.isEmpty()) {
this.regionBreaker = new CircuitBreaker();
}
}
private void trySetHttpClient() {
Object httpClient = profile.getHttpProfile().getHttpClient();
if (httpClient != null) {
this.httpConnection.setHttpClient(httpClient);
}
}
/**
* Executes an API request and returns the raw string response.
* Handles circuit breaking for region failover.
*
* @param request The request object containing API parameters.
* @param actionName The name of the API action to be called.
* @return The raw string response from the API.
* @throws TencentCloudSDKException If an error occurs during the API call.
*/
protected String internalRequest(AbstractModel request, String actionName)
throws TencentCloudSDKException {
CircuitBreaker.Token breakerToken = null;
// Attempt to acquire a token from the circuit breaker.
// If the circuit is open, use the backup endpoint.
if (regionBreaker != null) {
breakerToken = regionBreaker.allow();
if (!breakerToken.allowed) {
endpoint = service + "." + profile.getBackupEndpoint();
}
}
Response okRsp;
try {
// Execute the raw API request.
okRsp = internalRequestRaw(request, actionName);
} catch (IOException e) {
// Network failure: report to circuit breaker and throw exception.
if (breakerToken != null) {
breakerToken.report(false);
}
throw new TencentCloudSDKException("", e);
}
String strResp;
try {
// Extract the response body as a string.
strResp = okRsp.body().string();
} catch (IOException e) {
String msg = "Cannot transfer response body to string, because Content-Length is too large, or " +
"Content-Length and stream length disagree.";
log.info(msg);
throw new TencentCloudSDKException(msg, e);
}
JsonResponseModel<JsonResponseErrModel> errResp;
try {
// Deserialize the response to check for errors.
Type errType = new TypeToken<JsonResponseModel<JsonResponseErrModel>>() {
}.getType();
errResp = gson.fromJson(strResp, errType);
} catch (JsonSyntaxException e) {
// Invalid JSON response: log and throw exception.
String msg = "json is not a valid representation for an object of type";
log.info(msg);
throw new TencentCloudSDKException(msg, e);
}
// Check for API errors in the response.
if (errResp.response.error != null) {
if (breakerToken != null) {
// Report the success/failure of the request to the circuit breaker.
JsonResponseErrModel error = errResp.response;
// Consider a region "OK" if we get a valid requestId and no InternalError.
boolean regionOk = error.requestId != null
&& !error.requestId.isEmpty()
&& error.error.code != null
&& !error.error.code.equals("InternalError");
breakerToken.report(regionOk);
}
throw new TencentCloudSDKException(
errResp.response.error.message,
errResp.response.requestId,
errResp.response.error.code);
}
return strResp;
}
/**
* Executes an API request and returns the deserialized response object.
* Handles circuit breaking for region failover.
*
* @param request The request object containing API parameters.
* @param actionName The name of the API action to be called.
* @param typeOfT The class of the response object to deserialize to.
* @param <T> The type of the response object.
* @return The deserialized response object.
* @throws TencentCloudSDKException If an error occurs during the API call.
*/
protected <T> T internalRequest(AbstractModel request, String actionName, Class<T> typeOfT)
throws TencentCloudSDKException {
CircuitBreaker.Token breakerToken = null;
// Attempt to acquire a token from the circuit breaker.
// If the circuit is open, use the backup endpoint.
if (regionBreaker != null) {
breakerToken = regionBreaker.allow();
if (!breakerToken.allowed) {
endpoint = service + "." + profile.getBackupEndpoint();
}
}
try {
Response resp = internalRequestRaw(request, actionName);
if (Objects.equals(resp.header("Content-Type"), "text/event-stream")) {
return processResponseSSE(resp, typeOfT, breakerToken);
}
return processResponseJson(resp, typeOfT, breakerToken);
} catch (IOException e) {
// Network failure: report to circuit breaker and throw exception.
if (breakerToken != null) {
breakerToken.report(false);
}
throw new TencentCloudSDKException("", e);
}
}
/**
* Processes a Server-Sent Events (SSE) response.
*
* @param resp The raw HTTP response.
* @param typeOfT The class of the response model.
* @param breakerToken The circuit breaker token.
* @param <T> The type of the response model.
* @return The SSE response model.
* @throws TencentCloudSDKException If an error occurs during processing.
*/
protected <T> T processResponseSSE(Response resp, Class<T> typeOfT, CircuitBreaker.Token breakerToken) throws TencentCloudSDKException {
SSEResponseModel responseModel;
try {
// Create a new instance of the response model.
responseModel = (SSEResponseModel) typeOfT.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new TencentCloudSDKException("", e);
}
// Set request ID and circuit breaker token in the response model.
responseModel.setRequestId(resp.header("X-TC-RequestId"));
responseModel.setToken(breakerToken);
responseModel.setResponse(resp);
return (T) responseModel;
}
/**
* Processes a JSON response.
*
* @param resp The raw HTTP response.
* @param typeOfT The class of the response object to deserialize to.
* @param breakerToken The circuit breaker token.
* @param <T> The type of the response object.
* @return The deserialized response object.
* @throws TencentCloudSDKException If an error occurs during processing.
*/
protected <T> T processResponseJson(Response resp, Class<T> typeOfT, CircuitBreaker.Token breakerToken) throws TencentCloudSDKException {
String body;
try {
body = resp.body().string();
} catch (IOException e) {
String msg = "Cannot transfer response body to string, because Content-Length is too large, or " +
"Content-Length and stream length disagree.";
log.info(msg);
throw new TencentCloudSDKException(msg, e);
}
JsonResponseModel<JsonResponseErrModel> errResp;
try {
Type errType = new TypeToken<JsonResponseModel<JsonResponseErrModel>>() {
}.getType();
errResp = gson.fromJson(body, errType);
} catch (JsonSyntaxException e) {
String msg = "json is not a valid representation for an object of type";
log.info(msg);
throw new TencentCloudSDKException(msg, e);
}
// Check for API errors in the response.
if (errResp.response.error != null) {
if (breakerToken != null) {
// Report the success/failure of the request to the circuit breaker.
JsonResponseErrModel error = errResp.response;
// Consider a region "OK" if we get a valid requestId and no InternalError.
boolean regionOk = error.requestId != null
&& !error.requestId.isEmpty()
&& error.error.code != null
&& !error.error.code.equals("InternalError");
breakerToken.report(regionOk);
}
throw new TencentCloudSDKException(
errResp.response.error.message,
errResp.response.requestId,
errResp.response.error.code);
}
// Deserialize the successful response into the desired object type.
Type type = TypeToken.getParameterized(JsonResponseModel.class, typeOfT).getType();
return ((JsonResponseModel<T>) gson.fromJson(body, type)).response;
}
/**
* Executes the raw API request and returns the HTTP Response object.
*
* @param request The request object containing API parameters.
* @param actionName The name of the API action to be called.
* @return The raw HTTP Response object.
* @throws TencentCloudSDKException If an error occurs during the API call.
* @throws IOException If an I/O error occurs.
*/
protected Response internalRequestRaw(AbstractModel request, String actionName)
throws TencentCloudSDKException, IOException {
Response okRsp = null;
String endpoint = this.getEndpoint();
String[] binaryParams = request.getBinaryParams();
String sm = this.profile.getSignMethod();
String reqMethod = this.profile.getHttpProfile().getReqMethod();
// currently, customized params only can be supported via post json tc3-hmac-sha256
HashMap<String, Object> customizedParams = request.any();
if (customizedParams.size() > 0) {
if (binaryParams.length > 0) {
throw new TencentCloudSDKException(
"WrongUsage: Cannot post multipart with customized parameters.");
}
if (sm.equals(ClientProfile.SIGN_SHA1) || sm.equals(ClientProfile.SIGN_SHA256)) {
throw new TencentCloudSDKException(
"WrongUsage: Cannot use HmacSHA1 or HmacSHA256 with customized parameters.");
}
if (reqMethod.equals(HttpProfile.REQ_GET)) {
throw new TencentCloudSDKException(
"WrongUsage: Cannot use get method with customized parameters.");
}
}
if (binaryParams.length > 0 || sm.equals(ClientProfile.SIGN_TC3_256)) {
okRsp = doRequestWithTC3(endpoint, request, actionName);
} else if (sm.equals(ClientProfile.SIGN_SHA1) || sm.equals(ClientProfile.SIGN_SHA256)) {
okRsp = doRequest(endpoint, request, actionName);
} else {
throw new TencentCloudSDKException(
"Signature method " + sm + " is invalid or not supported yet.");
}
// Check the HTTP response code.
if (okRsp.code() != AbstractClient.HTTP_RSP_OK) {
String msg = "response code is " + okRsp.code() + ", not 200";
log.info(msg);
throw new TencentCloudSDKException(msg, "", "ServerSideError");
}
return okRsp;
}
/**
* Executes an API request using the older signature methods (HmacSHA1 or HmacSHA256).
*
* @param endpoint The API endpoint.
* @param request The request object.
* @param action The API action name.
* @return The HTTP Response object.
* @throws TencentCloudSDKException If an error occurs.
* @throws IOException If an I/O error occurs.
*/
private Response doRequest(String endpoint, AbstractModel request, String action)
throws TencentCloudSDKException, IOException {
HashMap<String, String> param = new HashMap<String, String>();
request.toMap(param, "");
String strParam = this.formatRequestData(action, request, param);
String reqMethod = this.profile.getHttpProfile().getReqMethod();
String protocol = this.profile.getHttpProfile().getProtocol();
String url = protocol + endpoint;
String apigwEndpoint = this.profile.getHttpProfile().getApigwEndpoint();
if (null != apigwEndpoint) {
url = protocol + apigwEndpoint;
}
Builder headers = new Headers.Builder();
if (null != request.GetHeader()) {
for (Map.Entry<String, String> entry : request.GetHeader().entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
}
if (reqMethod.equals(HttpProfile.REQ_GET)) {
return this.httpConnection.getRequest(url + "?" + strParam, headers.build());
} else if (reqMethod.equals(HttpProfile.REQ_POST)) {
headers.add("X-TC-RequestClient", SDK_VERSION);
headers.add("Content-Type", "application/x-www-form-urlencoded");
return this.httpConnection.postRequest(url, strParam, headers.build());
} else {
throw new TencentCloudSDKException("Method only support (GET, POST)");
}
}
/**
* Executes an API request using the TC3-HMAC-SHA256 signature method.
*
* @param endpoint The API endpoint.
* @param request The request object.
* @param action The API action name.
* @return The HTTP Response object.
* @throws TencentCloudSDKException If an error occurs.
* @throws IOException If an I/O error occurs.
*/
private Response doRequestWithTC3(String endpoint, AbstractModel request, String action)
throws TencentCloudSDKException, IOException {
String httpRequestMethod = this.profile.getHttpProfile().getReqMethod();
if (httpRequestMethod == null) {
throw new TencentCloudSDKException(
"Request method should not be null, can only be GET or POST");
}
String contentType = "application/x-www-form-urlencoded";
byte[] requestPayload = "".getBytes(StandardCharsets.UTF_8);
HashMap<String, String> params = new HashMap<String, String>();
request.toMap(params, "");
String[] binaryParams = request.getBinaryParams();
if (binaryParams.length > 0) {
httpRequestMethod = HttpProfile.REQ_POST;
String boundary = UUID.randomUUID().toString();
// okhttp always set charset even we don't specify it,
// to ensure signature be correct, we have to set it here as well.
contentType = "multipart/form-data; charset=utf-8" + "; boundary=" + boundary;
try {
requestPayload = getMultipartPayload(request, boundary);
} catch (Exception e) {
throw new TencentCloudSDKException("Failed to generate multipart.", e);
}
} else if (httpRequestMethod.equals(HttpProfile.REQ_POST)) {
requestPayload = AbstractModel.toJsonString(request).getBytes(StandardCharsets.UTF_8);
// okhttp always set charset even we don't specify it,
// to ensure signature be correct, we have to set it here as well.
contentType = "application/json; charset=utf-8";
}
// Construct the canonical request for signature calculation.
String host = this.getHost();
if (request.GetHeader().containsKey("Host")) {
host = request.GetHeader().get("Host");
request.GetHeader().remove("Host");
}
String canonicalUri = "/";
String canonicalQueryString = this.getCanonicalQueryString(params, httpRequestMethod);
String canonicalHeaders = "content-type:" + contentType + "\nhost:" + host + "\n";
String signedHeaders = "content-type;host";
String hashedRequestPayload = "";
if (this.profile.isUnsignedPayload()) {
hashedRequestPayload = Sign.sha256Hex("UNSIGNED-PAYLOAD".getBytes(StandardCharsets.UTF_8));
} else {
hashedRequestPayload = Sign.sha256Hex(requestPayload);
}
String canonicalRequest =
httpRequestMethod
+ "\n"
+ canonicalUri
+ "\n"
+ canonicalQueryString
+ "\n"
+ canonicalHeaders
+ "\n"
+ signedHeaders
+ "\n"
+ hashedRequestPayload;
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String date = sdf.format(new Date(Long.valueOf(timestamp + "000")));
String service = host.split("\\.")[0];
String credentialScope = date + "/" + service + "/" + "tc3_request";
String hashedCanonicalRequest =
Sign.sha256Hex(canonicalRequest.getBytes(StandardCharsets.UTF_8));
String stringToSign =
"TC3-HMAC-SHA256\n" + timestamp + "\n" + credentialScope + "\n" + hashedCanonicalRequest;
boolean skipSign = request.getSkipSign();
String authorization = "";
if (skipSign) {
authorization = "SKIP";
} else {
String secretId = this.credential.getSecretId();
String secretKey = this.credential.getSecretKey();
byte[] secretDate = Sign.hmac256(("TC3" + secretKey).getBytes(StandardCharsets.UTF_8), date);
byte[] secretService = Sign.hmac256(secretDate, service);
byte[] secretSigning = Sign.hmac256(secretService, "tc3_request");
String signature =
DatatypeConverter.printHexBinary(Sign.hmac256(secretSigning, stringToSign)).toLowerCase();
authorization =
"TC3-HMAC-SHA256 "
+ "Credential="
+ secretId
+ "/"
+ credentialScope
+ ", "
+ "SignedHeaders="
+ signedHeaders
+ ", "
+ "Signature="
+ signature;
}
Builder hb = new Headers.Builder();
hb.add("Content-Type", contentType)
.add("Host", host)
.add("Authorization", authorization)
.add("X-TC-Action", action)
.add("X-TC-Timestamp", timestamp)
.add("X-TC-Version", this.apiVersion)
.add("X-TC-RequestClient", SDK_VERSION);
if (null != request.GetHeader()) {
for (Map.Entry<String, String> entry : request.GetHeader().entrySet()) {
hb.add(entry.getKey(), entry.getValue());
}
}
if (null != this.getRegion()) {
hb.add("X-TC-Region", this.getRegion());
}
String token = this.credential.getToken();
if (token != null && !token.isEmpty()) {
hb.add("X-TC-Token", token);
}
if (this.profile.isUnsignedPayload()) {
hb.add("X-TC-Content-SHA256", "UNSIGNED-PAYLOAD");
}
if (null != this.profile.getLanguage()) {
hb.add("X-TC-Language", this.profile.getLanguage().getValue());
}
String protocol = this.profile.getHttpProfile().getProtocol();
String url = protocol + endpoint;
String apigwEndpoint = this.profile.getHttpProfile().getApigwEndpoint();
if (null != apigwEndpoint) {
url = protocol + apigwEndpoint;
hb.set("Host", apigwEndpoint);
}
Headers headers = hb.build();
if (httpRequestMethod.equals(HttpProfile.REQ_GET)) {
return this.httpConnection.getRequest(url + "?" + canonicalQueryString, headers);
} else if (httpRequestMethod.equals(HttpProfile.REQ_POST)) {
return this.httpConnection.postRequest(url, requestPayload, headers);
} else {
throw new TencentCloudSDKException("Method only support GET, POST");
}
}
/**
* Constructs the multipart payload for file uploads.
*
* @param request The request object containing file parameters.
* @param boundary The boundary string to separate parts of the multipart data.
* @return The byte array representing the multipart payload.
* @throws Exception If an error occurs during payload construction.
*/
private byte[] getMultipartPayload(AbstractModel request, String boundary) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String[] binaryParams = request.getBinaryParams();
// Iterate through each parameter in the multipart request.
for (Map.Entry<String, byte[]> entry : request.getMultipartRequestParams().entrySet()) {
baos.write("--".getBytes(StandardCharsets.UTF_8));
baos.write(boundary.getBytes(StandardCharsets.UTF_8));
baos.write("\r\n".getBytes(StandardCharsets.UTF_8));
baos.write("Content-Disposition: form-data; name=\"".getBytes(StandardCharsets.UTF_8));
baos.write(entry.getKey().getBytes(StandardCharsets.UTF_8));
if (Arrays.asList(binaryParams).contains(entry.getKey())) {
baos.write("\"; filename=\"".getBytes(StandardCharsets.UTF_8));
baos.write(entry.getKey().getBytes(StandardCharsets.UTF_8));
baos.write("\"\r\n".getBytes(StandardCharsets.UTF_8));
} else {
baos.write("\"\r\n".getBytes(StandardCharsets.UTF_8));
}
baos.write("\r\n".getBytes(StandardCharsets.UTF_8));
baos.write(entry.getValue());
baos.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
// Write the closing boundary if there's any data.
if (baos.size() != 0) {
baos.write("--".getBytes(StandardCharsets.UTF_8));
baos.write(boundary.getBytes(StandardCharsets.UTF_8));
baos.write("--\r\n".getBytes(StandardCharsets.UTF_8));
}
byte[] bytes = baos.toByteArray();
baos.close();
return bytes;
}
/**
* Generates the canonical query string for GET requests.
*
* @param params The map of request parameters.
* @param method The HTTP method (should be GET).
* @return The canonical query string.
* @throws TencentCloudSDKException If UTF-8 encoding is not supported.
*/
private String getCanonicalQueryString(HashMap<String, String> params, String method)
throws TencentCloudSDKException {
// POST requests don't have a query string in the signature.
if (method != null && method.equals(HttpProfile.REQ_POST)) {
return "";
}
StringBuilder queryString = new StringBuilder("");
// Iterate through each parameter and build the query string.
for (Map.Entry<String, String> entry : params.entrySet()) {
String v;
try {
v = URLEncoder.encode(entry.getValue(), "UTF8");
} catch (UnsupportedEncodingException e) {
throw new TencentCloudSDKException("UTF8 is not supported.", e);
}
queryString.append("&").append(entry.getKey()).append("=").append(v);
}
// Remove the leading '&' if the query string is not empty.
if (queryString.length() == 0) {
return "";
} else {
return queryString.toString().substring(1);
}
}
/**
* Formats the request data for signing (older signature methods).
*
* @param action The API action name.
* @param param The map of request parameters.
* @return The formatted string for signing.
* @throws TencentCloudSDKException If UTF-8 encoding is not supported.
*/
private String formatRequestData(String action, AbstractModel request, Map<String, String> param)
throws TencentCloudSDKException {
param.put("Action", action);
param.put("RequestClient", this.sdkVersion);
param.put("Nonce", String.valueOf(Math.abs(new SecureRandom().nextInt())));
param.put("Timestamp", String.valueOf(System.currentTimeMillis() / 1000));
param.put("Version", this.apiVersion);
// Add SecretId, Region, SignatureMethod, and Token if available.
if (this.credential.getSecretId() != null && (!this.credential.getSecretId().isEmpty())) {
param.put("SecretId", this.credential.getSecretId());
}
if (this.region != null && (!this.region.isEmpty())) {
param.put("Region", this.region);
}
if (this.profile.getSignMethod() != null && (!this.profile.getSignMethod().isEmpty())) {
param.put("SignatureMethod", this.profile.getSignMethod());
}
if (this.credential.getToken() != null && (!this.credential.getToken().isEmpty())) {
param.put("Token", this.credential.getToken());
}