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;
}
This diff is collapsed.
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;
}
}
This diff is collapsed.
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);
}
}
This diff is collapsed.
This diff is collapsed.
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