Commit a8f1c612 authored by zhaowei's avatar zhaowei

init

parent e767d74b
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>com.dsk.acc</groupId>
<version>2.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<artifactId>dsk-open-sdk-java</artifactId>
<name>开放平台-sdk</name>
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.65</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.33</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
</build>
<!--使用分发上传将项目打成jar包,上传到nexus私服上-->
<distributionManagement>
<!--快照版本仓库-->
<snapshotRepository>
<!--nexus服务器中用户名:在settings.xml中和<server>的id一致-->
<id>snapshots</id>
<!--自定义名称-->
<name>snapshots</name>
<!--仓库地址-->
<url>http://120.27.13.145:8081/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
\ No newline at end of file
package com.dsk.acc.openapi;
/**
*
* @author zhaowei 2021年9月2日
*/
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dsk.acc.openapi.api.AccClient;
import com.dsk.acc.openapi.client.Config;
//@Slf4j
//@Component
public class DemoAccClientUtil {
public static String accessKeyId;
public static String accessSecret;
/**
* -开放平台统一请求
* @param path
* @param bodyMap
* @return
*/
public static JSONObject request(String path, Map<String, Object> bodyMap){
JSONObject resObj = null;
try {
AccClient.init(new Config(accessKeyId, accessSecret));
Map<String, ?> res = AccClient.request(path, bodyMap);
if(res.get("body") == null || res.get("headers") == null) {
return null;
}
resObj = JSON.parseObject(JSON.toJSONString(res.get("body")));
} catch (Exception e) {
// log.error("请求开放平台失败,reqPath={},reqBody={},e={}", path, JSON.toJSONString(bodyMap), e.getMessage());
}
return resObj;
}
public String getAccessKeyId() {
return accessKeyId;
}
// @Value("${dsk-acc.open.accessKeyId}")
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessSecret() {
return accessSecret;
}
// @Value("${dsk-acc.open.accessSecret}")
public void setAccessSecret(String accessSecret) {
this.accessSecret = accessSecret;
}
}
\ No newline at end of file
package com.dsk.acc.openapi.api;
import java.util.Map;
import com.dsk.acc.openapi.client.Client;
import com.dsk.acc.openapi.client.Config;
import com.dsk.acc.openapi.client.bean.OpenApiRequest;
import com.dsk.acc.openapi.client.bean.Params;
import com.dsk.acc.openapi.client.bean.RuntimeOptions;
import com.dsk.acc.openapi.client.core.AccConverter;
import com.dsk.acc.openapi.client.core.AccPair;
import com.dsk.acc.openapi.client.exception.AccValidException;
public class AccClient {
private static Client client;
private static String version = "1.0.0";
private static String OPENAPI_POINT = "120.27.13.145:8766"; //测试
// private static String OPENAPI_POINT = "120.27.13.145:8766"; //正式
private AccClient() {
}
/**
* -单例生成
* @param config
* @return
*/
public static void init(Config config) {
try {
if(client == null) client = new Client(config.setEndpoint(OPENAPI_POINT));
} catch (Exception e) {
throw new AccValidException("client config init error", e);
}
}
/**
* -发起请求
* @param config
* @return
*/
public static Map<String, ?> request(String pathname, Map<String, Object> reqBody){
if(client == null) throw new AccValidException("client not init");
OpenApiRequest req;
Map<String, ?> callApi = null;
try {
req = OpenApiRequest.build(AccConverter.buildMap( new AccPair("body", reqBody) ));
Params params = new Params()
.setAction(pathname)
.setPathname(pathname)
.setAuthType("AK")
.setBodyType("json")
.setReqBodyType("json")
.setMethod("POST")
.setProtocol("HTTP")
.setVersion(version);
callApi = client.callApi(params, req, new RuntimeOptions());
} catch (Exception e) {
e.printStackTrace();
}
return callApi;
}
}
package com.dsk.acc.openapi.client;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface AccJsonField {
/** 命名 */
String value();
/** 反序列化字段时字段的可选名称 */
String[] alternate() default {};
}
package com.dsk.acc.openapi.client;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface AccValid {
String pattern() default "";
int maxLength() default 0;
int minLength() default 0;
double maximum() default Double.MAX_VALUE;
double minimum() default Double.MIN_VALUE;
boolean required() default false;
}
package com.dsk.acc.openapi.client;
import java.util.Map;
import com.dsk.acc.openapi.client.bean.OpenApiRequest;
import com.dsk.acc.openapi.client.bean.Params;
import com.dsk.acc.openapi.client.bean.RuntimeOptions;
import com.dsk.acc.openapi.client.core.Acc;
import com.dsk.acc.openapi.client.core.AccConverter;
import com.dsk.acc.openapi.client.core.AccModel;
import com.dsk.acc.openapi.client.core.AccPair;
import com.dsk.acc.openapi.client.core.AccRequest;
import com.dsk.acc.openapi.client.core.AccResponse;
import com.dsk.acc.openapi.client.exception.AccException;
import com.dsk.acc.openapi.client.exception.AccUnretryableException;
import com.dsk.acc.openapi.client.util.ClientUtil;
import com.dsk.acc.openapi.client.util.CommonUtils;
public class Client {
public String _endpoint;
public String _regionId;
public String _protocol;
public String _userAgent;
public String _endpointRule;
public Map<String, String> _endpointMap;
public Integer _readTimeout;
public Integer _connectTimeout;
public String _network;
public Integer _maxIdleConns;
public String _signatureAlgorithm;
public Map<String, String> _headers;
public String _accessKeyId;
public String _accessKeySecret;
public String _securityToken;
public Client(Config config) throws Exception {
if (CommonUtils.isUnset(AccModel.buildMap(config))) {
throw new AccException(AccConverter.buildMap(
new AccPair("code", "ParameterMissing"),
new AccPair("message", "'config' can not be unset")
));
}
this._accessKeyId = config.accessKeyId;
this._accessKeySecret = config.accessKeySecret;
this._securityToken = config.securityToken;
this._endpoint = CommonUtils.defaultString(config.endpoint, "import.jiansheku.com");
this._protocol = config.protocol;
this._regionId = config.regionId;
this._userAgent = config.userAgent;
this._readTimeout = config.readTimeout;
this._connectTimeout = config.connectTimeout;
this._maxIdleConns = config.maxIdleConns;
}
public Map<String, ?> doRPCRequest(String action, String version, String protocol, String method, String authType, String bodyType, OpenApiRequest request, RuntimeOptions runtime) throws Exception {
AccModel.validateParams(request, "request");
Map<String, Object> runtime_ = AccConverter.buildMap(
new AccPair("timeouted", "retry"),
new AccPair("readTimeout", CommonUtils.defaultNumber(runtime.readTimeout, _readTimeout)),
new AccPair("connectTimeout", CommonUtils.defaultNumber(runtime.connectTimeout, _connectTimeout)),
new AccPair("maxIdleConns", CommonUtils.defaultNumber(runtime.maxIdleConns, _maxIdleConns)),
new AccPair("retry", AccConverter.buildMap(
new AccPair("retryable", runtime.autoretry),
new AccPair("maxAttempts", CommonUtils.defaultNumber(runtime.maxAttempts, 3))
)),
new AccPair("ignoreSSL", runtime.ignoreSSL)
);
AccRequest _lastRequest = null;
Exception _lastException = null;
long _now = System.currentTimeMillis();
int _retryTimes = 0;
while (Acc.allowRetry((Map<String, Object>) runtime_.get("retry"), _retryTimes, _now)) {
if (_retryTimes > 0) {
int backoffTime = Acc.getBackoffTime(runtime_.get("backoff"), _retryTimes);
if (backoffTime > 0) {
Acc.sleep(backoffTime);
}
}
_retryTimes = _retryTimes + 1;
try {
AccRequest request_ = new AccRequest();
request_.protocol = CommonUtils.defaultString(_protocol, protocol);
request_.method = method;
request_.pathname = "/";
request_.query = AccConverter.merge(String.class,
AccConverter.buildMap(
new AccPair("Action", action),
new AccPair("Format", "json"),
new AccPair("Version", version),
new AccPair("Timestamp", System.currentTimeMillis()),
new AccPair("SignatureNonce", CommonUtils.getNonce())
),
request.query
);
Map<String, String> headers = this.getRpcHeaders();
if (CommonUtils.isUnset(headers)) {
// endpoint is setted in product client
request_.headers = AccConverter.buildMap(
new AccPair("host", _endpoint),
new AccPair("x-acc-version", version),
new AccPair("x-acc-action", action),
new AccPair("user-agent", this.getUserAgent())
);
} else {
request_.headers = AccConverter.merge(String.class,
AccConverter.buildMap(
new AccPair("host", _endpoint),
new AccPair("x-acc-version", version),
new AccPair("x-acc-action", action),
new AccPair("user-agent", this.getUserAgent())
),
headers
);
}
if (!CommonUtils.isUnset(request.body)) {
Map<String, Object> m = CommonUtils.assertAsMap(request.body);
Map<String, Object> tmp = CommonUtils.anyifyMapValue(ClientUtil.query(m));
request_.body = Acc.toReadable(CommonUtils.toFormString(tmp));
request_.headers.put("content-type", "application/x-www-form-urlencoded");
}
if (!CommonUtils.equalString(authType, "Anonymous")) {
String accessKeyId = this.getAccessKeyId();
String accessKeySecret = this.getAccessKeySecret();
String securityToken = this.getSecurityToken();
if (!CommonUtils.empty(securityToken)) {
request_.query.put("SecurityToken", securityToken);
}
request_.query.put("SignatureMethod", "HMAC-SHA1");
request_.query.put("SignatureVersion", "1.0");
request_.query.put("AccessKeyId", accessKeyId);
Map<String, Object> t = null;
if (!CommonUtils.isUnset(request.body)) {
t = CommonUtils.assertAsMap(request.body);
}
Map<String, String> signedParam = AccConverter.merge(String.class,
request_.query,
ClientUtil.query(t)
);
request_.query.put("Signature", ClientUtil.getRPCSignature(signedParam, request_.method, accessKeySecret));
}
_lastRequest = request_;
AccResponse response_ = Acc.doAction(request_, runtime_);
if (CommonUtils.is4xx(response_.statusCode) || CommonUtils.is5xx(response_.statusCode)) {
Object _res = CommonUtils.readAsJSON(response_.body);
Map<String, Object> err = CommonUtils.assertAsMap(_res);
Object requestId = Client.defaultAny(err.get("RequestId"), err.get("requestId"));
throw new AccException(AccConverter.buildMap(
new AccPair("code", "" + Client.defaultAny(err.get("code"), err.get("statusCode")) + ""),
new AccPair("msg", "code: " + response_.statusCode + ", " + Client.defaultAny(err.get("msg"), err.get("message")) + " request id: " + requestId + ""),
new AccPair("data", err)
));
}
if (CommonUtils.equalString(bodyType, "binary")) {
Map<String, Object> resp = AccConverter.buildMap(
new AccPair("body", response_.body),
new AccPair("headers", response_.headers)
);
return resp;
} else if (CommonUtils.equalString(bodyType, "byte")) {
byte[] byt = CommonUtils.readAsBytes(response_.body);
return AccConverter.buildMap(
new AccPair("body", byt),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(bodyType, "string")) {
String str = CommonUtils.readAsString(response_.body);
return AccConverter.buildMap(
new AccPair("body", str),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(bodyType, "json")) {
Object obj = CommonUtils.readAsJSON(response_.body);
Map<String, Object> res = CommonUtils.assertAsMap(obj);
return AccConverter.buildMap(
new AccPair("body", res),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(bodyType, "array")) {
Object arr = CommonUtils.readAsJSON(response_.body);
return AccConverter.buildMap(
new AccPair("body", arr),
new AccPair("headers", response_.headers)
);
} else {
return AccConverter.buildMap(
new AccPair("headers", response_.headers)
);
}
} catch (Exception e) {
if (Acc.isRetryable(e)) {
_lastException = e;
continue;
}
throw e;
}
}
throw new AccUnretryableException(_lastRequest, _lastException);
}
public Map<String, ?> doROARequest(String action, String version, String protocol, String method, String authType, String pathname, String bodyType, OpenApiRequest request, RuntimeOptions runtime) throws Exception {
AccModel.validateParams(request, "request");
Map<String, Object> runtime_ = AccConverter.buildMap(
new AccPair("timeouted", "retry"),
new AccPair("readTimeout", CommonUtils.defaultNumber(runtime.readTimeout, _readTimeout)),
new AccPair("connectTimeout", CommonUtils.defaultNumber(runtime.connectTimeout, _connectTimeout)),
new AccPair("maxIdleConns", CommonUtils.defaultNumber(runtime.maxIdleConns, _maxIdleConns)),
new AccPair("retry", AccConverter.buildMap(
new AccPair("retryable", runtime.autoretry),
new AccPair("maxAttempts", CommonUtils.defaultNumber(runtime.maxAttempts, 3))
)),
new AccPair("ignoreSSL", runtime.ignoreSSL)
);
AccRequest _lastRequest = null;
Exception _lastException = null;
long _now = System.currentTimeMillis();
int _retryTimes = 0;
while (Acc.allowRetry((Map<String, Object>) runtime_.get("retry"), _retryTimes, _now)) {
if (_retryTimes > 0) {
int backoffTime = Acc.getBackoffTime(runtime_.get("backoff"), _retryTimes);
if (backoffTime > 0) {
Acc.sleep(backoffTime);
}
}
_retryTimes = _retryTimes + 1;
try {
AccRequest request_ = new AccRequest();
request_.protocol = CommonUtils.defaultString(_protocol, protocol);
request_.method = method;
request_.pathname = pathname;
request_.headers = AccConverter.merge(String.class,
AccConverter.buildMap(
new AccPair("date", CommonUtils.getDateUTCString()),
new AccPair("host", _endpoint),
new AccPair("accept", "application/json"),
new AccPair("x-acc-signature-nonce", CommonUtils.getNonce()),
new AccPair("x-acc-signature-method", "HMAC-SHA1"),
new AccPair("x-acc-signature-version", "1.0"),
new AccPair("x-acc-version", version),
new AccPair("x-acc-action", action),
new AccPair("user-agent", CommonUtils.getUserAgent(_userAgent))
),
request.headers
);
if (!CommonUtils.isUnset(request.body)) {
request_.body = Acc.toReadable(CommonUtils.toJSONString(request.body));
request_.headers.put("content-type", "application/json; charset=utf-8");
}
if (!CommonUtils.isUnset(request.query)) {
request_.query = request.query;
}
if (!CommonUtils.equalString(authType, "Anonymous")) {
String accessKeyId = this.getAccessKeyId();
String accessKeySecret = this.getAccessKeySecret();
String securityToken = this.getSecurityToken();
if (!CommonUtils.empty(securityToken)) {
request_.headers.put("x-acc-accesskey-id", accessKeyId);
request_.headers.put("x-acc-security-token", securityToken);
}
String stringToSign = ClientUtil.getStringToSign(request_);
request_.headers.put("authorization", "acs " + accessKeyId + ":" + ClientUtil.getROASignature(stringToSign, accessKeySecret) + "");
}
_lastRequest = request_;
AccResponse response_ = Acc.doAction(request_, runtime_);
if (CommonUtils.equalNumber(response_.statusCode, 204)) {
return AccConverter.buildMap(
new AccPair("headers", response_.headers)
);
}
if (CommonUtils.is4xx(response_.statusCode) || CommonUtils.is5xx(response_.statusCode)) {
Object _res = CommonUtils.readAsJSON(response_.body);
Map<String, Object> err = CommonUtils.assertAsMap(_res);
Object requestId = Client.defaultAny(err.get("RequestId"), err.get("requestId"));
requestId = Client.defaultAny(requestId, err.get("requestid"));
throw new AccException(AccConverter.buildMap(
new AccPair("code", "" + Client.defaultAny(err.get("code"), err.get("statusCode")) + ""),
new AccPair("msg", "code: " + response_.statusCode + ", " + Client.defaultAny(err.get("msg"), err.get("message")) + " request id: " + requestId + ""),
new AccPair("data", err)
));
}
if (CommonUtils.equalString(bodyType, "binary")) {
Map<String, Object> resp = AccConverter.buildMap(
new AccPair("body", response_.body),
new AccPair("headers", response_.headers)
);
return resp;
} else if (CommonUtils.equalString(bodyType, "byte")) {
byte[] byt = CommonUtils.readAsBytes(response_.body);
return AccConverter.buildMap(
new AccPair("body", byt),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(bodyType, "string")) {
String str = CommonUtils.readAsString(response_.body);
return AccConverter.buildMap(
new AccPair("body", str),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(bodyType, "json")) {
Object obj = CommonUtils.readAsJSON(response_.body);
Map<String, Object> res = CommonUtils.assertAsMap(obj);
return AccConverter.buildMap(
new AccPair("body", res),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(bodyType, "array")) {
Object arr = CommonUtils.readAsJSON(response_.body);
return AccConverter.buildMap(
new AccPair("body", arr),
new AccPair("headers", response_.headers)
);
} else {
return AccConverter.buildMap(
new AccPair("headers", response_.headers)
);
}
} catch (Exception e) {
if (Acc.isRetryable(e)) {
_lastException = e;
continue;
}
throw e;
}
}
throw new AccUnretryableException(_lastRequest, _lastException);
}
public Map<String, ?> doROARequestWithForm(String action, String version, String protocol, String method, String authType, String pathname, String bodyType, OpenApiRequest request, RuntimeOptions runtime) throws Exception {
AccModel.validateParams(request, "request");
Map<String, Object> runtime_ = AccConverter.buildMap(
new AccPair("timeouted", "retry"),
new AccPair("readTimeout", CommonUtils.defaultNumber(runtime.readTimeout, _readTimeout)),
new AccPair("connectTimeout", CommonUtils.defaultNumber(runtime.connectTimeout, _connectTimeout)),
new AccPair("maxIdleConns", CommonUtils.defaultNumber(runtime.maxIdleConns, _maxIdleConns)),
new AccPair("retry", AccConverter.buildMap(
new AccPair("retryable", runtime.autoretry),
new AccPair("maxAttempts", CommonUtils.defaultNumber(runtime.maxAttempts, 3))
)),
new AccPair("ignoreSSL", runtime.ignoreSSL)
);
AccRequest _lastRequest = null;
Exception _lastException = null;
long _now = System.currentTimeMillis();
int _retryTimes = 0;
while (Acc.allowRetry((Map<String, Object>) runtime_.get("retry"), _retryTimes, _now)) {
if (_retryTimes > 0) {
int backoffTime = Acc.getBackoffTime(runtime_.get("backoff"), _retryTimes);
if (backoffTime > 0) {
Acc.sleep(backoffTime);
}
}
_retryTimes = _retryTimes + 1;
try {
AccRequest request_ = new AccRequest();
request_.protocol = CommonUtils.defaultString(_protocol, protocol);
request_.method = method;
request_.pathname = pathname;
request_.headers = AccConverter.merge(String.class,
AccConverter.buildMap(
new AccPair("date", CommonUtils.getDateUTCString()),
new AccPair("host", _endpoint),
new AccPair("accept", "application/json"),
new AccPair("x-acc-signature-nonce", CommonUtils.getNonce()),
new AccPair("x-acc-signature-method", "HMAC-SHA1"),
new AccPair("x-acc-signature-version", "1.0"),
new AccPair("x-acc-version", version),
new AccPair("x-acc-action", action),
new AccPair("user-agent", CommonUtils.getUserAgent(_userAgent))
),
request.headers
);
if (!CommonUtils.isUnset(request.body)) {
Map<String, Object> m = CommonUtils.assertAsMap(request.body);
request_.body = Acc.toReadable(ClientUtil.toForm(m));
request_.headers.put("content-type", "application/x-www-form-urlencoded");
}
if (!CommonUtils.isUnset(request.query)) {
request_.query = request.query;
}
if (!CommonUtils.equalString(authType, "Anonymous")) {
String accessKeyId = this.getAccessKeyId();
String accessKeySecret = this.getAccessKeySecret();
String securityToken = this.getSecurityToken();
if (!CommonUtils.empty(securityToken)) {
request_.headers.put("x-acc-accesskey-id", accessKeyId);
request_.headers.put("x-acc-security-token", securityToken);
}
String stringToSign = ClientUtil.getStringToSign(request_);
request_.headers.put("authorization", "acs " + accessKeyId + ":" + ClientUtil.getROASignature(stringToSign, accessKeySecret) + "");
}
_lastRequest = request_;
AccResponse response_ = Acc.doAction(request_, runtime_);
if (CommonUtils.equalNumber(response_.statusCode, 204)) {
return AccConverter.buildMap(
new AccPair("headers", response_.headers)
);
}
if (CommonUtils.is4xx(response_.statusCode) || CommonUtils.is5xx(response_.statusCode)) {
Object _res = CommonUtils.readAsJSON(response_.body);
Map<String, Object> err = CommonUtils.assertAsMap(_res);
throw new AccException(AccConverter.buildMap(
new AccPair("code", "" + Client.defaultAny(err.get("code"), err.get("statusCode")) + ""),
new AccPair("msg", "code: " + response_.statusCode + ", " + Client.defaultAny(err.get("msg"), err.get("message")) + " request id: " + Client.defaultAny(err.get("RequestId"), err.get("requestId")) + ""),
new AccPair("data", err)
));
}
if (CommonUtils.equalString(bodyType, "binary")) {
Map<String, Object> resp = AccConverter.buildMap(
new AccPair("body", response_.body),
new AccPair("headers", response_.headers)
);
return resp;
} else if (CommonUtils.equalString(bodyType, "byte")) {
byte[] byt = CommonUtils.readAsBytes(response_.body);
return AccConverter.buildMap(
new AccPair("body", byt),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(bodyType, "string")) {
String str = CommonUtils.readAsString(response_.body);
return AccConverter.buildMap(
new AccPair("body", str),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(bodyType, "json")) {
Object obj = CommonUtils.readAsJSON(response_.body);
Map<String, Object> res = CommonUtils.assertAsMap(obj);
return AccConverter.buildMap(
new AccPair("body", res),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(bodyType, "array")) {
Object arr = CommonUtils.readAsJSON(response_.body);
return AccConverter.buildMap(
new AccPair("body", arr),
new AccPair("headers", response_.headers)
);
} else {
return AccConverter.buildMap(
new AccPair("headers", response_.headers)
);
}
} catch (Exception e) {
if (Acc.isRetryable(e)) {
_lastException = e;
continue;
}
throw e;
}
}
throw new AccUnretryableException(_lastRequest, _lastException);
}
public Map<String, ?> doRequest(Params params, OpenApiRequest request, RuntimeOptions runtime) throws Exception {
AccModel.validateParams(params, "params");
AccModel.validateParams(request, "request");
Map<String, Object> runtime_ = AccConverter.buildMap(
new AccPair("timeouted", "retry"),
new AccPair("readTimeout", CommonUtils.defaultNumber(runtime.readTimeout, _readTimeout)),
new AccPair("connectTimeout", CommonUtils.defaultNumber(runtime.connectTimeout, _connectTimeout)),
new AccPair("maxIdleConns", CommonUtils.defaultNumber(runtime.maxIdleConns, _maxIdleConns)),
new AccPair("retry", AccConverter.buildMap(
new AccPair("retryable", runtime.autoretry),
new AccPair("maxAttempts", CommonUtils.defaultNumber(runtime.maxAttempts, 3))
)),
new AccPair("ignoreSSL", runtime.ignoreSSL)
);
AccRequest _lastRequest = null;
Exception _lastException = null;
long _now = System.currentTimeMillis();
int _retryTimes = 0;
while (Acc.allowRetry((Map<String, Object>) runtime_.get("retry"), _retryTimes, _now)) {
if (_retryTimes > 0) {
int backoffTime = Acc.getBackoffTime(runtime_.get("backoff"), _retryTimes);
if (backoffTime > 0) {
Acc.sleep(backoffTime);
}
}
_retryTimes = _retryTimes + 1;
try {
AccRequest request_ = new AccRequest();
request_.protocol = CommonUtils.defaultString(_protocol, params.protocol);
request_.method = params.method;
request_.pathname = ClientUtil.getEncodePath(params.pathname);
request_.query = request.query;
// endpoint is setted in product client
request_.headers = AccConverter.merge(String.class,
AccConverter.buildMap(
new AccPair("host", _endpoint),
new AccPair("x-acc-version", params.version),
new AccPair("x-acc-action", params.action),
new AccPair("user-agent", this.getUserAgent()),
new AccPair("x-acc-date", ClientUtil.getTimestamp()),
new AccPair("x-acc-signature-nonce", CommonUtils.getNonce()),
new AccPair("accept", "application/json")
),
request.headers
);
String signatureAlgorithm = CommonUtils.defaultString(_signatureAlgorithm, "ACS3-HMAC-SHA256");
String hashedRequestPayload = null;
if (!CommonUtils.isUnset(request.body)) {
if (CommonUtils.equalString(params.reqBodyType, "json")) {
String jsonObj = CommonUtils.toJSONString(request.body);
hashedRequestPayload = ClientUtil.hexEncode(ClientUtil.hash(CommonUtils.toBytes(jsonObj), signatureAlgorithm));
request_.body = Acc.toReadable(jsonObj);
} else {
Map<String, Object> m = CommonUtils.assertAsMap(request.body);
String formObj = ClientUtil.toForm(m);
hashedRequestPayload = ClientUtil.hexEncode(ClientUtil.hash(CommonUtils.toBytes(formObj), signatureAlgorithm));
request_.body = Acc.toReadable(formObj);
request_.headers.put("content-type", "application/x-www-form-urlencoded");
}
}
if (!CommonUtils.isUnset(request.stream)) {
byte[] tmp = CommonUtils.readAsBytes(request.stream);
hashedRequestPayload = ClientUtil.hexEncode(ClientUtil.hash(tmp, signatureAlgorithm));
request_.body = Acc.toReadable(tmp);
}
if( hashedRequestPayload == null) {
hashedRequestPayload = ClientUtil.hexEncode(ClientUtil.hash(CommonUtils.toBytes(""), signatureAlgorithm));
}
request_.headers.put("x-acc-content-sha256", hashedRequestPayload);
if (!CommonUtils.equalString(params.authType, "Anonymous")) {
String accessKeyId = this.getAccessKeyId();
String accessKeySecret = this.getAccessKeySecret();
String securityToken = this.getSecurityToken();
if (!CommonUtils.empty(securityToken)) {
request_.headers.put("x-acc-security-token", securityToken);
}
request_.headers.put("Authorization", ClientUtil.getAuthorization(request_, signatureAlgorithm, hashedRequestPayload, accessKeyId, accessKeySecret));
}
_lastRequest = request_;
AccResponse response_ = Acc.doAction(request_, runtime_);
if (CommonUtils.is4xx(response_.statusCode) || CommonUtils.is5xx(response_.statusCode)) {
Object _res = CommonUtils.readAsJSON(response_.body);
Map<String, Object> err = CommonUtils.assertAsMap(_res);
throw new AccException(AccConverter.buildMap(
new AccPair("code", "" + Client.defaultAny(err.get("code"), err.get("statusCode")) + ""),
new AccPair("msg", "code: " + response_.statusCode + ", " + Client.defaultAny(err.get("msg"), err.get("message")) + " request id: " + Client.defaultAny(err.get("RequestId"), err.get("requestId")) + ""),
new AccPair("data", err)
));
}
if (CommonUtils.equalString(params.bodyType, "binary")) {
Map<String, Object> resp = AccConverter.buildMap(
new AccPair("body", response_.body),
new AccPair("headers", response_.headers)
);
return resp;
} else if (CommonUtils.equalString(params.bodyType, "byte")) {
byte[] byt = CommonUtils.readAsBytes(response_.body);
return AccConverter.buildMap(
new AccPair("body", byt),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(params.bodyType, "string")) {
String str = CommonUtils.readAsString(response_.body);
return AccConverter.buildMap(
new AccPair("body", str),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(params.bodyType, "json")) {
Object obj = CommonUtils.readAsJSON(response_.body);
Map<String, Object> res = CommonUtils.assertAsMap(obj);
return AccConverter.buildMap(
new AccPair("body", res),
new AccPair("headers", response_.headers)
);
} else if (CommonUtils.equalString(params.bodyType, "array")) {
Object arr = CommonUtils.readAsJSON(response_.body);
return AccConverter.buildMap(
new AccPair("body", arr),
new AccPair("headers", response_.headers)
);
} else {
return AccConverter.buildMap(
new AccPair("headers", response_.headers)
);
}
} catch (Exception e) {
if (Acc.isRetryable(e)) {
_lastException = e;
continue;
}
throw e;
}
}
throw new AccUnretryableException(_lastRequest, _lastException);
}
public Map<String, ?> callApi(Params params, OpenApiRequest request, RuntimeOptions runtime) throws Exception {
if (CommonUtils.isUnset(AccModel.buildMap(params))) {
throw new AccException(AccConverter.buildMap(
new AccPair("code", "ParameterMissing"),
new AccPair("msg", "'params' can not be unset")
));
}
if (CommonUtils.isUnset(_signatureAlgorithm) || !CommonUtils.equalString(_signatureAlgorithm, "v2")) {
return this.doRequest(params, request, runtime);
} else if (CommonUtils.equalString(params.style, "ROA") && CommonUtils.equalString(params.reqBodyType, "json")) {
return this.doROARequest(params.action, params.version, params.protocol, params.method, params.authType, params.pathname, params.bodyType, request, runtime);
} else if (CommonUtils.equalString(params.style, "ROA")) {
return this.doROARequestWithForm(params.action, params.version, params.protocol, params.method, params.authType, params.pathname, params.bodyType, request, runtime);
} else {
return this.doRPCRequest(params.action, params.version, params.protocol, params.method, params.authType, params.bodyType, request, runtime);
}
}
/**
* Get user agent
* @return user agent
*/
public String getUserAgent() throws Exception {
String userAgent = CommonUtils.getUserAgent(_userAgent);
return userAgent;
}
/**
* Get accesskey id by using credential
* @return accesskey id
*/
public String getAccessKeyId() throws Exception {
return this._accessKeyId;
}
/**
* Get accesskey secret by using credential
* @return accesskey secret
*/
public String getAccessKeySecret() throws Exception {
return this._accessKeySecret;
}
/**
* Get security token by using credential
* @return security token
*/
public String getSecurityToken() throws Exception {
return this._securityToken;
}
/**
* If inputValue is not null, return it or return defaultValue
* @param inputValue users input value
* @param defaultValue default value
* @return the final result
*/
public static Object defaultAny(Object inputValue, Object defaultValue) throws Exception {
if (CommonUtils.isUnset(inputValue)) {
return defaultValue;
}
return inputValue;
}
/**
* If the endpointRule and config.endpoint are empty, throw error
* @param config config contains the necessary information to create a client
*/
public void checkConfig(Config config) throws Exception {
if (CommonUtils.empty(_endpointRule) && CommonUtils.empty(config.endpoint)) {
throw new AccException(AccConverter.buildMap(
new AccPair("code", "ParameterMissing"),
new AccPair("message", "'config.endpoint' can not be empty")
));
}
}
/**
* set RPC header for debug
* @param headers headers for debug, this header can be used only once.
*/
public void setRpcHeaders(Map<String, String> headers) throws Exception {
this._headers = headers;
}
/**
* get RPC header for debug
*/
public Map<String, String> getRpcHeaders() throws Exception {
Map<String, String> headers = _headers;
this._headers = null;
return headers;
}
}
package com.dsk.acc.openapi.client;
import com.dsk.acc.openapi.client.core.AccModel;
public class Config extends AccModel {
// accesskey id
@AccJsonField("accessKeyId")
public String accessKeyId;
// accesskey secret
@AccJsonField("accessKeySecret")
public String accessKeySecret;
// security token
@AccJsonField("securityToken")
public String securityToken;
// http protocol
@AccJsonField("protocol")
public String protocol;
// region id
@AccJsonField("regionId")
public String regionId;
// read timeout
@AccJsonField("readTimeout")
public Integer readTimeout;
// connect timeout
@AccJsonField("connectTimeout")
public Integer connectTimeout;
// endpoint
@AccJsonField("endpoint")
public String endpoint;
// max idle conns
@AccJsonField("maxIdleConns")
public Integer maxIdleConns;
// network for endpoint
@AccJsonField("network")
public String network;
// user agent
@AccJsonField("userAgent")
public String userAgent;
// Signature Algorithm
@AccJsonField("signatureAlgorithm")
public String signatureAlgorithm;
// credential
@AccJsonField("credential")
public Client credential;
public static Config build(java.util.Map<String, ?> map) throws Exception {
Config self = new Config();
return AccModel.build(map, self);
}
public Config() {
super();
}
public Config(String accessKeyId, String accessKeySecret) {
super();
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return accessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
this.accessKeySecret = accessKeySecret;
}
public String getSecurityToken() {
return securityToken;
}
public void setSecurityToken(String securityToken) {
this.securityToken = securityToken;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getRegionId() {
return regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public Integer getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(Integer readTimeout) {
this.readTimeout = readTimeout;
}
public Integer getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(Integer connectTimeout) {
this.connectTimeout = connectTimeout;
}
public String getEndpoint() {
return endpoint;
}
public Config setEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public Integer getMaxIdleConns() {
return maxIdleConns;
}
public void setMaxIdleConns(Integer maxIdleConns) {
this.maxIdleConns = maxIdleConns;
}
public String getNetwork() {
return network;
}
public void setNetwork(String network) {
this.network = network;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public String getSignatureAlgorithm() {
return signatureAlgorithm;
}
public void setSignatureAlgorithm(String signatureAlgorithm) {
this.signatureAlgorithm = signatureAlgorithm;
}
public Config setCredential(Client credential) {
this.credential = credential;
return this;
}
public Client getCredential() {
return this.credential;
}
}
package com.dsk.acc.openapi.client.bean;
import com.dsk.acc.openapi.client.AccJsonField;
import com.dsk.acc.openapi.client.core.AccModel;
public class OpenApiRequest extends AccModel {
@AccJsonField("headers")
public java.util.Map<String, String> headers;
@AccJsonField("query")
public java.util.Map<String, String> query;
@AccJsonField("body")
public Object body;
@AccJsonField("stream")
public java.io.InputStream stream;
public static OpenApiRequest build(java.util.Map<String, ?> map) throws Exception {
OpenApiRequest self = new OpenApiRequest();
return AccModel.build(map, self);
}
public OpenApiRequest setHeaders(java.util.Map<String, String> headers) {
this.headers = headers;
return this;
}
public java.util.Map<String, String> getHeaders() {
return this.headers;
}
public OpenApiRequest setQuery(java.util.Map<String, String> query) {
this.query = query;
return this;
}
public java.util.Map<String, String> getQuery() {
return this.query;
}
public OpenApiRequest setBody(Object body) {
this.body = body;
return this;
}
public Object getBody() {
return this.body;
}
public OpenApiRequest setStream(java.io.InputStream stream) {
this.stream = stream;
return this;
}
public java.io.InputStream getStream() {
return this.stream;
}
}
package com.dsk.acc.openapi.client.bean;
import com.dsk.acc.openapi.client.AccJsonField;
import com.dsk.acc.openapi.client.AccValid;
import com.dsk.acc.openapi.client.core.AccModel;
public class Params extends AccModel {
@AccJsonField("action")
@AccValid(required = true)
public String action;
@AccJsonField("version")
@AccValid(required = true)
public String version;
@AccJsonField("protocol")
@AccValid(required = true)
public String protocol;
@AccJsonField("pathname")
@AccValid(required = true)
public String pathname;
@AccJsonField("method")
@AccValid(required = true)
public String method;
@AccJsonField("authType")
@AccValid(required = true)
public String authType;
@AccJsonField("bodyType")
@AccValid(required = true)
public String bodyType;
@AccJsonField("reqBodyType")
@AccValid(required = true)
public String reqBodyType;
@AccJsonField("style")
public String style;
public static Params build(java.util.Map<String, ?> map) throws Exception {
Params self = new Params();
return AccModel.build(map, self);
}
public Params setAction(String action) {
this.action = action;
return this;
}
public String getAction() {
return this.action;
}
public Params setVersion(String version) {
this.version = version;
return this;
}
public String getVersion() {
return this.version;
}
public Params setProtocol(String protocol) {
this.protocol = protocol;
return this;
}
public String getProtocol() {
return this.protocol;
}
public Params setPathname(String pathname) {
this.pathname = pathname;
return this;
}
public String getPathname() {
return this.pathname;
}
public Params setMethod(String method) {
this.method = method;
return this;
}
public String getMethod() {
return this.method;
}
public Params setAuthType(String authType) {
this.authType = authType;
return this;
}
public String getAuthType() {
return this.authType;
}
public Params setBodyType(String bodyType) {
this.bodyType = bodyType;
return this;
}
public String getBodyType() {
return this.bodyType;
}
public Params setReqBodyType(String reqBodyType) {
this.reqBodyType = reqBodyType;
return this;
}
public String getReqBodyType() {
return this.reqBodyType;
}
public Params setStyle(String style) {
this.style = style;
return this;
}
public String getStyle() {
return this.style;
}
}
package com.dsk.acc.openapi.client.bean;
import com.dsk.acc.openapi.client.AccJsonField;
import com.dsk.acc.openapi.client.core.AccModel;
public class RuntimeOptions extends AccModel {
@AccJsonField("autoretry")
public Boolean autoretry = false;
@AccJsonField("ignoreSSL")
public Boolean ignoreSSL = true;
@AccJsonField("max_attempts")
public Integer maxAttempts;
@AccJsonField("readTimeout")
public Integer readTimeout;
@AccJsonField("connectTimeout")
public Integer connectTimeout;
@AccJsonField("maxIdleConns")
public Integer maxIdleConns;
public static RuntimeOptions build(java.util.Map<String, ?> map) throws Exception {
RuntimeOptions self = new RuntimeOptions();
return AccModel.build(map, self);
}
}
package com.dsk.acc.openapi.client.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import com.dsk.acc.openapi.client.exception.AccException;
import com.dsk.acc.openapi.client.exception.AccRetryableException;
import com.dsk.acc.openapi.client.util.StringUtils;
import com.dsk.acc.openapi.client.util.okhttp.ClientHelper;
import com.dsk.acc.openapi.client.util.okhttp.OkRequestBuilder;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class Acc {
private static String composeUrl(AccRequest request) {
Map<String, String> queries = request.query;
String host = request.headers.get("host");
String protocol = null == request.protocol ? "http" : request.protocol;
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(protocol);
urlBuilder.append("://").append(host);
if (null != request.pathname) {
urlBuilder.append(request.pathname);
}
if (queries != null && queries.size() > 0) {
if (urlBuilder.indexOf("?") >= 1) {
urlBuilder.append("&");
} else {
urlBuilder.append("?");
}
try {
for (Map.Entry<String, String> entry : queries.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
if (val == null || "null".equals(val)) {
continue;
}
urlBuilder.append(URLEncoder.encode(key, "UTF-8"));
urlBuilder.append("=");
urlBuilder.append(URLEncoder.encode(val, "UTF-8"));
urlBuilder.append("&");
}
} catch (Exception e) {
throw new AccException(e.getMessage(), e);
}
int strIndex = urlBuilder.length();
urlBuilder.deleteCharAt(strIndex - 1);
}
return urlBuilder.toString();
}
public static AccResponse doAction(AccRequest request) {
return doAction(request, new HashMap<String, Object>());
}
public static AccResponse doAction(AccRequest request, Map<String, Object> runtimeOptions) {
try {
String urlString = Acc.composeUrl(request);
URL url = new URL(urlString);
OkHttpClient okHttpClient = ClientHelper.getOkHttpClient(url.getHost(), url.getPort(), runtimeOptions);
Request.Builder requestBuilder = new Request.Builder();
OkRequestBuilder okRequestBuilder = new OkRequestBuilder(requestBuilder).url(url).header(request.headers);
Response response = okHttpClient.newCall(okRequestBuilder.buildRequest(request)).execute();
return new AccResponse(response);
} catch (Exception e) {
throw new AccRetryableException(e);
}
}
private static Map<String, String> setProxyAuthorization(Map<String, String> header, Object httpsProxy) {
try {
if (!StringUtils.isEmpty(httpsProxy)) {
URL proxyUrl = new URL(String.valueOf(httpsProxy));
String userInfo = proxyUrl.getUserInfo();
if (null != userInfo) {
String[] userMessage = userInfo.split(":");
String credential = Credentials.basic(userMessage[0], userMessage[1]);
header.put("Proxy-Authorization", credential);
}
}
return header;
} catch (Exception e) {
throw new AccException(e.getMessage(), e);
}
}
public static boolean allowRetry(Map<String, ?> map, int retryTimes, long now) {
if (0 == retryTimes) {
return true;
}
if (map == null) {
return false;
}
Object shouldRetry = map.get("retryable");
if (shouldRetry instanceof Boolean && (boolean) shouldRetry) {
int retry = map.get("maxAttempts") == null ? 0 : Integer.parseInt(String.valueOf(map.get("maxAttempts")));
return retry >= retryTimes;
}
return false;
}
public static int getBackoffTime(Object o, int retryTimes) {
int backOffTime = 0;
Map<String, Object> map = (Map<String, Object>) o;
if (StringUtils.isEmpty(map.get("policy")) || "no".equals(map.get("policy"))) {
return backOffTime;
}
if (!StringUtils.isEmpty(map.get("period")) &&
(backOffTime = Integer.valueOf(String.valueOf(map.get("period")))) <= 0) {
return retryTimes;
}
return backOffTime;
}
public static void sleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
throw new AccException(e.getMessage(), e);
}
}
public static boolean isRetryable(Exception e) {
return e instanceof AccRetryableException;
}
public static InputStream toReadable(String string) {
try {
return toReadable(string.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new AccException(e.getMessage(), e);
}
}
public static InputStream toReadable(byte[] byteArray) {
return new ByteArrayInputStream(byteArray);
}
public static OutputStream toWriteable(int size) {
try {
return new ByteArrayOutputStream(size);
} catch (IllegalArgumentException e) {
throw new AccException(e.getMessage(), e);
}
}
public static OutputStream toWriteable() {
return new ByteArrayOutputStream();
}
}
package com.dsk.acc.openapi.client.core;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class AccConverter {
@SuppressWarnings("unchecked")
public static <T> Map<String, T> buildMap(AccPair... pairs) {
Map<String, T> map = new HashMap<String, T>();
for (int i = 0; i < pairs.length; i++) {
AccPair pair = pairs[i];
map.put(pair.key, (T) pair.value);
}
return map;
}
@SuppressWarnings("unchecked")
public static <T> Map<String, T> merge(Class<T> t, Map<String, ?>... maps) {
Map<String, T> out = new HashMap<String, T>();
for (int i = 0; i < maps.length; i++) {
Map<String, ?> map = maps[i];
if (null == map) {
continue;
}
Set<? extends Entry<String, ?>> entries = map.entrySet();
for (Entry<String, ?> entry : entries) {
if (null != entry.getValue()) {
out.put(entry.getKey(), (T) entry.getValue());
}
}
}
return out;
}
@SuppressWarnings("unchecked")
public static <T> Map<String, T> merge(Class<T> t, Object... maps) {
Map<String, T> out = new HashMap<String, T>();
Map<String, ?> map = null;
for (int i = 0; i < maps.length; i++) {
if (null == maps[i]) {
continue;
}
if (AccModel.class.isAssignableFrom(maps[i].getClass())) {
map = AccModel.buildMap((AccModel) maps[i]);
} else {
map = (Map<String, T>) maps[i];
}
Set<? extends Entry<String, ?>> entries = map.entrySet();
for (Entry<String, ?> entry : entries) {
if (null != entry.getValue()) {
out.put(entry.getKey(), (T) entry.getValue());
}
}
}
return out;
}
}
package com.dsk.acc.openapi.client.core;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import com.dsk.acc.openapi.client.AccJsonField;
import com.dsk.acc.openapi.client.AccValid;
import com.dsk.acc.openapi.client.exception.AccException;
import com.dsk.acc.openapi.client.exception.AccValidException;
public class AccModel {
public Map<String, Object> toMap() {
return changeToMap(this, true);
}
public static Map<String, Object> toMap(Object object) {
return toMap(object, true);
}
private static Map<String, Object> toMap(Object object, Boolean exceptStream) {
Map<String, Object> map = new HashMap<String, Object>();
if (null != object && object instanceof Map) {
return (Map<String, Object>) object;
}
if (null == object || !AccModel.class.isAssignableFrom(object.getClass())) {
return map;
}
map = changeToMap(object, exceptStream);
return map;
}
private Map<String, Object> toMap(Boolean exceptStream) {
return changeToMap(this, exceptStream);
}
private static Map<String, Object> changeToMap(Object object, Boolean exceptStream) {
HashMap<String, Object> map = new HashMap<String, Object>();
try {
for (Field field : object.getClass().getFields()) {
AccJsonField anno = field.getAnnotation(AccJsonField.class);
String key;
if (anno == null) {
key = field.getName();
} else {
key = anno.value();
}
if (null != field.get(object) && List.class.isAssignableFrom(field.get(object).getClass())) {
List<Object> arrayField = (List<Object>) field.get(object);
List<Object> fieldList = new ArrayList<Object>();
for (int i = 0; i < arrayField.size(); i++) {
fieldList.add(parseObject(arrayField.get(i)));
}
map.put(key, fieldList);
} else if (null != field.get(object) && AccModel.class.isAssignableFrom(field.get(object).getClass())) {
map.put(key, AccModel.toMap(field.get(object), exceptStream));
} else if (null != field.get(object) && Map.class.isAssignableFrom(field.get(object).getClass())) {
Map<String, Object> valueMap = (Map<String, Object>) field.get(object);
Map<String, Object> result = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : valueMap.entrySet()) {
result.put(entry.getKey(), parseObject(entry.getValue()));
}
map.put(key, result);
} else if (exceptStream && null != field.get(object) && InputStream.class.isAssignableFrom(field.get(object).getClass())) {
continue;
} else if (exceptStream && null != field.get(object) && OutputStream.class.isAssignableFrom(field.get(object).getClass())) {
continue;
} else {
map.put(key, field.get(object));
}
}
} catch (Exception e) {
throw new AccException(e.getMessage(), e);
}
return map;
}
public static Object parseObject(Object o) {
if (null == o) {
return o;
}
Class clazz = o.getClass();
if (List.class.isAssignableFrom(clazz)) {
List<Object> list = (List<Object>) o;
List<Object> result = new ArrayList<Object>();
for (Object object : list) {
result.add(parseObject(object));
}
return result;
} else if (Map.class.isAssignableFrom(clazz)) {
Map<String, Object> map = (Map<String, Object>) o;
Map<String, Object> result = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
result.put(entry.getKey(), parseObject(entry.getValue()));
}
return result;
} else if (AccModel.class.isAssignableFrom(clazz)) {
return ((AccModel) o).toMap(false);
} else {
return o;
}
}
private static Object buildObject(Object o, Class self, Type subType) {
Class valueClass = o.getClass();
if (Map.class.isAssignableFrom(self) && Map.class.isAssignableFrom(valueClass)) {
Map<String, Object> valueMap = (Map<String, Object>) o;
Map<String, Object> result = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : valueMap.entrySet()) {
if (null == subType || subType instanceof WildcardType) {
result.put(entry.getKey(), entry.getValue());
} else if (subType instanceof Class) {
result.put(entry.getKey(), buildObject(entry.getValue(), (Class) subType, null));
} else {
ParameterizedType parameterizedType = (ParameterizedType) subType;
Type[] types = parameterizedType.getActualTypeArguments();
result.put(entry.getKey(), buildObject(entry.getValue(), (Class) parameterizedType.getRawType(), types[types.length - 1]));
}
}
return result;
} else if (List.class.isAssignableFrom(self) && List.class.isAssignableFrom(valueClass)) {
List<Object> valueList = (List<Object>) o;
List<Object> result = new ArrayList<Object>();
for (Object object : valueList) {
if (null == subType || subType instanceof WildcardType) {
result.add(object);
} else if (subType instanceof Class) {
result.add(buildObject(object, (Class) subType, null));
} else {
ParameterizedType parameterizedType = (ParameterizedType) subType;
Type[] types = parameterizedType.getActualTypeArguments();
result.add(buildObject(object, (Class) parameterizedType.getRawType(), types[types.length - 1]));
}
}
return result;
} else if (AccModel.class.isAssignableFrom(self) && Map.class.isAssignableFrom(valueClass)) {
try {
return AccModel.toModel((Map<String, Object>) o, (AccModel) self.newInstance());
} catch (Exception e) {
throw new AccException(e.getMessage(), e);
}
} else {
return o;
}
}
private static Type getType(Field field, int index) {
ParameterizedType genericType = (ParameterizedType) field.getGenericType();
Type[] actualTypeArguments = genericType.getActualTypeArguments();
Type actualTypeArgument = actualTypeArguments[index];
return actualTypeArgument;
}
@SuppressWarnings("unchecked")
public static <T extends AccModel> T toModel(Map<String, ?> map, T model) {
T result = model;
for (Field field : result.getClass().getFields()) {
AccJsonField anno = field.getAnnotation(AccJsonField.class);
String key;
if (anno == null) {
key = field.getName();
} else {
key = anno.value();
}
Object value = map.get(key);
if (value == null) {
continue;
}
result = setAccModelField(result, field, value, false);
}
return result;
}
@SuppressWarnings("unchecked")
private static <T extends AccModel> T setAccModelField(T model, Field field, Object value, boolean userBuild) {
try {
Class<?> clazz = field.getType();
Object resultValue = parseNumber(value, clazz);
T result = model;
if (AccModel.class.isAssignableFrom(clazz)) {
Object data = clazz.getDeclaredConstructor().newInstance();
if (userBuild) {
field.set(result, AccModel.build(AccModel.toMap(resultValue, false), (AccModel) data));
} else if (!userBuild && Map.class.isAssignableFrom(resultValue.getClass())) {
field.set(result, AccModel.toModel((Map<String, Object>) resultValue, (AccModel) data));
} else {
field.set(result, resultValue);
}
} else if (Map.class.isAssignableFrom(clazz)) {
field.set(result, buildObject(resultValue, Map.class, getType(field, 1)));
} else if (List.class.isAssignableFrom(clazz)) {
field.set(result, buildObject(resultValue, List.class, getType(field, 0)));
} else {
field.set(result, confirmType(clazz, resultValue));
}
return result;
} catch (Exception e) {
throw new AccException(e.getMessage(), e);
}
}
@SuppressWarnings("unchecked")
public static <T extends AccModel> T build(Map<String, ?> map, T model) {
T result = model;
for (Field field : model.getClass().getFields()) {
String key = field.getName();
Object value = map.get(key);
if (value == null) {
AccJsonField anno = field.getAnnotation(AccJsonField.class);
if (null == anno) {
continue;
}
key = anno.value();
value = map.get(key);
if (null == value) {
continue;
}
}
result = setAccModelField(result, field, value, true);
}
return result;
}
private static Object parseNumber(Object value, Class clazz) {
BigDecimal bigDecimal;
if (value instanceof Double && (clazz == Long.class || clazz == long.class)) {
bigDecimal = new BigDecimal(value.toString());
return bigDecimal.longValue();
}
if (value instanceof Double && (clazz == Integer.class || clazz == int.class)) {
bigDecimal = new BigDecimal(value.toString());
return bigDecimal.intValue();
}
if (value instanceof Double && (clazz == Float.class || clazz == float.class)) {
bigDecimal = new BigDecimal(value.toString());
return bigDecimal.floatValue();
}
return value;
}
public void validate() {
Field[] fields = this.getClass().getFields();
Object object;
AccValid validation;
String pattern;
int maxLength;
int minLength;
double maximum;
double minimum;
boolean required;
try {
for (int i = 0; i < fields.length; i++) {
object = fields[i].get(this);
validation = fields[i].getAnnotation(AccValid.class);
if (null != validation) {
required = validation.required();
} else {
required = false;
}
if (required && null == object) {
throw new AccValidException("Field " + fields[i].getName() + " is required");
}
if (null != validation && null != object) {
pattern = validation.pattern();
maxLength = validation.maxLength();
minLength = validation.minLength();
maximum = validation.maximum();
minimum = validation.minimum();
if (!"".equals(pattern) || maxLength > 0 || minLength > 0 || maximum != Double.MAX_VALUE || minimum != Double.MIN_VALUE) {
determineType(fields[i].getType(), object, pattern, maxLength, minLength, maximum, minimum, fields[i].getName());
}
}
}
} catch (Exception e) {
throw new AccValidException(e.getMessage(), e);
}
}
private void determineType(Class clazz, Object object, String pattern, int maxLength, int minLength, double maximum, double minimum, String fieldName) {
if (Map.class.isAssignableFrom(clazz)) {
validateMap(pattern, maxLength, minLength, maximum, minimum, (Map<String, Object>) object, fieldName);
} else if (AccModel.class.isAssignableFrom(clazz)) {
((AccModel) object).validate();
} else if (List.class.isAssignableFrom(clazz)) {
List<?> list = (List<?>) object;
for (int j = 0; j < list.size(); j++) {
determineType(list.get(j).getClass(), list.get(j), pattern, maxLength, minLength, maximum, minimum, fieldName);
}
} else if (clazz.isArray()) {
Object[] objects = (Object[]) object;
for (int j = 0; j < objects.length; j++) {
determineType(clazz.getComponentType(), objects[j], pattern, maxLength, minLength, maximum, minimum, fieldName);
}
} else if (Number.class.isAssignableFrom(clazz)) {
double value = Double.valueOf(object.toString());
if (value > maximum) {
throw new AccValidException(this.getClass().getName() + "." + fieldName + " exceeds the maximum");
}
if (value < minimum) {
throw new AccValidException(this.getClass().getName() + "." + fieldName + " less than minimum");
}
} else {
String value = String.valueOf(object);
if (maxLength > 0 && value.length() > maxLength) {
throw new AccValidException(this.getClass().getName() + "." + fieldName + " exceeds the maximum length");
}
if (minLength > 0 && value.length() < minLength) {
throw new AccValidException(this.getClass().getName() + "." + fieldName + " less than minimum length");
}
if (!"".equals(pattern) && !Pattern.matches(pattern, value)) {
throw new AccValidException(this.getClass().getName() + "." + fieldName + " regular match failed");
}
}
}
private void validateMap(String pattern, int maxLength, int minLength, double maximum, double minimum, Map<String, Object> map, String fieldName) {
for (Map.Entry entry : map.entrySet()) {
if (entry.getValue() != null) {
determineType(entry.getValue().getClass(), entry.getValue(), pattern, maxLength, minLength, maximum, minimum, fieldName);
}
}
}
public static Map<String, Object> buildMap(AccModel AccModel) {
if (null == AccModel) {
return null;
} else {
return AccModel.toMap();
}
}
public static void validateParams(AccModel AccModel, String paramName) {
if (null == AccModel) {
throw new AccValidException("parameter " + paramName + " is not allowed as null");
}
AccModel.validate();
}
public static Object confirmType(Class expect, Object object) throws Exception {
if (String.class.isAssignableFrom(expect)) {
if (object instanceof Number || object instanceof Boolean) {
return object.toString();
}
} else if (Boolean.class.isAssignableFrom(expect)) {
if (object instanceof String) {
return Boolean.parseBoolean(String.valueOf(object));
} else if (object instanceof Integer) {
if (object.toString().equals("1")) {
return true;
} else if (object.toString().equals("0")) {
return false;
}
}
} else if (Integer.class.isAssignableFrom(expect)) {
if (object instanceof String) {
return Integer.parseInt(object.toString());
}
// 判断数值大小是否超过期望数据类型的上限,如果不超过则强制转换,如果超过则报错
if (object instanceof Long && ((Long) object).longValue() <= Integer.MAX_VALUE) {
return Integer.parseInt(object.toString());
}
} else if (Long.class.isAssignableFrom(expect)) {
if (object instanceof String || object instanceof Integer) {
return Long.parseLong(object.toString());
}
} else if (Float.class.isAssignableFrom(expect)) {
if (object instanceof String || object instanceof Integer || object instanceof Long) {
return Float.parseFloat(object.toString());
}
// 判断数值大小是否超过期望数据类型的上限,如果不超过则强制转换,如果超过则报错
if (object instanceof Double && ((Double) object).doubleValue() <= Float.MAX_VALUE) {
return Float.parseFloat(object.toString());
}
} else if (Double.class.isAssignableFrom(expect)) {
if (object instanceof String || object instanceof Integer || object instanceof Long || object instanceof Float) {
return Double.parseDouble(object.toString());
}
}
return object;
}
}
package com.dsk.acc.openapi.client.core;
public class AccPair {
public String key;
public Object value;
public AccPair(String key, Object value) {
this.key = key;
this.value = value;
}
}
\ No newline at end of file
package com.dsk.acc.openapi.client.core;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class AccRequest {
public final static String URL_ENCODING = "UTF-8";
public String protocol;
public Integer port;
public String method;
public String pathname;
public Map<String, String> query;
public Map<String, String> headers;
public InputStream body;
public AccRequest() {
protocol = "http";
method = "GET";
query = new HashMap<String, String>();
headers = new HashMap<String, String>();
}
public static AccRequest create() {
return new AccRequest();
}
@Override
public String toString() {
String output = "Protocol: " + this.protocol + "\nPort: " + this.port + "\n" + this.method + " " + this.pathname
+ "\n";
output += "Query:\n";
for (Entry<String, String> e : this.query.entrySet()) {
output += " " + e.getKey() + ": " + e.getValue() + "\n";
}
output += "Headers:\n";
for (Entry<String, String> e : this.headers.entrySet()) {
output += " " + e.getKey() + ": " + e.getValue() + "\n";
}
return output;
}
}
\ No newline at end of file
package com.dsk.acc.openapi.client.core;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.dsk.acc.openapi.client.exception.AccException;
import com.dsk.acc.openapi.client.util.StringUtils;
import okhttp3.Headers;
import okhttp3.Response;
public class AccResponse {
public Response response;
public int statusCode;
public String statusMessage;
public HashMap<String, String> headers;
public InputStream body;
public AccResponse() {
headers = new HashMap<String, String>();
}
public AccResponse(Response response) {
headers = new HashMap<String, String>();
this.response = response;
statusCode = response.code();
statusMessage = response.message();
body = response.body().byteStream();
Headers headers = response.headers();
Map<String, List<String>> resultHeaders = headers.toMultimap();
for (Map.Entry<String, List<String>> entry : resultHeaders.entrySet()) {
this.headers.put(entry.getKey(), StringUtils.join(";", entry.getValue()));
}
}
public InputStream getResponse() {
return this.body;
}
public String getResponseBody() {
if (null == body) {
return String.format("{\"message\":\"%s\"}", statusMessage);
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buff = new byte[4096];
try {
while (true) {
final int read = body.read(buff);
if (read == -1) {
break;
}
os.write(buff, 0, read);
}
} catch (Exception e) {
throw new AccException(e.getMessage(), e);
}
return new String(os.toByteArray());
}
}
package com.dsk.acc.openapi.client.exception;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class AccException extends RuntimeException {
private static final long serialVersionUID = 1L;
public String code;
public String message;
public Map<String, Object> data;
public AccException() {
}
public AccException(String message, Throwable cause) {
super(message, cause);
}
public AccException(Map<String, ?> map) {
this.setCode(String.valueOf(map.get("code")));
this.setMessage(String.valueOf(map.get("msg")));
Object obj = map.get("data");
if (obj == null) {
return;
}
if (obj instanceof Map) {
data = (Map<String, Object>) obj;
return;
}
Map<String, Object> hashMap = new HashMap<String, Object>();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
try {
hashMap.put(field.getName(), field.get(obj));
} catch (Exception e) {
continue;
}
}
this.data = hashMap;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
}
\ No newline at end of file
package com.dsk.acc.openapi.client.exception;
import java.util.Map;
public class AccRetryableException extends AccException {
private static final long serialVersionUID = 3883312421128465122L;
public AccRetryableException(Throwable cause) {
super("", cause);
message = cause.getMessage();
}
public AccRetryableException(Map<String, ?> map) {
super(map);
}
public AccRetryableException() {
}
}
\ No newline at end of file
package com.dsk.acc.openapi.client.exception;
import com.dsk.acc.openapi.client.core.AccRequest;
public class AccUnretryableException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -7006694712718176751L;
private AccRequest lastRequest = null;
public AccRequest getLastRequest() {
return lastRequest;
}
public AccUnretryableException(AccRequest lastRequest, Throwable lastException) {
super(lastException.getMessage(), lastException);
this.lastRequest = lastRequest;
}
public AccUnretryableException(AccRequest lastRequest) {
this.lastRequest = lastRequest;
}
public AccUnretryableException(Throwable lastException) {
super(lastException);
}
public AccUnretryableException() {
super();
}
}
package com.dsk.acc.openapi.client.exception;
public class AccValidException extends RuntimeException {
public AccValidException(String message) {
super(message);
}
public AccValidException(String message, Exception e) {
super(message, e);
}
}
package com.dsk.acc.openapi.client.util;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SimpleTimeZone;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.dsk.acc.openapi.client.core.AccModel;
import com.dsk.acc.openapi.client.core.AccRequest;
import com.google.gson.Gson;
import sun.misc.BASE64Encoder;
public class ClientUtil {
public final static String SEPARATOR = "&";
public final static String URL_ENCODING = "UTF-8";
public static final String ALGORITHM_NAME = "HmacSHA1";
public static final String HASH_SHA256 = "SHA-256";
public static final String HASH_SM3 = "SM3";
public static final String HMAC_SHA256 = "ACS3-HMAC-SHA256";
public static final String RSA_SHA256 = "ACS3-RSA-SHA256";
public static final String HMAC_SM3 = "ACS3-HMAC-SM3";
public static final String UTF8 = "UTF-8";
public static final String PEM_BEGIN = "-----BEGIN RSA PRIVATE KEY-----\n";
public static final String PEM_END = "\n-----END RSA PRIVATE KEY-----";
/**
* Convert all params of body other than type of readable into content
*
* @param body body Model
* @param content content Model
* @return void
*/
public static void convert(AccModel body, AccModel content) throws Exception {
if (body == null || content == null) {
return;
}
Class bodyClass = body.getClass();
Class contentClass = content.getClass();
Field[] fields = bodyClass.getDeclaredFields();
AccModel AccModel = (AccModel) bodyClass.newInstance();
for (Field field : fields) {
field.setAccessible(true);
if (InputStream.class.isAssignableFrom(field.getType())) {
continue;
}
field.set(AccModel, field.get(body));
}
Gson gson = new Gson();
String jsonString = gson.toJson(AccModel);
Object outPut = gson.fromJson(jsonString, contentClass);
fields = outPut.getClass().getFields();
for (Field field : fields) {
field.setAccessible(true);
field.set(content, field.get(outPut));
}
}
/**
* Get the string to be signed according to request
*
* @param request which contains signed messages
* @return the signed string
*/
public static String getStringToSign(AccRequest request) throws Exception {
if (request == null) {
return "";
}
String method = request.method;
String pathname = request.pathname;
Map<String, String> headers = request.headers;
Map<String, String> query = request.query;
String accept = headers.get("accept") == null ? "" : headers.get("accept");
String contentMD5 = headers.get("content-md5") == null ? "" : headers.get("content-md5");
String contentType = headers.get("content-type") == null ? "" : headers.get("content-type");
String date = headers.get("date") == null ? "" : headers.get("date");
String header = method + "\n" + accept + "\n" + contentMD5 + "\n" + contentType + "\n" + date + "\n";
String canonicalizedHeaders = getCanonicalizedHeaders(headers);
String canonicalizedResource = getCanonicalizedResource(pathname, query);
String stringToSign = header + canonicalizedHeaders + canonicalizedResource;
return stringToSign;
}
protected static String getCanonicalizedHeaders(Map<String, String> headers) {
if (headers == null) {
return "";
}
String prefix = "x-acc-";
Set<String> keys = headers.keySet();
List<String> canonicalizedKeys = new ArrayList<>();
for (String key : keys) {
if (key.startsWith(prefix)) {
canonicalizedKeys.add(key);
}
}
String[] canonicalizedKeysArray = canonicalizedKeys.toArray(new String[canonicalizedKeys.size()]);
Arrays.sort(canonicalizedKeysArray);
StringBuilder result = new StringBuilder();
for (int i = 0; i < canonicalizedKeysArray.length; i++) {
String key = canonicalizedKeysArray[i];
result.append(key);
result.append(":");
result.append(headers.get(key).trim());
result.append("\n");
}
return result.toString();
}
protected static Map<String, String> getCanonicalizedHeadersMap(Map<String, String> headers) {
Map<String, String> result = new HashMap<>();
if (headers == null) {
return result;
}
String prefix = "x-acc-";
Set<String> keys = headers.keySet();
List<String> canonicalizedKeys = new ArrayList<>();
Map<String, String> valueMap = new HashMap<>();
for (String key : keys) {
String lowerKey = key.toLowerCase();
if (lowerKey.startsWith(prefix) || lowerKey.equals("host") || lowerKey.equals("content-type")) {
if (!canonicalizedKeys.contains(lowerKey)) {
canonicalizedKeys.add(lowerKey);
}
valueMap.put(lowerKey, headers.get(key).trim());
}
}
String[] canonicalizedKeysArray = canonicalizedKeys.toArray(new String[canonicalizedKeys.size()]);
String signedHeaders = StringUtils.join(";", Arrays.asList(canonicalizedKeysArray));
Arrays.sort(canonicalizedKeysArray);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < canonicalizedKeysArray.length; i++) {
String key = canonicalizedKeysArray[i];
sb.append(key);
sb.append(":");
sb.append(valueMap.get(key));
sb.append("\n");
}
result.put("canonicalHeaders", sb.toString());
result.put("signedHeaders", signedHeaders);
return result;
}
protected static String getCanonicalizedQueryString(StringBuilder sb, Map<String, String> query, String[] keys)
throws Exception {
if (query == null || query.size() == 0) {
return "";
}
if (keys == null || keys.length == 0) {
return "";
}
if (sb == null) {
sb = new StringBuilder();
}
Arrays.sort(keys);
String key;
String value;
for (int i = 0; i < keys.length; i++) {
key = keys[i];
sb.append(percentEncode(key));
value = query.get(key);
sb.append("=");
if (!StringUtils.isEmpty(value)) {
sb.append(percentEncode(value));
}
sb.append(SEPARATOR);
}
return sb.deleteCharAt(sb.length() - 1).toString();
}
protected static String getCanonicalizedQueryStringForROA(StringBuilder sb, Map<String, String> query,
String[] keys) throws Exception {
if (query == null || query.size() == 0) {
return "";
}
if (keys == null || keys.length == 0) {
return "";
}
if (sb == null) {
sb = new StringBuilder();
}
Arrays.sort(keys);
String key;
String value;
for (int i = 0; i < keys.length; i++) {
key = keys[i];
sb.append(key);
value = query.get(key);
if (!StringUtils.isEmpty(value)) {
sb.append("=");
sb.append(value);
}
sb.append(SEPARATOR);
}
return sb.deleteCharAt(sb.length() - 1).toString();
}
protected static String getCanonicalizedResource(Map<String, String> query) throws Exception {
if (query == null || query.size() == 0) {
return "";
}
String[] keys = query.keySet().toArray(new String[query.size()]);
StringBuilder result = new StringBuilder();
return getCanonicalizedQueryString(result, query, keys);
}
protected static String getCanonicalizedResource(String pathname, Map<String, String> query) throws Exception {
if (query == null || query.size() == 0) {
return pathname;
}
String[] keys = query.keySet().toArray(new String[query.size()]);
if (pathname == null || keys.length <= 0) {
return pathname;
}
StringBuilder result = new StringBuilder(pathname);
result.append("?");
return getCanonicalizedQueryStringForROA(result, query, keys);
}
/**
* Get signature according to stringToSign, secret
*
* @param stringToSign the signed string
* @param secret accesskey secret
* @return the signature
*/
public static String getROASignature(String stringToSign, String secret) throws Exception {
if (StringUtils.isEmpty(secret)) {
return secret;
}
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(secret.getBytes(UTF8), "HmacSHA1"));
byte[] signData = mac.doFinal(stringToSign.getBytes(UTF8));
return new BASE64Encoder().encode(signData);
}
/**
* Parse filter into a form string
*
* @param filter object
* @return the string
*/
public static String toForm(java.util.Map<String, ?> filter) throws Exception {
return toFormWithSymbol(filter, SEPARATOR);
}
private static String toFormWithSymbol(java.util.Map<String, ?> filter, String symbol) throws Exception {
Map<String, String> map = query(filter);
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, ?> entry : map.entrySet()) {
if (StringUtils.isEmpty(entry.getValue())) {
continue;
}
if (first) {
first = false;
} else {
result.append(symbol);
}
result.append(URLEncoder.encode(entry.getKey(), UTF8));
result.append("=");
result.append(URLEncoder.encode(String.valueOf(entry.getValue()), UTF8));
}
return result.toString();
}
/**
* Get timestamp
*
* @return the timestamp string
*/
public static String getTimestamp() throws Exception {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
df.setTimeZone(new SimpleTimeZone(0, "UTC"));
return df.format(new Date());
}
/**
* Parse filter into a object which's type is map[string]string
*
* @param filter query param
* @return the object
*/
public static java.util.Map<String, String> query(java.util.Map<String, ?> filter) throws Exception {
Map<String, String> outMap = new HashMap<>();
if (null != filter) {
processObject(outMap, "", filter);
}
return outMap;
}
private static void processObject(Map<String, String> map, String key, Object value)
throws UnsupportedEncodingException {
if (null == value) {
return;
}
if (value instanceof List) {
List list = (List) value;
for (int i = 0; i < list.size(); i++) {
processObject(map, key + "." + (i + 1), list.get(i));
}
} else if (value instanceof AccModel) {
Map<String, Object> subMap = (Map<String, Object>) (((AccModel) value).toMap());
for (Map.Entry<String, Object> entry : subMap.entrySet()) {
processObject(map, key + "." + (entry.getKey()), entry.getValue());
}
} else if (value instanceof Map) {
Map<String, Object> subMap = (Map<String, Object>) value;
for (Map.Entry<String, Object> entry : subMap.entrySet()) {
processObject(map, key + "." + (entry.getKey()), entry.getValue());
}
} else {
if (key.startsWith(".")) {
key = key.substring(1);
}
if (value instanceof byte[]) {
map.put(key, new String((byte[]) value, UTF8));
} else {
map.put(key, String.valueOf(value));
}
}
}
/**
* Get signature according to signedParams, method and secret
*
* @param signedParams params which need to be signed
* @param method http method e.g. GET
* @param secret AccessKeySecret
* @return the signature
*/
public static String getRPCSignature(java.util.Map<String, String> signedParams, String method, String secret)
throws Exception {
if (signedParams == null || StringUtils.isEmpty(secret)) {
return secret;
}
Map<String, String> queries = signedParams;
String[] sortedKeys = queries.keySet().toArray(new String[] {});
Arrays.sort(sortedKeys);
StringBuilder canonicalizedQueryString = new StringBuilder();
for (String key : sortedKeys) {
if (StringUtils.isEmpty(queries.get(key))) {
continue;
}
canonicalizedQueryString.append(SEPARATOR).append(percentEncode(key)).append("=")
.append(percentEncode(queries.get(key)));
}
StringBuilder stringToSign = new StringBuilder();
stringToSign.append(method);
stringToSign.append(SEPARATOR);
stringToSign.append(percentEncode("/"));
stringToSign.append(SEPARATOR);
stringToSign.append(percentEncode(canonicalizedQueryString.toString().substring(1)));
Mac mac = Mac.getInstance(ALGORITHM_NAME);
mac.init(new SecretKeySpec((secret + SEPARATOR).getBytes(URL_ENCODING), ALGORITHM_NAME));
byte[] signData = mac.doFinal(stringToSign.toString().getBytes(URL_ENCODING));
return DatatypeConverter.printBase64Binary(signData);
}
public static String percentEncode(String value) throws UnsupportedEncodingException {
return value != null
? URLEncoder.encode(value, URL_ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~")
: null;
}
/**
* Parse array into a string with specified style
*
* @param array the array
* @param prefix the prefix string
* @return the string
* @style specified style e.g. repeatList
*/
public static String arrayToStringWithSpecifiedStyle(Object array, String prefix, String style) throws Exception {
if (null == array) {
return "";
}
switch (style) {
case "repeatList":
Map<String, Object> map = new HashMap<String, Object>();
map.put(prefix, array);
return toFormWithSymbol(map, "&&");
case "simple":
case "spaceDelimited":
case "pipeDelimited":
return flatArray((List) array, style);
case "json":
Class clazz = array.getClass();
List list = new ArrayList();
if (List.class.isAssignableFrom(clazz)) {
list = (List) array;
}
if (list.size() > 0) {
if (AccModel.class.isAssignableFrom(list.get(0).getClass())) {
List<AccModel> AccModels = (List<AccModel>) array;
List<Map<String, Object>> mapList = new ArrayList<>();
for (AccModel AccModel : AccModels) {
mapList.add(AccModel.toMap());
}
return new Gson().toJson(mapList);
}
}
return new Gson().toJson(array);
default:
return "";
}
}
private static String flatArray(List array, String sty) {
if (array == null || array.size() <= 0 || sty == null) {
return "";
}
String flag;
if ("simple".equalsIgnoreCase(sty)) {
flag = ",";
} else if ("spaceDelimited".equalsIgnoreCase(sty)) {
flag = " ";
} else {
flag = "|";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.size(); i++) {
sb.append(array.get(i));
sb.append(flag);
}
return sb.deleteCharAt(sb.length() - 1).toString();
}
public static Map<String, Object> parseToMap(Object o) {
if (null == o) {
return null;
}
return (Map<String, Object>) AccModel.parseObject(o);
}
public static String hexEncode(byte[] raw) {
if (raw == null) {
return null;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < raw.length; i++) {
String hex = Integer.toHexString(raw[i] & 0xFF);
if (hex.length() < 2) {
sb.append(0);
}
sb.append(hex);
}
return sb.toString();
}
public static byte[] hash(byte[] raw, String signAlgorithm) throws Exception {
if (signAlgorithm == null) {
return null;
}
if (signAlgorithm.equals(HMAC_SHA256) || signAlgorithm.equals(RSA_SHA256)) {
MessageDigest digest = MessageDigest.getInstance(HASH_SHA256);
return digest.digest(raw);
} else if (signAlgorithm.equals(HMAC_SM3)) {
BouncyCastleProvider provider = new BouncyCastleProvider();
MessageDigest digest = MessageDigest.getInstance(HASH_SM3, provider);
return digest.digest(raw);
}
return null;
}
public static String getAuthorization(AccRequest request, String signAlgorithm, String payload, String accessKey,
String secret) throws Exception {
if (request == null) {
return null;
}
if (secret == null) {
throw new Exception("Need secret!");
}
if (StringUtils.isEmpty(signAlgorithm)) {
throw new Exception("Need signAlgorithm!");
}
String canonicalURI = request.pathname;
if (canonicalURI == null || StringUtils.isEmpty(canonicalURI) || "".equals(canonicalURI.trim())) {
canonicalURI = "/";
}
String method = request.method;
Map<String, String> headers = request.headers;
Map<String, String> query = request.query;
Map<String, String> cannoicalHeaders = getCanonicalizedHeadersMap(headers);
String signedHeaders = cannoicalHeaders.get("signedHeaders");
String queryString = getCanonicalizedResource(query);
StringBuilder sb = new StringBuilder(method);
sb.append("\n").append(canonicalURI).append("\n").append(queryString).append("\n")
.append(cannoicalHeaders.get("canonicalHeaders")).append("\n").append(signedHeaders).append("\n")
.append(payload);
String hex = hexEncode(hash(sb.toString().getBytes(UTF8), signAlgorithm));
String stringToSign = signAlgorithm + "\n" + hex;
String signature = hexEncode(SignatureMethod(stringToSign, secret, signAlgorithm));
String auth = signAlgorithm + " Credential=" + accessKey + ",SignedHeaders=" + signedHeaders + ",Signature="
+ signature;
return auth;
}
protected static String checkRSASecret(String secret) {
if (secret != null) {
if (secret.startsWith(PEM_BEGIN)) {
secret = secret.replace(PEM_BEGIN, "");
}
while (secret.endsWith("\n") || secret.endsWith("\r")) {
secret = secret.substring(0, secret.length() - 1);
}
if (secret.endsWith(PEM_END)) {
secret = secret.replace(PEM_END, "");
}
}
return secret;
}
public static byte[] SignatureMethod(String stringToSign, String secret, String signAlgorithm) throws Exception {
if (stringToSign == null || secret == null || signAlgorithm == null) {
return null;
}
byte[] bytes = null;
if (signAlgorithm.equals(HMAC_SHA256)) {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
bytes = sha256_HMAC.doFinal(stringToSign.getBytes());
return bytes;
} else if (signAlgorithm.equals(RSA_SHA256)) {
secret = checkRSASecret(secret);
Signature rsaSign = Signature.getInstance("SHA256withRSA");
KeyFactory kf = KeyFactory.getInstance("RSA");
byte[] keySpec = DatatypeConverter.parseBase64Binary(secret);
PrivateKey privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(keySpec));
rsaSign.initSign(privateKey);
rsaSign.update(stringToSign.getBytes(UTF8));
bytes = rsaSign.sign();
} else if (signAlgorithm.equals(HMAC_SM3)) {
SecretKey key = new SecretKeySpec((secret).getBytes(UTF8), "HMAC-SM3");
HMac mac = new HMac(new SM3Digest());
bytes = new byte[mac.getMacSize()];
byte[] inputBytes = stringToSign.getBytes(UTF8);
mac.init(new KeyParameter(key.getEncoded()));
mac.update(inputBytes, 0, inputBytes.length);
mac.doFinal(bytes, 0);
}
return bytes;
}
public static String getEncodePath(String path) throws UnsupportedEncodingException {
if (StringUtils.isEmpty(path)) {
return path;
}
String[] strs = path.split("/");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strs.length; i++) {
sb.append(percentEncode(strs[i]));
sb.append("/");
}
return sb.deleteCharAt(sb.length() - 1).toString();
}
}
package com.dsk.acc.openapi.client.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.SimpleTimeZone;
import java.util.UUID;
import com.dsk.acc.openapi.client.core.AccModel;
import com.dsk.acc.openapi.client.exception.AccValidException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
public class CommonUtils {
private static final String defaultUserAgent;
static {
Properties sysProps = System.getProperties();
defaultUserAgent = String.format("AccOpenApiClient (%s; %s) Java/%s V%s", sysProps.getProperty("os.name"), sysProps
.getProperty("os.arch"), sysProps.getProperty("java.runtime.version"), "1.0.0");
}
/**
* Convert a string(utf8) to bytes
*
* @return the return bytes
*/
public static byte[] toBytes(String str) {
try {
return str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AccValidException(e.getMessage(), e);
}
}
/**
* Convert a bytes to string(utf8)
*
* @return the return string
*/
public static String toString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AccValidException(e.getMessage(), e);
}
}
/**
* Parse it by JSON format
*
* @return the parsed result
*/
public static Object parseJSON(String json) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(new TypeToken<Map<String,Object>>(){}.getType(),new MapTypeAdapter()).create();
JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
return jsonElement.isJsonArray() ? gson.fromJson(json,List.class):
gson.fromJson(json,new TypeToken<Map<String, Object>>(){}.getType());
}
/**
* Assert a value, if it is a map, it, otherwise throws
*
* @return the map value
*/
public static Map<String, Object> assertAsMap(Object object) {
if (null != object && Map.class.isAssignableFrom(object.getClass())) {
return (Map<String, Object>) object;
}
throw new AccValidException("The value is not a object");
}
/**
* Assert a value, if it is a array, return it, otherwise throws
*
* @return the array
*/
public static List<Object> assertAsArray(Object object) {
if (null != object && List.class.isAssignableFrom(object.getClass())) {
return (List<Object>) object;
}
throw new AccValidException("The value is not a array");
}
/**
* Assert a value, if it is a readable, return it, otherwise throws
*
* @return the readable value
*/
public static InputStream assertAsReadable(Object value) {
if (null != value && InputStream.class.isAssignableFrom(value.getClass())) {
return (InputStream) value;
}
throw new AccValidException("The value is not a readable");
}
/**
* Assert a value, if it is a bytes, return it, otherwise throws
*
* @return the bytes value
*/
public static byte[] assertAsBytes(Object object) {
if (object instanceof byte[]) {
return (byte[]) object;
}
throw new AccValidException("The value is not a byteArray");
}
/**
* Assert a value, if it is a number, return it, otherwise throws
*
* @return the number value
*/
public static Number assertAsNumber(Object object) {
if (object instanceof Number) {
return (Number) object;
}
throw new AccValidException("The value is not a Number");
}
/**
* Assert a value, if it is a string, return it, otherwise throws
*
* @return the string value
*/
public static String assertAsString(Object object) {
if (object instanceof String) {
return (String) object;
}
throw new AccValidException("The value is not a String");
}
/**
* Assert a value, if it is a boolean, return it, otherwise throws
*
* @return the boolean value
*/
public static Boolean assertAsBoolean(Object object) {
try {
return (Boolean) object;
} catch (Exception e) {
throw new AccValidException("The value is not a Boolean");
}
}
/**
* Read data from a readable stream, and compose it to a bytes
*
* @param stream the readable stream
* @return the bytes result
*/
public static byte[] readAsBytes(InputStream stream) {
try {
if (null == stream) {
return new byte[]{};
} else {
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
while (true) {
int read = stream.read(buff);
if (read == -1) {
return os.toByteArray();
}
os.write(buff, 0, read);
}
}
} catch (Exception e) {
throw new AccValidException(e.getMessage(), e);
} finally {
if (null != stream) {
try {
stream.close();
} catch (IOException e) {
throw new AccValidException(e.getMessage(), e);
}
}
}
}
/**
* Read data from a readable stream, and compose it to a string
*
* @param stream the readable stream
* @return the string result
*/
public static String readAsString(InputStream stream) {
try {
return new String(readAsBytes(stream), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AccValidException(e.getMessage(), e);
}
}
/**
* Read data from a readable stream, and parse it by JSON format
*
* @param stream the readable stream
* @return the parsed result
*/
public static Object readAsJSON(InputStream stream) {
String body = readAsString(stream);
try {
return parseJSON(body);
} catch (Exception exception) {
throw new AccValidException("Error: convert to JSON, response is:\n" + body);
}
}
/**
* Generate a nonce string
*
* @return the nonce string
*/
public static String getNonce() {
StringBuffer uniqueNonce = new StringBuffer();
UUID uuid = UUID.randomUUID();
uniqueNonce.append(uuid.toString());
uniqueNonce.append(System.currentTimeMillis());
uniqueNonce.append(Thread.currentThread().getId());
return uniqueNonce.toString();
}
/**
* Get an UTC format string by current date, e.g. 'Thu, 06 Feb 2020 07:32:54 GMT'
*
* @return the UTC format string
*/
public static String getDateUTCString() {
SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
df.setTimeZone(new SimpleTimeZone(0, "GMT"));
return df.format(new Date());
}
/**
* If not set the real, use default value
*
* @return the return string
*/
public static String defaultString(String str, String defaultStr) {
if (!StringUtils.isEmpty(str)) {
return str;
}
return defaultStr;
}
/**
* If not set the real, use default value
*
* @return the return string
*/
public static Number defaultNumber(Number number, Number defaultNumber) {
if (number != null && number.doubleValue() >= 0) {
return number;
}
return defaultNumber;
}
/**
* Format a map to form string, like a=a%20b%20c
*
* @return the form string
*/
public static String toFormString(Map<String, ?> map) {
if (null == map) {
return "";
}
StringBuilder result = new StringBuilder();
boolean first = true;
try {
for (Map.Entry<String, ?> entry : map.entrySet()) {
if (StringUtils.isEmpty(entry.getValue())) {
continue;
}
if (first) {
first = false;
} else {
result.append("&");
}
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
}
} catch (Exception e) {
throw new AccValidException(e.getMessage(), e);
}
return result.toString();
}
/**
* If not set the real, use default value
*
* @return the return string
*/
public static String toJSONString(Object object) {
return new Gson().toJson(object);
}
/**
* Check the string is empty?
*
* @return if string is null or zero length, return true
*/
public static boolean empty(String str) {
return StringUtils.isEmpty(str);
}
/**
* Check one string equals another one?
*
* @return if equals, return true
*/
public static boolean equalString(String str, String val) {
if (str == null || val == null) {
return false;
}
return str.equals(val);
}
/**
* Check one number equals another one?
*
* @return if equals, return true
*/
public static boolean equalNumber(Number num, Number val) {
if (num == null || val == null) {
return false;
}
return num.doubleValue() == val.doubleValue();
}
/**
* Check one value is unset
*
* @return if unset, return true
*/
public static boolean isUnset(Object object) {
return null == object;
}
/**
* Stringify the value of map
*
* @return the new stringified map
*/
public static Map<String, String> stringifyMapValue(Map<String, ?> map) {
Map<String, String> result = new HashMap<>();
if (null == map) {
return null;
}
for (Map.Entry<String, ?> entry : map.entrySet()) {
if (null == entry.getValue()) {
continue;
}
result.put(entry.getKey(), String.valueOf(entry.getValue()));
}
return result;
}
/**
* Anyify the value of map
*
* @return the new anyfied map
*/
public static Map<String, Object> anyifyMapValue(Map<String, ?> map) {
Map<String, Object> result = new HashMap<>();
if (null == map) {
return null;
}
for (Map.Entry<String, ?> entry : map.entrySet()) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
/**
* Get user agent, if it userAgent is not null, splice it with defaultUserAgent and return, otherwise return defaultUserAgent
*
* @return the string value
*/
public static String getUserAgent(String val) {
if (StringUtils.isEmpty(val)) {
return defaultUserAgent;
}
return defaultUserAgent + " " + val;
}
/**
* If the code between 200 and 300, return true, or return false
*
* @return boolean
*/
public static boolean is2xx(Number code) {
if (null == code) {
return false;
}
return code.intValue() >= 200 && code.intValue() < 300 ? true : false;
}
/**
* If the code between 300 and 400, return true, or return false
*
* @return boolean
*/
public static boolean is3xx(Number code) {
if (null == code) {
return false;
}
return code.intValue() >= 300 && code.intValue() < 400 ? true : false;
}
/**
* If the code between 400 and 500, return true, or return false
*
* @return boolean
*/
public static boolean is4xx(Number code) {
if (null == code) {
return false;
}
return code.intValue() >= 400 && code.intValue() < 500 ? true : false;
}
/**
* If the code between 500 and 600, return true, or return false
*
* @return boolean
*/
public static boolean is5xx(Number code) {
if (null == code) {
return false;
}
return code.intValue() >= 500 && code.intValue() < 600 ? true : false;
}
/**
* Validate model
*
* @return void
*/
public static void validateModel(AccModel m) {
if (null == m) {
throw new AccValidException("parameter is not allowed as null");
}
try {
m.validate();
} catch (Exception e) {
throw new AccValidException(e.getMessage(), e);
}
}
/**
* Model transforms to map[string]any
*
* @return map[string]any
*/
public static java.util.Map<String, Object> toMap(AccModel in) {
try {
return AccModel.toMap(in);
} catch (Exception e) {
throw new AccValidException(e.getMessage(), e);
}
}
/**
* Suspends the current thread for the specified number of milliseconds.
*/
public static void sleep(int millisecond) {
try {
Thread.sleep(millisecond);
} catch (InterruptedException e) {
throw new AccValidException(e.getMessage(), e);
}
}
/**
* Transform input as array.
*/
public static List<Map<String, Object>> toArray(Object input) {
if (null == input) {
return null;
}
try {
List<AccModel> AccModels = (List<AccModel>) input;
List<Map<String, Object>> result = new ArrayList<>();
for (AccModel AccModel : AccModels) {
if (null == AccModel) {
continue;
}
result.add(AccModel.toMap());
}
return result;
} catch (Exception e) {
return null;
}
}
}
package com.dsk.acc.openapi.client.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
public class MapTypeAdapter extends TypeAdapter<Object> {
private final TypeAdapter<Object> delegate = new Gson().getAdapter(Object.class);
@Override
public Object read(JsonReader in) throws IOException {
JsonToken token = in.peek();
switch (token) {
case BEGIN_ARRAY:
List<Object> list = new ArrayList<Object>();
in.beginArray();
while (in.hasNext()) {
list.add(read(in));
}
in.endArray();
return list;
case BEGIN_OBJECT:
Map<String, Object> map = new LinkedTreeMap<String,Object>();
in.beginObject();
while (in.hasNext()) {
map.put(in.nextName(), read(in));
}
in.endObject();
return map;
case STRING:
return in.nextString();
case NUMBER:
/**
* 改写数字的处理逻辑,将数字值分为整型与浮点型。
*/
double dbNum = in.nextDouble();
// 数字超过long的最大值,返回浮点类型
if (dbNum > Long.MAX_VALUE) {
return dbNum;
}
// 判断数字是否为整数值
long lngNum = (long) dbNum;
if (dbNum == lngNum) {
return lngNum;
} else {
return dbNum;
}
case BOOLEAN:
return in.nextBoolean();
case NULL:
in.nextNull();
return null;
default:
throw new IllegalStateException();
}
}
@Override
public void write(JsonWriter out, Object value) throws IOException {
delegate.write(out,value);
}
}
\ No newline at end of file
package com.dsk.acc.openapi.client.util;
import java.util.Objects;
public class StringUtils {
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static boolean isEmpty(Object object) {
if (null != object) {
return isEmpty(String.valueOf(object));
}
return true;
}
public static String join(String delimiter, Iterable<? extends String> elements) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(elements);
StringBuilder stringBuilder = new StringBuilder();
for (String value : elements) {
stringBuilder.append(value);
stringBuilder.append(delimiter);
}
if (stringBuilder.length() > 0) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
return stringBuilder.toString();
}
}
package com.dsk.acc.openapi.client.util;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class TrueHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
package com.dsk.acc.openapi.client.util;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
public class X509TrustManagerImp implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
package com.dsk.acc.openapi.client.util.okhttp;
import okhttp3.OkHttpClient;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ClientHelper {
public static final ConcurrentHashMap<String, OkHttpClient> clients = new ConcurrentHashMap<String, OkHttpClient>();
public static OkHttpClient getOkHttpClient(String host, int port, Map<String, Object> map) throws Exception {
String key;
if (null != map.get("httpProxy") || null != map.get("httpsProxy")) {
Object urlString = null == map.get("httpProxy") ? map.get("httpsProxy") : map.get("httpProxy");
URL url = new URL(String.valueOf(urlString));
key = getClientKey(url.getHost(), url.getPort());
} else {
key = getClientKey(host, port);
}
OkHttpClient client = clients.get(key);
if (null == client) {
client = creatClient(map);
clients.put(key, client);
}
return client;
}
public static OkHttpClient creatClient(Map<String, Object> map) {
OkHttpClientBuilder builder = new OkHttpClientBuilder();
builder = builder.connectTimeout(map).readTimeout(map).connectionPool(map).certificate(map).proxy(map).proxyAuthenticator(map);
OkHttpClient client = builder.buildOkHttpClient();
return client;
}
public static String getClientKey(String host, int port) {
return String.format("%s:%d", host, port);
}
}
package com.dsk.acc.openapi.client.util.okhttp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.dsk.acc.openapi.client.exception.AccException;
import com.dsk.acc.openapi.client.util.TrueHostnameVerifier;
import com.dsk.acc.openapi.client.util.X509TrustManagerImp;
import okhttp3.Authenticator;
import okhttp3.ConnectionPool;
import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class OkHttpClientBuilder {
private OkHttpClient.Builder builder;
public OkHttpClientBuilder() {
builder = new OkHttpClient().newBuilder();
}
public OkHttpClientBuilder connectTimeout(Map<String, Object> map) {
Object object = map.get("connectTimeout");
long timeout;
try {
timeout = Long.parseLong(String.valueOf(object));
} catch (Exception e) {
return this;
}
this.builder.connectTimeout(timeout, TimeUnit.MILLISECONDS);
return this;
}
public OkHttpClientBuilder readTimeout(Map<String, Object> map) {
Object object = map.get("readTimeout");
long timeout;
try {
timeout = Long.parseLong(String.valueOf(object));
} catch (Exception e) {
return this;
}
this.builder.readTimeout(timeout, TimeUnit.MILLISECONDS);
return this;
}
public OkHttpClientBuilder connectionPool(Map<String, Object> map) {
Object maxIdleConns = map.get("maxIdleConns");
int maxIdleConnections;
try {
maxIdleConnections = Integer.parseInt(String.valueOf(maxIdleConns));
} catch (Exception e) {
maxIdleConnections = 5;
}
ConnectionPool connectionPool = new ConnectionPool(maxIdleConnections, 10000L, TimeUnit.MILLISECONDS);
this.builder.connectionPool(connectionPool);
return this;
}
public OkHttpClientBuilder certificate(Map<String, Object> map) {
try {
if (Boolean.parseBoolean(String.valueOf(map.get("ignoreSSL")))) {
X509TrustManager compositeX509TrustManager = new X509TrustManagerImp();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{compositeX509TrustManager}, new java.security.SecureRandom());
this.builder.sslSocketFactory(sslContext.getSocketFactory(), compositeX509TrustManager).
hostnameVerifier(new TrueHostnameVerifier());
}
return this;
} catch (Exception e) {
throw new AccException(e.getMessage(), e);
}
}
public OkHttpClientBuilder proxy(Map<String, Object> map) {
try {
if (null != map.get("httpProxy") || null != map.get("httpsProxy")) {
Object urlString = null == map.get("httpProxy") ? map.get("httpsProxy") : map.get("httpProxy");
URL url = new URL(String.valueOf(urlString));
this.builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort())));
}
return this;
} catch (Exception e) {
throw new AccException(e.getMessage(), e);
}
}
public OkHttpClientBuilder proxyAuthenticator(Map<String, Object> map) {
try {
Object httpsProxy = map.get("httpsProxy");
if (httpsProxy != null) {
URL proxyUrl = new URL(String.valueOf(httpsProxy));
String userInfo = proxyUrl.getUserInfo();
if (null != userInfo) {
String[] userMessage = userInfo.split(":");
final String credential = Credentials.basic(userMessage[0], userMessage[1]);
Authenticator authenticator = new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
this.builder.proxyAuthenticator(authenticator);
}
}
return this;
} catch (Exception e) {
throw new AccException(e.getMessage(), e);
}
}
public OkHttpClient buildOkHttpClient() {
return this.builder.build();
}
}
package com.dsk.acc.openapi.client.util.okhttp;
import java.io.IOException;
import java.io.InputStream;
import com.dsk.acc.openapi.client.core.AccRequest;
import com.dsk.acc.openapi.client.util.StringUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
public class OkRequestBody extends RequestBody {
private InputStream inputStream;
private String contentType;
public OkRequestBody(AccRequest teaRequest) {
this.inputStream = teaRequest.body;
this.contentType = teaRequest.headers.get("content-type");
}
@Override
public MediaType contentType() {
MediaType type;
if (StringUtils.isEmpty(contentType)) {
if (null == inputStream) {
return null;
}
type = MediaType.parse("application/json; charset=UTF-8;");
return type;
}
return MediaType.parse(contentType);
}
@Override
public long contentLength() throws IOException {
if (null != inputStream && inputStream.available() > 0) {
return inputStream.available();
}
return super.contentLength();
}
@Override
public void writeTo(BufferedSink bufferedSink) throws IOException {
if (null == inputStream) {
return;
}
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
bufferedSink.write(buffer, 0, bytesRead);
}
}
}
package com.dsk.acc.openapi.client.util.okhttp;
import java.net.URL;
import java.util.Map;
import com.dsk.acc.openapi.client.core.AccRequest;
import okhttp3.Request;
public class OkRequestBuilder {
private Request.Builder builder;
public OkRequestBuilder(Request.Builder builder) {
this.builder = builder;
}
public OkRequestBuilder url(URL url) {
this.builder.url(url);
return this;
}
public OkRequestBuilder header(Map<String, String> headers) {
for (String headerName : headers.keySet()) {
this.builder.header(headerName, headers.get(headerName));
}
return this;
}
public Request buildRequest(AccRequest request) {
String method = request.method.toUpperCase();
OkRequestBody requestBody;
switch (method) {
case "DELETE":
this.builder.delete();
break;
case "POST":
requestBody = new OkRequestBody(request);
this.builder.post(requestBody);
break;
case "PUT":
requestBody = new OkRequestBody(request);
this.builder.put(requestBody);
break;
case "PATCH":
requestBody = new OkRequestBody(request);
this.builder.patch(requestBody);
break;
default:
this.builder.get();
break;
}
return this.builder.build();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment