Skip to content

Commit

Permalink
improve for coding style
Browse files Browse the repository at this point in the history
  • Loading branch information
JacksonTian committed Jul 8, 2024
1 parent bdb4fbc commit 62b2c9e
Show file tree
Hide file tree
Showing 9 changed files with 53 additions and 135 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,10 @@
@SuppressWarnings("deprecation")
public class DefaultAcsClient implements IAcsClient {

/*
Now maxRetryNumber and autoRetry has no effect.
*/
// Now maxRetryNumber and autoRetry has no effect.
private int maxRetryNumber = 3;
private boolean autoRetry = true;
private IClientProfile clientProfile = null;
private IClientProfile clientProfile;
private AlibabaCloudCredentialsProvider credentialsProvider;

private IHttpClient httpClient;
Expand Down Expand Up @@ -118,12 +116,10 @@ public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, Stri
request.setSysSignatureAlgorithm(this.signatureAlgorithm);
}
Signer signer = Signer.getSigner(new LegacyCredentials(credential), request.getSysSignatureVersion(), request.getSysSignatureAlgorithm());
FormatType format = null;
if (null == request.getSysRegionId()) {
request.setSysRegionId(regionId);
}
return doAction(request, autoRetry, maxRetryNumber, regionId, new LegacyCredentials(credential), signer,
format);
return doAction(request, regionId, new LegacyCredentials(credential), signer, null);
}

@Override
Expand Down Expand Up @@ -191,8 +187,6 @@ public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, bool
if (null == profile) {
throw new ClientException("SDK.InvalidProfile", "No active profile found.");
}
boolean retry = autoRetry;
int retryNumber = maxRetryCounts;
String region = profile.getRegionId();
if (null == request.getSysRegionId()) {
request.setSysRegionId(region);
Expand All @@ -212,7 +206,7 @@ public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, bool
Signer signer = Signer.getSigner(credentials, request.getSysSignatureVersion(), request.getSysSignatureAlgorithm());
FormatType format = profile.getFormat();

return this.doAction(request, retry, retryNumber, request.getSysRegionId(), credentials, signer, format);
return this.doAction(request, request.getSysRegionId(), credentials, signer, format);
}

private <T extends AcsResponse> T parseAcsResponse(AcsRequest<T> request, HttpResponse baseResponse)
Expand Down Expand Up @@ -254,13 +248,13 @@ private <T extends AcsResponse> T parseAcsResponse(AcsRequest<T> request, HttpRe
public <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryNumber,
String regionId, Credential credential, Signer signer, FormatType format)
throws ClientException, ServerException {
return doAction(request, autoRetry, maxRetryNumber, regionId, new LegacyCredentials(credential), signer,
return doAction(request, regionId, new LegacyCredentials(credential), signer,
format);
}

public ProductDomain getDomain(AcsRequest request, String regionId)
throws ClientException {
ProductDomain domain = null;
ProductDomain domain;
if (request.getSysProductDomain() != null) {
domain = request.getSysProductDomain();
} else {
Expand All @@ -283,11 +277,11 @@ public ProductDomain getDomain(AcsRequest request, String regionId)
return domain;
}

private <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boolean autoRetry, int maxRetryNumber,
private <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request,
String regionId, AlibabaCloudCredentials credentials, Signer signer, FormatType format)
throws ClientException, ServerException {
if (!GlobalTracer.isRegistered() || clientProfile.isCloseTrace()) {
return doRealAction(request, autoRetry, maxRetryNumber, regionId, credentials, signer, format);
return doRealAction(request, regionId, credentials, signer, format);
}

Tracer tracer = GlobalTracer.get();
Expand All @@ -302,7 +296,7 @@ private <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boo
.start();
tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new HttpHeadersInjectAdapter(request));
try {
HttpResponse response = doRealAction(request, autoRetry, maxRetryNumber, regionId, credentials, signer, format);
HttpResponse response = doRealAction(request, regionId, credentials, signer, format);
span.setTag("status", response.getStatus());
span.setTag("ReasonPhrase", response.getReasonPhrase());
return response;
Expand All @@ -315,7 +309,7 @@ private <T extends AcsResponse> HttpResponse doAction(AcsRequest<T> request, boo

}

private <T extends AcsResponse> HttpResponse doRealAction(AcsRequest<T> request, boolean autoRetry, int maxRetryNumber,
private <T extends AcsResponse> HttpResponse doRealAction(AcsRequest<T> request,
String regionId, AlibabaCloudCredentials credentials, Signer signer, FormatType format)
throws ClientException, ServerException {

Expand Down Expand Up @@ -454,17 +448,17 @@ private <T extends AcsResponse> HttpResponse doRealAction(AcsRequest<T> request,
* 2019-01-03 change access control from private to protected, then subClass can
* override it and rewrite httpResponse processing
*/
protected <T extends AcsResponse> T readResponse(Class<T> clasz, HttpResponse httpResponse, FormatType format)
protected <T extends AcsResponse> T readResponse(Class<T> clazz, HttpResponse httpResponse, FormatType format)
throws ClientException {
// new version response contains "@XmlRootElement" annotation
if (clasz.isAnnotationPresent(XmlRootElement.class)
if (clazz.isAnnotationPresent(XmlRootElement.class)
&& !clientProfile.getHttpClientConfig().isCompatibleMode()) {
Unmarshaller unmarshaller = UnmarshallerFactory.getUnmarshaller(format);
return unmarshaller.unmarshal(clasz, httpResponse.getHttpContentString());
return unmarshaller.unmarshal(clazz, httpResponse.getHttpContentString());
} else {
Reader reader = ReaderFactory.createInstance(format);
UnmarshallerContext context = new UnmarshallerContext();
T response = null;
T response;
String stringContent = httpResponse.getHttpContentString();

if (stringContent == null) {
Expand All @@ -473,13 +467,13 @@ protected <T extends AcsResponse> T readResponse(Class<T> clasz, HttpResponse ht
}

try {
response = clasz.newInstance();
response = clazz.newInstance();
} catch (Exception e) {
throw new ClientException("SDK.InvalidResponseClass",
"Unable to allocate " + clasz.getName() + " class");
"Unable to allocate " + clazz.getName() + " class");
}

String responseEndpoint = clasz.getName().substring(clasz.getName().lastIndexOf(".") + 1);
String responseEndpoint = clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1);
if (response.checkShowJsonItemName()) {
context.setResponseMap(reader.read(stringContent, responseEndpoint));
} else {
Expand Down Expand Up @@ -532,6 +526,7 @@ public void doActionWithProxy(ProtocolType protocolType, String httpsProxy, Stri
config.setHttpsProxy(httpsProxy);
return;
}
return;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public class BasicSessionCredentials implements AlibabaCloudCredentials {
private final String accessKeyId;
private final String accessKeySecret;
private final String sessionToken;
private long sessionStartedTimeInMilliSeconds = 0;
private long sessionStartedTimeInMilliSeconds;

public BasicSessionCredentials(String accessKeyId, String accessKeySecret, String sessionToken) {
this(accessKeyId, accessKeySecret, sessionToken, 0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
public class ECSMetadataServiceCredentialsFetcher {
private static final String URL_IN_ECS_METADATA = "/latest/meta-data/ram/security-credentials/";
private static final int DEFAULT_TIMEOUT_IN_MILLISECONDS = 1000;
private static final String ECS_METADAT_FETCH_ERROR_MSG = "Failed to get RAM session credentials from ECS metadata service.";
private static final String ECS_METADATA_FETCH_ERROR_MSG = "Failed to get RAM session credentials from ECS metadata service.";
private static final int DEFAULT_ECS_SESSION_TOKEN_DURATION_SECONDS = 3600 * 6;
private URL credentialUrl;
private String roleName;
Expand All @@ -28,7 +28,7 @@ public ECSMetadataServiceCredentialsFetcher() {

public void setRoleName(String roleName) {
if (null == roleName) {
throw new NullPointerException("You must specifiy a valid role name.");
throw new NullPointerException("You must specify a valid role name.");
}
this.roleName = roleName;
setCredentialUrl();
Expand Down Expand Up @@ -68,22 +68,22 @@ public String getMetadata() throws ClientException {
}

if (response.getStatus() != HttpURLConnection.HTTP_OK) {
throw new ClientException(ECS_METADAT_FETCH_ERROR_MSG + " HttpCode=" + response.getStatus());
throw new ClientException(ECS_METADATA_FETCH_ERROR_MSG + " HttpCode=" + response.getStatus());
}

return new String(response.getHttpContent());
}

public InstanceProfileCredentials fetch() throws ClientException {
String jsonContent = getMetadata();
JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();;
JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
if (!jsonObject.has("Code") || !jsonObject.has("AccessKeyId") || !jsonObject.has("AccessKeySecret") || !jsonObject
.has("SecurityToken") || !jsonObject.has("Expiration")) {
throw new ClientException("Invalid json got from ECS Metadata service.");
}

if (!"Success".equals(jsonObject.get("Code").getAsString())) {
throw new ClientException(ECS_METADAT_FETCH_ERROR_MSG);
throw new ClientException(ECS_METADATA_FETCH_ERROR_MSG);
}
return new InstanceProfileCredentials(
jsonObject.get("AccessKeyId").getAsString(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ public AlibabaCloudCredentials getCredentials() throws ClientException {
if (accessKeyId == null || accessKeySecret == null) {
return null;
}
if (accessKeyId.length() == 0) {
if (accessKeyId.isEmpty()) {
throw new ClientException("Environment variable accessKeyId cannot be empty");
}
if (accessKeySecret.length() == 0) {
if (accessKeySecret.isEmpty()) {
throw new ClientException("Environment variable accessKeySecret cannot be empty");
}
return new BasicCredentials(accessKeyId, accessKeySecret);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class InstanceProfileCredentialsProvider implements AlibabaCloudCredentia

public InstanceProfileCredentialsProvider(String roleName) {
if (null == roleName) {
throw new NullPointerException("You must specifiy a valid role name.");
throw new NullPointerException("You must specify a valid role name.");
}
this.roleName = roleName;
this.fetcher = new ECSMetadataServiceCredentialsFetcher();
Expand All @@ -29,11 +29,7 @@ public InstanceProfileCredentialsProvider withFetcher(ECSMetadataServiceCredenti
public AlibabaCloudCredentials getCredentials() throws ClientException {
if (credentials == null || credentials.isExpired()) {
ecsMetadataServiceFetchCount += 1;
int maxRetryTimes = MAX_ECS_METADATA_FETCH_RETRY_TIMES;
credentials = fetcher.fetch(maxRetryTimes);
// } else if (credentials.isExpired()) {
// throw new ClientException("SDK.SessionTokenExpired", "Current session token
// has expired.");
credentials = fetcher.fetch(MAX_ECS_METADATA_FETCH_RETRY_TIMES);
} else if (credentials.willSoonExpire() && credentials.shouldRefresh()) {
try {
ecsMetadataServiceFetchCount += 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import java.util.Map;
import java.util.Date;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
Expand Down Expand Up @@ -136,7 +135,7 @@ private String invokeAssumeRoleWithOIDC() throws ClientException {
queries.put("Format", "JSON");
queries.put("Version", "2015-04-01");
queries.put("Timestamp", ParameterHelper.getISO8601Time(new Date()));
String url = null;
String url;
try {
url = this.stsEndpoint + "?" + new String(ParameterHelper.getFormData(queries));
} catch (UnsupportedEncodingException e) {
Expand All @@ -148,11 +147,11 @@ private String invokeAssumeRoleWithOIDC() throws ClientException {
httpRequest.setHttpContentType(FormatType.FORM);
httpRequest.setSysConnectTimeout(1000);
httpRequest.setSysReadTimeout(3000);
String oidcToken = null;
String oidcToken;
FileInputStream in = null;
byte[] buffer;
try {
in = new FileInputStream(new File(oidcTokenFilePath));
in = new FileInputStream(oidcTokenFilePath);
buffer = new byte[in.available()];
in.read(buffer);
oidcToken = new String(buffer, "UTF-8");
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ public synchronized static DefaultProfile getProfile(String regionId) {
* @Deprecated : Use addEndpoint(String regionId, String product, String endpoint) instead of this
*/
@Deprecated
public synchronized static void addEndpoint(String endpointName, String regionId, String product, String domain)
throws ClientException {
public synchronized static void addEndpoint(String endpointName, String regionId, String product, String domain) {
addEndpoint(endpointName, regionId, product, domain, true);
}

Expand Down
Loading

0 comments on commit 62b2c9e

Please sign in to comment.