diff --git a/doc/docs/_sidebar.md b/doc/docs/_sidebar.md index c41c2a91..5f9e6e4f 100644 --- a/doc/docs/_sidebar.md +++ b/doc/docs/_sidebar.md @@ -1,17 +1,18 @@ -* [首页](/?t=1554123435599) +* [首页](/?t=1554195848085) * 开发文档 - * [快速体验](files/10010_快速体验.md?t=1554123435601) - * [项目接入到SOP](files/10011_项目接入到SOP.md?t=1554123435620) - * [新增接口](files/10020_新增接口.md?t=1554123435620) - * [业务参数校验](files/10030_业务参数校验.md?t=1554123435620) - * [错误处理](files/10040_错误处理.md?t=1554123435620) - * [接口交互详解](files/10050_接口交互详解.md?t=1554123435621) - * [使用SpringCloudGateway](files/10060_使用SpringCloudGateway.md?t=1554123435621) - * [easyopen支持](files/10070_easyopen支持.md?t=1554123435621) - * [使用签名校验工具](files/10080_使用签名校验工具.md?t=1554123435621) - * [ISV管理](files/10085_ISV管理.md?t=1554123435621) - * [路由授权](files/10090_路由授权.md?t=1554123435621) + * [快速体验](files/10010_快速体验.md?t=1554195848087) + * [项目接入到SOP](files/10011_项目接入到SOP.md?t=1554195848105) + * [新增接口](files/10020_新增接口.md?t=1554195848105) + * [业务参数校验](files/10030_业务参数校验.md?t=1554195848105) + * [错误处理](files/10040_错误处理.md?t=1554195848105) + * [接口交互详解](files/10050_接口交互详解.md?t=1554195848105) + * [使用SpringCloudGateway](files/10060_使用SpringCloudGateway.md?t=1554195848105) + * [easyopen支持](files/10070_easyopen支持.md?t=1554195848105) + * [使用签名校验工具](files/10080_使用签名校验工具.md?t=1554195848106) + * [ISV管理](files/10085_ISV管理.md?t=1554195848106) + * [路由授权](files/10090_路由授权.md?t=1554195848106) + * [开发SDK](files/10095_开发SDK.md?t=1554195848106) * 原理分析 - * [原理分析之@ApiMapping](files/90010_原理分析之@ApiMapping.md?t=1554123435621) - * [原理分析之路由存储](files/90011_原理分析之路由存储.md?t=1554123435622) - * [原理分析之如何路由](files/90012_原理分析之如何路由.md?t=1554123435622) + * [原理分析之@ApiMapping](files/90010_原理分析之@ApiMapping.md?t=1554195848106) + * [原理分析之路由存储](files/90011_原理分析之路由存储.md?t=1554195848106) + * [原理分析之如何路由](files/90012_原理分析之如何路由.md?t=1554195848106) diff --git a/doc/docs/files/10095_开发SDK.md b/doc/docs/files/10095_开发SDK.md new file mode 100644 index 00000000..eae72982 --- /dev/null +++ b/doc/docs/files/10095_开发SDK.md @@ -0,0 +1,142 @@ +# 开发SDK + +开放平台把接口开发完毕后,一般需要开发对应的SDK,提供给ISV。SOP提供了一个基础的SDK开发包 + +开发者可以在此基础上做开发,就拿sdk-java来说,具体步骤如下: + +sdk for java + +开放平台对应的sdk,适用于Android。SDK依赖了三个jar包 + +- okhttp.jar 用于网络请求 +- fastjson-android.jar 用于json处理 +- commons-logging.jar 日志处理 + +## 接口封装步骤 + +比如获取故事信息接口 + +- 接口名:alipay.story.find +- 版本号:1.0 +- 参数:name 故事名称 +- 返回信息 + +``` +{ + "alipay_story_find_response": { + "msg": "Success", + "code": "10000", + "name": "白雪公主", + "id": 1, + "gmtCreate": 1554193987378 + }, + "sign": "xxxxx" +} +``` + +针对这个接口,封装步骤如下: + +1.在`model`包下新建一个类,定义业务参数 + + +```java +@Data +public class GetStoryModel { + + @JSONField(name = "name") + private String name; +} +``` + +2.在`response`包下新建一个返回类GetStoryResponse,继承`BaseResponse` + +里面填写返回的字段 + +``` +@Data +public class GetStoryResponse extends BaseResponse { + private Long id; + private String name; + private Date gmtCreate; +} +``` + +3.在`request`包下新建一个请求类,继承`BaseRequest` + +BaseRequest中有个泛型参数,填`GetStoryResponse`类,表示这个请求对应的返回类。 +重写`method()`方法,填接口名。 + +如果要指定版本号,可重写`version()`方法,或者后续使用`request.setVersion(version)`进行设置 + +```java +public class GetStoryRequest extends BaseRequest { + @Override + protected String method() { + return "alipay.story.find"; + } +} + +``` + +## 使用方式 + +```java +String url = "http://localhost:8081/api"; // zuul +String appId = "2019032617262200001"; +String privateKey = "你的私钥"; + +// 声明一个就行 +OpenClient client = new OpenClient(url, appId, privateKey); + +// 标准用法 +@Test +public void testGet() { + // 创建请求对象 + GetStoryRequest request = new GetStoryRequest(); + // 请求参数 + GetStoryModel model = new GetStoryModel(); + model.setName("白雪公主"); + + request.setBizModel(model); + + // 发送请求 + GetStoryResponse response = client.execute(request); + + if (response.isSuccess()) { + // 返回结果 + System.out.println(response); + } else { + System.out.println(response); + } +} +``` + +## 使用方式2(懒人版) + +如果不想添加Request,Response,Model。可以用这种方式,返回body部分是字符串,后续自己处理 + +body对应的是alipay_story_find_response部分 + +```java +@Test +public void testLazy() { + // 创建请求对象 + CommonRequest request = new CommonRequest("alipay.story.find"); + // 请求参数 + Map bizModel = new HashMap<>(); + bizModel.put("name", "白雪公主"); + request.setBizModel(bizModel); + + // 发送请求 + CommonResponse response = client.execute(request); + + if (response.isSuccess()) { + // 返回结果,body对应的是alipay_story_find_response部分 + String body = response.getBody(); + JSONObject jsonObject = JSON.parseObject(body); + System.out.println(jsonObject); + } else { + System.out.println(response); + } +} +``` diff --git a/pom.xml b/pom.xml index e9be012a..4d774179 100644 --- a/pom.xml +++ b/pom.xml @@ -18,5 +18,6 @@ sop-registry sop-gateway sop-test + sop-sdk \ No newline at end of file diff --git a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/isv/IsvApi.java b/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/isv/IsvApi.java index ba3e0bdb..4754eef4 100644 --- a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/isv/IsvApi.java +++ b/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/isv/IsvApi.java @@ -129,8 +129,8 @@ public class IsvApi { @Api(name = "isv.info.add") @ApiDocMethod(description = "添加isv") - @Transactional - void addIsv(IsvInfoFormAdd param) throws Exception { + @Transactional(rollbackFor = Exception.class) + public void addIsv(IsvInfoFormAdd param) throws Exception { if (isvInfoMapper.getByColumn("app_key", param.getAppKey()) != null) { throw new ApiException("appKey已存在"); } @@ -147,8 +147,8 @@ public class IsvApi { @Api(name = "isv.info.update") @ApiDocMethod(description = "修改isv") - @Transactional - void updateIsv(IsvInfoFormUpdate param) { + @Transactional(rollbackFor = Exception.class) + public void updateIsv(IsvInfoFormUpdate param) { formatForm(param); IsvInfo rec = isvInfoMapper.getById(param.getId()); CopyUtil.copyPropertiesIgnoreNull(param, rec); diff --git a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/service/RouteApi.java b/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/service/RouteApi.java index c222c4d2..252eeb23 100644 --- a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/service/RouteApi.java +++ b/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/service/RouteApi.java @@ -26,6 +26,7 @@ import org.apache.commons.lang.StringUtils; import org.apache.curator.framework.recipes.cache.ChildData; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -143,7 +144,8 @@ public class RouteApi { @Api(name = "route.role.update") @ApiDocMethod(description = "更新路由对应的角色") - void updateRouteRole(RoutePermissionParam param) { + @Transactional(rollbackFor = Exception.class) + public void updateRouteRole(RoutePermissionParam param) { String routeId = param.getRouteId(); // 删除所有数据 Query delQuery = new Query(); diff --git a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/interceptor/LockInterceptor.java b/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/interceptor/LockInterceptor.java deleted file mode 100644 index 3584e983..00000000 --- a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/interceptor/LockInterceptor.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.gitee.sop.adminserver.interceptor; - -import java.util.Map; - -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.core.StringRedisTemplate; - -import com.auth0.jwt.interfaces.Claim; -import com.gitee.easyopen.ApiContext; -import com.gitee.easyopen.ApiMeta; -import com.gitee.easyopen.support.BaseLockInterceptor; - -/** - * 使用分布式锁防止表单重复提交 - * - * @author tanghc - */ -public class LockInterceptor extends BaseLockInterceptor { - - private StringRedisTemplate redisTemplate; - - public LockInterceptor() { - redisTemplate = ApiContext.getApplicationContext().getBean(StringRedisTemplate.class); - } - - @SuppressWarnings("rawtypes") - @Override - protected RedisTemplate getRedisTemplate() { - return redisTemplate; - } - - @Override - protected String getUserId() { - Map jwtData = ApiContext.getJwtData(); - String id = jwtData.get("id").asString(); // 用户id - return id; - } - - @Override - public boolean match(ApiMeta apiMeta) { - return "userlock.test".equals(apiMeta.getName()); // 只针对这个接口 - } -} diff --git a/sop-example/sop-story/sop-story-web/src/main/java/com/gitee/sop/bookweb/controller/AlipayController.java b/sop-example/sop-story/sop-story-web/src/main/java/com/gitee/sop/bookweb/controller/AlipayController.java index ab433fd0..3c378faa 100644 --- a/sop-example/sop-story/sop-story-web/src/main/java/com/gitee/sop/bookweb/controller/AlipayController.java +++ b/sop-example/sop-story/sop-story-web/src/main/java/com/gitee/sop/bookweb/controller/AlipayController.java @@ -2,8 +2,11 @@ package com.gitee.sop.bookweb.controller; import com.gitee.sop.servercommon.annotation.ApiMapping; import com.gitee.sop.story.api.domain.Story; +import lombok.Data; import org.springframework.web.bind.annotation.RestController; +import java.util.Date; + /** * 支付宝服务端,假设签名验证通过后,到达这里进行具体的业务处理。 * 这里演示如何接受业务参数。 @@ -20,8 +23,24 @@ public class AlipayController { return story; } + @ApiMapping(value = "alipay.story.find") + public StoryVO getStory2(Story story) { + StoryVO storyVO = new StoryVO(); + storyVO.id = 1L; + storyVO.name = "白雪公主"; + storyVO.gmtCreate = new Date(); + return storyVO; + } + @ApiMapping(value = "alipay.story.get", version = "1.2") public Story getStory11(Story story) { return story; } + + @Data + public static class StoryVO { + private Long id; + private String name; + private Date gmtCreate; + } } diff --git a/sop-sdk/pom.xml b/sop-sdk/pom.xml new file mode 100644 index 00000000..14908be5 --- /dev/null +++ b/sop-sdk/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + com.gitee.sop + sop-sdk + 1.0.0-SNAPSHOT + pom + + + 1.8 + UTF-8 + 1.8 + 1.8 + + + + sdk-java + + + \ No newline at end of file diff --git a/sop-sdk/readme.md b/sop-sdk/readme.md new file mode 100644 index 00000000..bcbc4e09 --- /dev/null +++ b/sop-sdk/readme.md @@ -0,0 +1,3 @@ +# 接口对应的sdk + +具体使用方式参见各语言版本的readme.md \ No newline at end of file diff --git a/sop-sdk/sdk-java/.gitignore b/sop-sdk/sdk-java/.gitignore new file mode 100644 index 00000000..2af7cefb --- /dev/null +++ b/sop-sdk/sdk-java/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/sop-sdk/sdk-java/pom.xml b/sop-sdk/sdk-java/pom.xml new file mode 100644 index 00000000..84d935a1 --- /dev/null +++ b/sop-sdk/sdk-java/pom.xml @@ -0,0 +1,105 @@ + + 4.0.0 + com.gitee.sop + sdk-java + 1.0.0-SNAPSHOT + + + + 1.8 + UTF-8 + UTF-8 + + + + + + com.squareup.okhttp3 + okhttp + 3.10.0 + + + + + com.alibaba + fastjson + 1.1.68.android + + + + commons-logging + commons-logging + 1.2 + + + + junit + junit + 4.8 + test + + + + org.projectlombok + lombok + 1.18.4 + provided + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + UTF-8 + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9 + + + attach-javadocs + + jar + + + + -Xdoclint:none + + + + + + + + diff --git a/sop-sdk/sdk-java/readme.md b/sop-sdk/sdk-java/readme.md new file mode 100644 index 00000000..f6c20ed4 --- /dev/null +++ b/sop-sdk/sdk-java/readme.md @@ -0,0 +1,139 @@ +# sdk-java + + +sdk for java + +开放平台对应的sdk,适用于Android。SDK只依赖了三个jar包 + +- okhttp.jar +- fastjson-android.jar +- commons-logging.jar + +## 接口封装步骤 + +比如获取故事信息接口 + +- 接口名:alipay.story.find +- 版本号:1.0 +- 参数:name 故事名称 +- 返回信息 + +``` +{ + "alipay_story_find_response": { + "msg": "Success", + "code": "10000", + "name": "白雪公主", + "id": 1, + "gmtCreate": 1554193987378 + }, + "sign": "xxxxx" +} +``` + +针对这个接口,封装步骤如下: + +1.在`model`包下新建一个类,定义业务参数 + + +```java +@Data +public class GetStoryModel { + + @JSONField(name = "name") + private String name; +} +``` + +2.在`response`包下新建一个返回类GetStoryResponse,继承`BaseResponse` + +里面填写返回的字段 + +``` +@Data +public class GetStoryResponse extends BaseResponse { + private Long id; + private String name; + private Date gmtCreate; +} +``` + +3.在`request`包下新建一个请求类,继承`BaseRequest` + +BaseRequest中有个泛型参数,填`GetStoryResponse`类,表示这个请求对应的返回类。 +重写`method()`方法,填接口名。 + +如果要指定版本号,可重写`version()`方法,或者后续使用`request.setVersion(version)`进行设置 + +```java +public class GetStoryRequest extends BaseRequest { + @Override + protected String method() { + return "alipay.story.find"; + } +} + +``` + +## 使用方式 + +```java +String url = "http://localhost:8081/api"; // zuul +String appId = "2019032617262200001"; +String privateKey = "你的私钥"; + +// 声明一个就行 +OpenClient client = new OpenClient(url, appId, privateKey); + +// 标准用法 +@Test +public void testGet() { + // 创建请求对象 + GetStoryRequest request = new GetStoryRequest(); + // 请求参数 + GetStoryModel model = new GetStoryModel(); + model.setName("白雪公主"); + + request.setBizModel(model); + + // 发送请求 + GetStoryResponse response = client.execute(request); + + if (response.isSuccess()) { + // 返回结果 + System.out.println(response); + } else { + System.out.println(response); + } +} +``` + +## 使用方式2(懒人版) + +如果不想添加Request,Response,Model。可以用这种方式,返回body部分是字符串,后续自己处理 + +body对应的是alipay_story_find_response部分 + +```java +@Test +public void testLazy() { + // 创建请求对象 + CommonRequest request = new CommonRequest("alipay.story.find"); + // 请求参数 + Map bizModel = new HashMap<>(); + bizModel.put("name", "白雪公主"); + request.setBizModel(bizModel); + + // 发送请求 + CommonResponse response = client.execute(request); + + if (response.isSuccess()) { + // 返回结果,body对应的是alipay_story_find_response部分 + String body = response.getBody(); + JSONObject jsonObject = JSON.parseObject(body); + System.out.println(jsonObject); + } else { + System.out.println(response); + } +} +``` \ No newline at end of file diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenClient.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenClient.java new file mode 100644 index 00000000..5e992c5b --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenClient.java @@ -0,0 +1,123 @@ +package com.gitee.sop.sdk.client; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.gitee.sop.sdk.common.OpenConfig; +import com.gitee.sop.sdk.common.RequestForm; +import com.gitee.sop.sdk.sign.SopSignException; +import com.gitee.sop.sdk.request.BaseRequest; +import com.gitee.sop.sdk.response.BaseResponse; +import com.gitee.sop.sdk.exception.SdkException; +import com.gitee.sop.sdk.sign.SopSignature; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Collections; +import java.util.Map; + +/** + * 请求客户端 + * + * @author tanghc + */ +public class OpenClient { + private static final Log log = LogFactory.getLog(OpenClient.class); + + private static final OpenConfig DEFAULT_CONFIG = new OpenConfig(); + + private static final char DOT = '.'; + private static final char UNDERLINE = '_'; + public static final String GATEWAY_CODE_NAME = "code"; + public static final String GATEWAY_MSG_NAME = "msg"; + public static final String DATA_SUFFIX = "_response"; + + private String url; + private String appKey; + private String privateKey; + + private OpenConfig openConfig; + private OpenRequest openRequest; + + public OpenClient(String url, String appKey, String privateKey) { + this(url, appKey, privateKey, DEFAULT_CONFIG); + } + + public OpenClient(String url, String appKey, String privateKey, OpenConfig openConfig) { + if (openConfig == null) { + throw new IllegalArgumentException("openConfig不能为null"); + } + this.url = url; + this.appKey = appKey; + this.privateKey = privateKey; + this.openConfig = openConfig; + + this.openRequest = new OpenRequest(openConfig); + } + + /** + * 请求接口 + * + * @param request 请求对象 + * @param 返回对应的Response + * @return 返回Response + */ + public T execute(BaseRequest request) { + return this.execute(request, null); + } + + /** + * 请求接口 + * + * @param request 请求对象 + * @param accessToken jwt + * @param 返回对应的Response + * @return 返回Response + */ + public T execute(BaseRequest request, String accessToken) { + RequestForm requestForm = request.createRequestForm(); + // 表单数据 + Map form = requestForm.getForm(); + if (accessToken != null) { + form.put(this.openConfig.getAccessTokenName(), accessToken); + } + form.put(this.openConfig.getAppKeyName(), this.appKey); + + String content = SopSignature.getSignContent(form); + String sign = null; + try { + sign = SopSignature.rsa256Sign(content, privateKey, "utf-8"); + } catch (SopSignException e) { + throw new SdkException("构建签名错误", e); + } + + form.put(this.openConfig.getSignName(), sign); + + String resp = doExecute(this.url, requestForm, Collections.emptyMap()); + if (log.isDebugEnabled()) { + log.debug("----------- 请求信息 -----------" + + "\n请求参数:" + SopSignature.getSignContent(form) + + "\n待签名内容:" + content + + "\n签名(sign):" + sign + + "\n----------- 返回结果 -----------" + + "\n" + resp + ); + } + return this.parseResponse(resp, request); + } + + protected String doExecute(String url, RequestForm requestForm, Map header) { + return openRequest.request(this.url, requestForm, header); + } + + protected T parseResponse(String resp, BaseRequest request) { + String method = request.getMethod(); + String dataName = method.replace(DOT, UNDERLINE) + DATA_SUFFIX; + JSONObject jsonObject = JSON.parseObject(resp); + JSONObject data = jsonObject.getJSONObject(dataName); + T t = data.toJavaObject(request.getResponseClass()); + t.setBody(data.toJSONString()); + return t; + } + + +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenHttp.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenHttp.java new file mode 100644 index 00000000..6ba70b70 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenHttp.java @@ -0,0 +1,148 @@ +package com.gitee.sop.sdk.client; + +import com.gitee.sop.sdk.common.OpenConfig; +import com.gitee.sop.sdk.common.UploadFile; +import okhttp3.Cookie; +import okhttp3.CookieJar; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * @author tanghc + */ +public class OpenHttp { + public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + + private Map> cookieStore = new HashMap>(); + + private OkHttpClient httpClient; + + public OpenHttp(OpenConfig openConfig) { + this.initHttpClient(openConfig); + } + + protected void initHttpClient(OpenConfig openConfig) { + httpClient = new OkHttpClient.Builder() + .connectTimeout(openConfig.getConnectTimeoutSeconds(), TimeUnit.SECONDS) // 设置链接超时时间,默认10秒 + .readTimeout(openConfig.getReadTimeoutSeconds(), TimeUnit.SECONDS) + .cookieJar(new CookieJar() { + public void saveFromResponse(HttpUrl httpUrl, List list) { + cookieStore.put(httpUrl.host(), list); + } + + public List loadForRequest(HttpUrl httpUrl) { + List cookies = cookieStore.get(httpUrl.host()); + return cookies != null ? cookies : new ArrayList(); + } + }).build(); + } + + /** + * get请求 + * + * @param url + * @param header + * @return + * @throws IOException + */ + public String get(String url, Map header) throws IOException { + Request.Builder builder = new Request.Builder().url(url).get(); + // 添加header + addHeader(builder, header); + + Request request = builder.build(); + Response response = httpClient.newCall(request).execute(); + return response.body().string(); + } + + /** + * 提交json字符串到请求体 + * + * @param url + * @param json + * @param header header内容 + * @return + * @throws IOException + */ + public String postJsonBody(String url, String json, Map header) throws IOException { + RequestBody body = RequestBody.create(JSON, json); + Request.Builder builder = new Request.Builder().url(url).post(body); + // 添加header + addHeader(builder, header); + + Request request = builder.build(); + Response response = httpClient.newCall(request).execute(); + return response.body().string(); + } + + /** + * 提交表单,并且上传文件 + * + * @param url + * @param form + * @param header + * @param files + * @return + * @throws IOException + */ + public String postFile(String url, Map form, Map header, List files) + throws IOException { + // 创建MultipartBody.Builder,用于添加请求的数据 + MultipartBody.Builder bodyBuilder = new MultipartBody.Builder(); + bodyBuilder.setType(MultipartBody.FORM); + + for (UploadFile uploadFile : files) { + bodyBuilder.addFormDataPart(uploadFile.getName(), // 请求的名字 + uploadFile.getFileName(), // 文件的文字,服务器端用来解析的 + RequestBody.create(null, uploadFile.getFileData()) // 创建RequestBody,把上传的文件放入 + ); + } + + Set> entrySet = form.entrySet(); + for (Map.Entry entry : entrySet) { + bodyBuilder.addFormDataPart(entry.getKey(), entry.getValue()); + } + + RequestBody requestBody = bodyBuilder.build(); + + Request.Builder builder = new Request.Builder().url(url).post(requestBody); + + // 添加header + addHeader(builder, header); + + Request request = builder.build(); + Response response = httpClient.newCall(request).execute(); + return response.body().string(); + } + + private void addHeader(Request.Builder builder, Map header) { + if (header != null) { + Set> entrySet = header.entrySet(); + for (Map.Entry entry : entrySet) { + builder.addHeader(entry.getKey(), String.valueOf(entry.getValue())); + } + } + } + + public void setCookieStore(Map> cookieStore) { + this.cookieStore = cookieStore; + } + + public void setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + } + +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenRequest.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenRequest.java new file mode 100644 index 00000000..590e3146 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/client/OpenRequest.java @@ -0,0 +1,57 @@ +package com.gitee.sop.sdk.client; + +import com.gitee.sop.sdk.common.OpenConfig; +import com.gitee.sop.sdk.common.RequestForm; +import com.gitee.sop.sdk.common.UploadFile; +import com.gitee.sop.sdk.response.BaseResponse; +import com.gitee.sop.sdk.util.JsonUtil; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * 负责请求操作 + * + * @author tanghc + */ +public class OpenRequest { + + private static final String HTTP_ERROR_CODE = "-400"; + + private OpenHttp openHttp; + + public OpenRequest(OpenConfig openConfig) { + this.openHttp = new OpenHttp(openConfig); + } + + public String request(String url, RequestForm requestForm, Map header) { + return this.doPost(url, requestForm, header); + } + + protected String doPost(String url, RequestForm requestForm, Map header) { + try { + Map form = requestForm.getForm(); + List files = requestForm.getFiles(); + if (files != null && files.size() > 0) { + return openHttp.postFile(url, form, header, files); + } else { + return openHttp.postJsonBody(url, JsonUtil.toJSONString(form), header); + } + } catch (IOException e) { + return this.causeException(e); + } + } + + protected String causeException(Exception e) { + ErrorResponse result = new ErrorResponse(); + result.setCode(HTTP_ERROR_CODE); + result.setSubCode(HTTP_ERROR_CODE); + result.setSubMsg(e.getMessage()); + result.setMsg(e.getMessage()); + return JsonUtil.toJSONString(result); + } + + static class ErrorResponse extends BaseResponse { + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/OpenConfig.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/OpenConfig.java new file mode 100644 index 00000000..6d1e64aa --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/OpenConfig.java @@ -0,0 +1,42 @@ +package com.gitee.sop.sdk.common; + +import lombok.Data; + +/** + * @author tanghc + */ +@Data +public class OpenConfig { + /** 成功返回码值 */ + private String successCode = SdkConfig.SUCCESS_CODE; + /** 默认版本号 */ + private String defaultVersion = SdkConfig.DEFAULT_VERSION; + /** 接口属性名 */ + private String apiName = "method"; + /** 版本号名称 */ + private String versionName = "version"; + /** appKey名称 */ + private String appKeyName = "app_id"; + /** data名称 */ + private String dataName = "biz_content"; + /** 时间戳名称 */ + private String timestampName = "timestamp"; + /** 时间戳格式 */ + private String timestampPattern = "yyyy-MM-dd HH:mm:ss"; + /** 签名串名称 */ + private String signName = "sign"; + /** 格式化名称 */ + private String formatName = "format"; + /** 格式类型 */ + private String formatType = "json"; + /** accessToken名称 */ + private String accessTokenName = "app_auth_token"; + /** 国际化语言 */ + private String locale = "zh-CN"; + /** 响应code名称 */ + private String responseCodeName = "code"; + /** 请求超时时间 */ + private int connectTimeoutSeconds = 10; + /** http读取超时时间 */ + private int readTimeoutSeconds = 10; +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/RequestForm.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/RequestForm.java new file mode 100644 index 00000000..e981fe53 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/RequestForm.java @@ -0,0 +1,22 @@ +package com.gitee.sop.sdk.common; + +import lombok.Getter; +import lombok.Setter; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Getter +@Setter +public class RequestForm { + + /** 请求表单内容 */ + private Map form; + /** 上传文件 */ + private List files; + + public RequestForm(Map m) { + this.form = m; + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/SdkConfig.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/SdkConfig.java new file mode 100644 index 00000000..573a949d --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/SdkConfig.java @@ -0,0 +1,16 @@ +package com.gitee.sop.sdk.common; + +public class SdkConfig { + + public static String SUCCESS_CODE = "10000"; + + public static String DEFAULT_VERSION = "1.0"; + + public static String FORMAT_TYPE = "json"; + + public static String TIMESTAMP_PATTERN = "yyyy-MM-dd HH:mm:ss"; + + public static String CHARSET = "UTF-8"; + + public static String SIGN_TYPE = "RSA2"; +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/UploadFile.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/UploadFile.java new file mode 100644 index 00000000..b616593b --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/common/UploadFile.java @@ -0,0 +1,88 @@ +package com.gitee.sop.sdk.common; + + +import com.gitee.sop.sdk.util.FileUtil; +import com.gitee.sop.sdk.util.MD5Util; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; + +/** + * 文件上传类 + * @author tanghc + */ +public class UploadFile implements Serializable { + private static final long serialVersionUID = -1100614660944996398L; + + /** + * @param name 表单名称,不能重复 + * @param file 文件 + * @throws IOException + */ + public UploadFile(String name, File file) throws IOException { + this(name, file.getName(), FileUtil.toBytes(file)); + } + + /** + * @param name 表单名称,不能重复 + * @param fileName 文件名 + * @param input 文件流 + * @throws IOException + */ + public UploadFile(String name, String fileName, InputStream input) throws IOException { + this(name, fileName, FileUtil.toBytes(input)); + } + + /** + * @param name 表单名称,不能重复 + * @param fileName 文件名 + * @param fileData 文件数据 + */ + public UploadFile(String name, String fileName, byte[] fileData) { + super(); + this.name = name; + this.fileName = fileName; + this.fileData = fileData; + this.md5 = MD5Util.encrypt(fileData); + } + + private String name; + private String fileName; + private byte[] fileData; + private String md5; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public byte[] getFileData() { + return fileData; + } + + public void setFileData(byte[] fileData) { + this.fileData = fileData; + } + + public String getMd5() { + return md5; + } + + public void setMd5(String md5) { + this.md5 = md5; + } + +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/entity/Goods.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/entity/Goods.java new file mode 100644 index 00000000..023ecbbe --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/entity/Goods.java @@ -0,0 +1,40 @@ +package com.gitee.sop.sdk.entity; + +import java.math.BigDecimal; + +public class Goods { + + private Long id; + private String goods_name; + private BigDecimal price; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getGoods_name() { + return goods_name; + } + + public void setGoods_name(String goods_name) { + this.goods_name = goods_name; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + @Override + public String toString() { + return "Goods [id=" + id + ", goods_name=" + goods_name + ", price=" + price + "]"; + } + +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/exception/SdkException.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/exception/SdkException.java new file mode 100644 index 00000000..01761ced --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/exception/SdkException.java @@ -0,0 +1,14 @@ +package com.gitee.sop.sdk.exception; + +public class SdkException extends RuntimeException { + + private static final long serialVersionUID = -1108392076700488161L; + + public SdkException(String message) { + super(message); + } + + public SdkException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/model/GetStoryModel.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/model/GetStoryModel.java new file mode 100644 index 00000000..b7ab8bb4 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/model/GetStoryModel.java @@ -0,0 +1,11 @@ +package com.gitee.sop.sdk.model; + +import com.alibaba.fastjson.annotation.JSONField; +import lombok.Data; + +@Data +public class GetStoryModel { + + @JSONField(name = "name") + private String name; +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/request/BaseRequest.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/request/BaseRequest.java new file mode 100644 index 00000000..dcbfd443 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/request/BaseRequest.java @@ -0,0 +1,123 @@ +package com.gitee.sop.sdk.request; + +import com.alibaba.fastjson.JSON; +import com.gitee.sop.sdk.common.RequestForm; +import com.gitee.sop.sdk.common.SdkConfig; +import com.gitee.sop.sdk.common.UploadFile; +import com.gitee.sop.sdk.response.BaseResponse; +import com.gitee.sop.sdk.util.ClassUtil; +import lombok.Getter; +import lombok.Setter; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 请求对象父类,后续请求对象都要继承这个类 + *

+ * 参数 类型 是否必填 最大长度 描述 示例值 + * app_id String 是 32 支付宝分配给开发者的应用ID 2014072300007148 + * method String 是 128 接口名称 alipay.trade.fastpay.refund.query + * format String 否 40 仅支持JSON JSON + * charset String 是 10 请求使用的编码格式,如utf-8,gbk,gb2312等 utf-8 + * sign_type String 是 10 商户生成签名字符串所使用的签名算法类型,目前支持RSA2和RSA,推荐使用RSA2 RSA2 + * sign String 是 344 商户请求参数的签名串,详见签名 详见示例 + * timestamp String 是 19 发送请求的时间,格式"yyyy-MM-dd HH:mm:ss" 2014-07-24 03:07:50 + * version String 是 3 调用的接口版本,固定为:1.0 1.0 + * app_auth_token String 否 40 详见应用授权概述 + * biz_content String 是 请求参数的集合,最大长度不限,除公共参数外所有请求参数都必须放在这个参数中传递,具体参照各产品快速接入文档 + * + * @param 对应的Response对象 + */ +public abstract class BaseRequest { + + private String method; + private String format = SdkConfig.FORMAT_TYPE; + private String charset = SdkConfig.CHARSET; + private String signType = SdkConfig.SIGN_TYPE; + private String timestamp = new SimpleDateFormat(SdkConfig.TIMESTAMP_PATTERN).format(new Date()); + private String version; + + private String bizContent; + private Object bizModel; + + /** + * 上传文件 + */ + private List files; + + private Class responseClass; + + protected abstract String method(); + + @SuppressWarnings("unchecked") + public BaseRequest() { + this.method = this.method(); + this.version = this.version(); + + this.responseClass = (Class) ClassUtil.getSuperClassGenricType(this.getClass(), 0); + } + + protected String version() { + return SdkConfig.DEFAULT_VERSION; + } + + public RequestForm createRequestForm() { + // 公共请求参数 + Map params = new HashMap(); + params.put("method", this.method); + params.put("format", this.format); + params.put("charset", this.charset); + params.put("sign_type", this.signType); + params.put("timestamp", this.timestamp); + params.put("version", this.version); + + // 业务参数 + String biz_content = buildBizContent(); + + params.put("biz_content", biz_content); + + RequestForm requestForm = new RequestForm(params); + requestForm.setFiles(this.files); + return requestForm; + } + + protected String buildBizContent() { + if (bizModel != null) { + return JSON.toJSONString(bizModel); + } else { + return this.bizContent; + } + } + + public String getMethod() { + return method; + } + + protected void setMethod(String method) { + this.method = method; + } + + public void setVersion(String version) { + this.version = version; + } + + public void setBizContent(String bizContent) { + this.bizContent = bizContent; + } + + public void setBizModel(Object bizModel) { + this.bizModel = bizModel; + } + + public void setFiles(List files) { + this.files = files; + } + + public Class getResponseClass() { + return responseClass; + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/request/CommonRequest.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/request/CommonRequest.java new file mode 100644 index 00000000..8373e862 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/request/CommonRequest.java @@ -0,0 +1,23 @@ +package com.gitee.sop.sdk.request; + +import com.gitee.sop.sdk.response.CommonResponse; + +/** + * @author tanghc + */ +public class CommonRequest extends BaseRequest { + + public CommonRequest(String method) { + this.setMethod(method); + } + + public CommonRequest(String method, String version) { + this.setMethod(method); + this.setVersion(version); + } + + @Override + protected String method() { + return ""; + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/request/GetStoryRequest.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/request/GetStoryRequest.java new file mode 100644 index 00000000..7db3c3b9 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/request/GetStoryRequest.java @@ -0,0 +1,10 @@ +package com.gitee.sop.sdk.request; + +import com.gitee.sop.sdk.response.GetStoryResponse; + +public class GetStoryRequest extends BaseRequest { + @Override + protected String method() { + return "alipay.story.find"; + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/response/BaseResponse.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/response/BaseResponse.java new file mode 100644 index 00000000..4fbf5af7 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/response/BaseResponse.java @@ -0,0 +1,38 @@ +package com.gitee.sop.sdk.response; + +import com.alibaba.fastjson.annotation.JSONField; +import com.gitee.sop.sdk.sign.StringUtils; +import lombok.Getter; +import lombok.Setter; + +/** + * 返回对象,后续返回对象都要继承这个类 + * { + * "alipay_trade_close_response": { + * "code": "20000", + * "msg": "Service Currently Unavailable", + * "sub_code": "isp.unknow-error", + * "sub_msg": "系统繁忙" + * }, + * "sign": "ERITJKEIJKJHKKKKKKKHJEREEEEEEEEEEE" + * } + * + */ +@Setter +@Getter +public abstract class BaseResponse { + + private String code; + private String msg; + @JSONField(name = "sub_code") + private String subCode; + @JSONField(name = "sub_msg") + private String subMsg; + private String body; + + public boolean isSuccess() { + return StringUtils.isEmpty(subCode); + } + + +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/response/CommonResponse.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/response/CommonResponse.java new file mode 100644 index 00000000..d0b62675 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/response/CommonResponse.java @@ -0,0 +1,10 @@ +package com.gitee.sop.sdk.response; + +import java.util.Map; + +/** + * @author tanghc + */ +public class CommonResponse extends BaseResponse { + +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/response/GetStoryResponse.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/response/GetStoryResponse.java new file mode 100644 index 00000000..524b96e2 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/response/GetStoryResponse.java @@ -0,0 +1,12 @@ +package com.gitee.sop.sdk.response; + +import lombok.Data; + +import java.util.Date; + +@Data +public class GetStoryResponse extends BaseResponse { + private Long id; + private String name; + private Date gmtCreate; +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/SopSignException.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/SopSignException.java new file mode 100644 index 00000000..0782ee12 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/SopSignException.java @@ -0,0 +1,49 @@ +/** + * Alipay.com Inc. + * Copyright (c) 2004-2012 All Rights Reserved. + */ +package com.gitee.sop.sdk.sign; + + +/** + * + * @author runzhi + */ +public class SopSignException extends Exception { + + private static final long serialVersionUID = -238091758285157331L; + + private String errCode; + private String errMsg; + + public SopSignException() { + super(); + } + + public SopSignException(String message, Throwable cause) { + super(message, cause); + } + + public SopSignException(String message) { + super(message); + } + + public SopSignException(Throwable cause) { + super(cause); + } + + public SopSignException(String errCode, String errMsg) { + super(errCode + ":" + errMsg); + this.errCode = errCode; + this.errMsg = errMsg; + } + + public String getErrCode() { + return this.errCode; + } + + public String getErrMsg() { + return this.errMsg; + } + +} \ No newline at end of file diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/SopSignature.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/SopSignature.java new file mode 100644 index 00000000..c1c0fb72 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/SopSignature.java @@ -0,0 +1,621 @@ +package com.gitee.sop.sdk.sign; + + + +import com.gitee.sop.sdk.util.Base64Util; + +import javax.crypto.Cipher; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * + * @author runzhi + */ +public class SopSignature { + + /** RSA最大加密明文大小 */ + private static final int MAX_ENCRYPT_BLOCK = 117; + + /** RSA最大解密密文大小 */ + private static final int MAX_DECRYPT_BLOCK = 128; + + public static final String SIGN_TYPE_RSA = "RSA"; + + /** + * sha256WithRsa 算法请求类型 + */ + public static final String SIGN_TYPE_RSA2 = "RSA2"; + + public static final String SIGN_ALGORITHMS = "SHA1WithRSA"; + + public static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA"; + + /** GBK字符集 **/ + public static final String CHARSET_GBK = "GBK"; + + + /** + * + * @param sortedParams + * @return + */ + public static String getSignContent(Map sortedParams) { + StringBuffer content = new StringBuffer(); + List keys = new ArrayList(sortedParams.keySet()); + Collections.sort(keys); + int index = 0; + for (int i = 0; i < keys.size(); i++) { + String key = keys.get(i); + String value = sortedParams.get(key); + if (StringUtils.areNotEmpty(key, value)) { + content.append((index == 0 ? "" : "&") + key + "=" + value); + index++; + } + } + return content.toString(); + } + + /** + * rsa内容签名 + * + * @param content + * @param privateKey + * @param charset + * @return + * @throws SopSignException + */ + public static String rsaSign(String content, String privateKey, String charset, + String signType) throws SopSignException { + + if (SIGN_TYPE_RSA.equals(signType)) { + + return rsaSign(content, privateKey, charset); + } else if (SIGN_TYPE_RSA2.equals(signType)) { + + return rsa256Sign(content, privateKey, charset); + } else { + + throw new SopSignException("Sign Type is Not Support : signType=" + signType); + } + + } + + /** + * sha256WithRsa 加签 + * + * @param content + * @param privateKey + * @param charset + * @return + * @throws SopSignException + */ + public static String rsa256Sign(String content, String privateKey, + String charset) throws SopSignException { + + try { + PrivateKey priKey = getPrivateKeyFromPKCS8(SIGN_TYPE_RSA, + new ByteArrayInputStream(privateKey.getBytes())); + + java.security.Signature signature = java.security.Signature + .getInstance(SIGN_SHA256RSA_ALGORITHMS); + + signature.initSign(priKey); + + if (StringUtils.isEmpty(charset)) { + signature.update(content.getBytes()); + } else { + signature.update(content.getBytes(charset)); + } + + byte[] signed = signature.sign(); + + return new String(Base64Util.encodeBase64(signed)); + } catch (Exception e) { + throw new SopSignException("RSAcontent = " + content + "; charset = " + charset, e); + } + + } + + /** + * sha1WithRsa 加签 + * + * @param content + * @param privateKey + * @param charset + * @return + * @throws SopSignException + */ + public static String rsaSign(String content, String privateKey, + String charset) throws SopSignException { + try { + PrivateKey priKey = getPrivateKeyFromPKCS8(SIGN_TYPE_RSA, + new ByteArrayInputStream(privateKey.getBytes())); + + java.security.Signature signature = java.security.Signature + .getInstance(SIGN_ALGORITHMS); + + signature.initSign(priKey); + + if (StringUtils.isEmpty(charset)) { + signature.update(content.getBytes()); + } else { + signature.update(content.getBytes(charset)); + } + + byte[] signed = signature.sign(); + + return new String(Base64Util.encodeBase64(signed)); + } catch (InvalidKeySpecException ie) { + throw new SopSignException("RSA私钥格式不正确,请检查是否正确配置了PKCS8格式的私钥", ie); + } catch (Exception e) { + throw new SopSignException("RSAcontent = " + content + "; charset = " + charset, e); + } + } + + public static String rsaSign(Map params, String privateKey, + String charset) throws SopSignException { + String signContent = getSignContent(params); + + return rsaSign(signContent, privateKey, charset); + + } + + public static PrivateKey getPrivateKeyFromPKCS8(String algorithm, + InputStream ins) throws Exception { + if (ins == null || StringUtils.isEmpty(algorithm)) { + return null; + } + + KeyFactory keyFactory = KeyFactory.getInstance(algorithm); + + byte[] encodedKey = StreamUtil.readText(ins).getBytes(); + + encodedKey = Base64Util.decodeBase64(encodedKey); + + return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey)); + } + + public static String getSignCheckContentV1(Map params) { + if (params == null) { + return null; + } + + params.remove("sign"); + params.remove("sign_type"); + + StringBuffer content = new StringBuffer(); + List keys = new ArrayList(params.keySet()); + Collections.sort(keys); + + for (int i = 0; i < keys.size(); i++) { + String key = keys.get(i); + String value = params.get(key); + content.append((i == 0 ? "" : "&") + key + "=" + value); + } + + return content.toString(); + } + + public static String getSignCheckContentV2(Map params) { + if (params == null) { + return null; + } + + params.remove("sign"); + + StringBuffer content = new StringBuffer(); + List keys = new ArrayList(params.keySet()); + Collections.sort(keys); + + for (int i = 0; i < keys.size(); i++) { + String key = keys.get(i); + String value = params.get(key); + content.append((i == 0 ? "" : "&") + key + "=" + value); + } + + return content.toString(); + } + + public static boolean rsaCheckV1(Map params, String publicKey, + String charset) throws SopSignException { + String sign = params.get("sign"); + String content = getSignCheckContentV1(params); + + return rsaCheckContent(content, sign, publicKey, charset); + } + + public static boolean rsaCheckV1(Map params, String publicKey, + String charset,String signType) throws SopSignException { + String sign = params.get("sign"); + String content = getSignCheckContentV1(params); + + return rsaCheck(content, sign, publicKey, charset,signType); + } + + public static boolean rsaCheckV2(Map params, String publicKey, + String charset) throws SopSignException { + String sign = params.get("sign"); + String content = getSignCheckContentV2(params); + + return rsaCheckContent(content, sign, publicKey, charset); + } + + public static boolean rsaCheckV2(Map params, String publicKey, + String charset,String signType) throws SopSignException { + String sign = params.get("sign"); + String content = getSignCheckContentV2(params); + + return rsaCheck(content, sign, publicKey, charset,signType); + } + + public static boolean rsaCheck(String content, String sign, String publicKey, String charset, + String signType) throws SopSignException { + + if (SIGN_TYPE_RSA.equals(signType)) { + + return rsaCheckContent(content, sign, publicKey, charset); + + } else if (SIGN_TYPE_RSA2.equals(signType)) { + + return rsa256CheckContent(content, sign, publicKey, charset); + + } else { + + throw new SopSignException("Sign Type is Not Support : signType=" + signType); + } + + } + + public static boolean rsa256CheckContent(String content, String sign, String publicKey, + String charset) throws SopSignException { + try { + PublicKey pubKey = getPublicKeyFromX509("RSA", + new ByteArrayInputStream(publicKey.getBytes())); + + java.security.Signature signature = java.security.Signature + .getInstance(SIGN_SHA256RSA_ALGORITHMS); + + signature.initVerify(pubKey); + + if (StringUtils.isEmpty(charset)) { + signature.update(content.getBytes()); + } else { + signature.update(content.getBytes(charset)); + } + + return signature.verify(Base64Util.decodeBase64(sign.getBytes())); + } catch (Exception e) { + throw new SopSignException( + "RSAcontent = " + content + ",sign=" + sign + ",charset = " + charset, e); + } + } + + public static boolean rsaCheckContent(String content, String sign, String publicKey, + String charset) throws SopSignException { + try { + PublicKey pubKey = getPublicKeyFromX509("RSA", + new ByteArrayInputStream(publicKey.getBytes())); + + java.security.Signature signature = java.security.Signature + .getInstance(SIGN_ALGORITHMS); + + signature.initVerify(pubKey); + + if (StringUtils.isEmpty(charset)) { + signature.update(content.getBytes()); + } else { + signature.update(content.getBytes(charset)); + } + + return signature.verify(Base64Util.decodeBase64(sign.getBytes())); + } catch (Exception e) { + throw new SopSignException( + "RSAcontent = " + content + ",sign=" + sign + ",charset = " + charset, e); + } + } + + public static PublicKey getPublicKeyFromX509(String algorithm, + InputStream ins) throws Exception { + KeyFactory keyFactory = KeyFactory.getInstance(algorithm); + + StringWriter writer = new StringWriter(); + StreamUtil.io(new InputStreamReader(ins), writer); + + byte[] encodedKey = writer.toString().getBytes(); + + encodedKey = Base64Util.decodeBase64(encodedKey); + + return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); + } + + /** + * 验签并解密 + *

+ * 目前适用于公众号
+ * params参数示例: + *
{ + *
biz_content=M0qGiGz+8kIpxe8aF4geWJdBn0aBTuJRQItLHo9R7o5JGhpic/MIUjvXo2BLB++BbkSq2OsJCEQFDZ0zK5AJYwvBgeRX30gvEj6eXqXRt16/IkB9HzAccEqKmRHrZJ7PjQWE0KfvDAHsJqFIeMvEYk1Zei2QkwSQPlso7K0oheo/iT+HYE8aTATnkqD/ByD9iNDtGg38pCa2xnnns63abKsKoV8h0DfHWgPH62urGY7Pye3r9FCOXA2Ykm8X4/Bl1bWFN/PFCEJHWe/HXj8KJKjWMO6ttsoV0xRGfeyUO8agu6t587Dl5ux5zD/s8Lbg5QXygaOwo3Fz1G8EqmGhi4+soEIQb8DBYanQOS3X+m46tVqBGMw8Oe+hsyIMpsjwF4HaPKMr37zpW3fe7xOMuimbZ0wq53YP/jhQv6XWodjT3mL0H5ACqcsSn727B5ztquzCPiwrqyjUHjJQQefFTzOse8snaWNQTUsQS7aLsHq0FveGpSBYORyA90qPdiTjXIkVP7mAiYiAIWW9pCEC7F3XtViKTZ8FRMM9ySicfuAlf3jtap6v2KPMtQv70X+hlmzO/IXB6W0Ep8DovkF5rB4r/BJYJLw/6AS0LZM9w5JfnAZhfGM2rKzpfNsgpOgEZS1WleG4I2hoQC0nxg9IcP0Hs+nWIPkEUcYNaiXqeBc=, + *
sign=rlqgA8O+RzHBVYLyHmrbODVSANWPXf3pSrr82OCO/bm3upZiXSYrX5fZr6UBmG6BZRAydEyTIguEW6VRuAKjnaO/sOiR9BsSrOdXbD5Rhos/Xt7/mGUWbTOt/F+3W0/XLuDNmuYg1yIC/6hzkg44kgtdSTsQbOC9gWM7ayB4J4c=, + * sign_type=RSA, + *
charset=UTF-8 + *
} + *

+ * @param params + * @param alipayPublicKey 支付宝公钥 + * @param cusPrivateKey 商户私钥 + * @param isCheckSign 是否验签 + * @param isDecrypt 是否解密 + * @return 解密后明文,验签失败则异常抛出 + * @throws SopSignException + */ + public static String checkSignAndDecrypt(Map params, String alipayPublicKey, + String cusPrivateKey, boolean isCheckSign, + boolean isDecrypt) throws SopSignException { + String charset = params.get("charset"); + String bizContent = params.get("biz_content"); + if (isCheckSign) { + if (!rsaCheckV2(params, alipayPublicKey, charset)) { + throw new SopSignException("rsaCheck failure:rsaParams=" + params); + } + } + + if (isDecrypt) { + return rsaDecrypt(bizContent, cusPrivateKey, charset); + } + + return bizContent; + } + + /** + * 验签并解密 + *

+ * 目前适用于公众号
+ * params参数示例: + *
{ + *
biz_content=M0qGiGz+8kIpxe8aF4geWJdBn0aBTuJRQItLHo9R7o5JGhpic/MIUjvXo2BLB++BbkSq2OsJCEQFDZ0zK5AJYwvBgeRX30gvEj6eXqXRt16/IkB9HzAccEqKmRHrZJ7PjQWE0KfvDAHsJqFIeMvEYk1Zei2QkwSQPlso7K0oheo/iT+HYE8aTATnkqD/ByD9iNDtGg38pCa2xnnns63abKsKoV8h0DfHWgPH62urGY7Pye3r9FCOXA2Ykm8X4/Bl1bWFN/PFCEJHWe/HXj8KJKjWMO6ttsoV0xRGfeyUO8agu6t587Dl5ux5zD/s8Lbg5QXygaOwo3Fz1G8EqmGhi4+soEIQb8DBYanQOS3X+m46tVqBGMw8Oe+hsyIMpsjwF4HaPKMr37zpW3fe7xOMuimbZ0wq53YP/jhQv6XWodjT3mL0H5ACqcsSn727B5ztquzCPiwrqyjUHjJQQefFTzOse8snaWNQTUsQS7aLsHq0FveGpSBYORyA90qPdiTjXIkVP7mAiYiAIWW9pCEC7F3XtViKTZ8FRMM9ySicfuAlf3jtap6v2KPMtQv70X+hlmzO/IXB6W0Ep8DovkF5rB4r/BJYJLw/6AS0LZM9w5JfnAZhfGM2rKzpfNsgpOgEZS1WleG4I2hoQC0nxg9IcP0Hs+nWIPkEUcYNaiXqeBc=, + *
sign=rlqgA8O+RzHBVYLyHmrbODVSANWPXf3pSrr82OCO/bm3upZiXSYrX5fZr6UBmG6BZRAydEyTIguEW6VRuAKjnaO/sOiR9BsSrOdXbD5Rhos/Xt7/mGUWbTOt/F+3W0/XLuDNmuYg1yIC/6hzkg44kgtdSTsQbOC9gWM7ayB4J4c=, + * sign_type=RSA, + *
charset=UTF-8 + *
} + *

+ * @param params + * @param alipayPublicKey 支付宝公钥 + * @param cusPrivateKey 商户私钥 + * @param isCheckSign 是否验签 + * @param isDecrypt 是否解密 + * @return 解密后明文,验签失败则异常抛出 + * @throws SopSignException + */ + public static String checkSignAndDecrypt(Map params, String alipayPublicKey, + String cusPrivateKey, boolean isCheckSign, + boolean isDecrypt, String signType) throws SopSignException { + String charset = params.get("charset"); + String bizContent = params.get("biz_content"); + if (isCheckSign) { + if (!rsaCheckV2(params, alipayPublicKey, charset,signType)) { + throw new SopSignException("rsaCheck failure:rsaParams=" + params); + } + } + + if (isDecrypt) { + return rsaDecrypt(bizContent, cusPrivateKey, charset); + } + + return bizContent; + } + + /** + * 加密并签名
+ * 目前适用于公众号 + * @param bizContent 待加密、签名内容 + * @param alipayPublicKey 支付宝公钥 + * @param cusPrivateKey 商户私钥 + * @param charset 字符集,如UTF-8, GBK, GB2312 + * @param isEncrypt 是否加密,true-加密 false-不加密 + * @param isSign 是否签名,true-签名 false-不签名 + * @return 加密、签名后xml内容字符串 + *

+ * 返回示例: + * + * 密文 + * RSA + * sign + * RSA + * + *

+ * @throws SopSignException + */ + public static String encryptAndSign(String bizContent, String alipayPublicKey, + String cusPrivateKey, String charset, boolean isEncrypt, + boolean isSign) throws SopSignException { + StringBuilder sb = new StringBuilder(); + if (StringUtils.isEmpty(charset)) { + charset = CHARSET_GBK; + } + sb.append(""); + if (isEncrypt) {// 加密 + sb.append(""); + String encrypted = rsaEncrypt(bizContent, alipayPublicKey, charset); + sb.append("" + encrypted + ""); + sb.append("RSA"); + if (isSign) { + String sign = rsaSign(encrypted, cusPrivateKey, charset); + sb.append("" + sign + ""); + sb.append("RSA"); + } + sb.append(""); + } else if (isSign) {// 不加密,但需要签名 + sb.append(""); + sb.append("" + bizContent + ""); + String sign = rsaSign(bizContent, cusPrivateKey, charset); + sb.append("" + sign + ""); + sb.append("RSA"); + sb.append(""); + } else {// 不加密,不加签 + sb.append(bizContent); + } + return sb.toString(); + } + + /** + * 加密并签名
+ * 目前适用于公众号 + * @param bizContent 待加密、签名内容 + * @param alipayPublicKey 支付宝公钥 + * @param cusPrivateKey 商户私钥 + * @param charset 字符集,如UTF-8, GBK, GB2312 + * @param isEncrypt 是否加密,true-加密 false-不加密 + * @param isSign 是否签名,true-签名 false-不签名 + * @return 加密、签名后xml内容字符串 + *

+ * 返回示例: + * + * 密文 + * RSA + * sign + * RSA + * + *

+ * @throws SopSignException + */ + public static String encryptAndSign(String bizContent, String alipayPublicKey, + String cusPrivateKey, String charset, boolean isEncrypt, + boolean isSign,String signType) throws SopSignException { + StringBuilder sb = new StringBuilder(); + if (StringUtils.isEmpty(charset)) { + charset = CHARSET_GBK; + } + sb.append(""); + if (isEncrypt) {// 加密 + sb.append(""); + String encrypted = rsaEncrypt(bizContent, alipayPublicKey, charset); + sb.append("" + encrypted + ""); + sb.append("RSA"); + if (isSign) { + String sign = rsaSign(encrypted, cusPrivateKey, charset, signType); + sb.append("" + sign + ""); + sb.append(""); + sb.append(signType); + sb.append(""); + } + sb.append(""); + } else if (isSign) {// 不加密,但需要签名 + sb.append(""); + sb.append("" + bizContent + ""); + String sign = rsaSign(bizContent, cusPrivateKey, charset, signType); + sb.append("" + sign + ""); + sb.append(""); + sb.append(signType); + sb.append(""); + sb.append(""); + } else {// 不加密,不加签 + sb.append(bizContent); + } + return sb.toString(); + } + + /** + * 公钥加密 + * + * @param content 待加密内容 + * @param publicKey 公钥 + * @param charset 字符集,如UTF-8, GBK, GB2312 + * @return 密文内容 + * @throws SopSignException + */ + public static String rsaEncrypt(String content, String publicKey, + String charset) throws SopSignException { + try { + PublicKey pubKey = getPublicKeyFromX509(SIGN_TYPE_RSA, + new ByteArrayInputStream(publicKey.getBytes())); + Cipher cipher = Cipher.getInstance(SIGN_TYPE_RSA); + cipher.init(Cipher.ENCRYPT_MODE, pubKey); + byte[] data = StringUtils.isEmpty(charset) ? content.getBytes() + : content.getBytes(charset); + int inputLen = data.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // 对数据分段加密 + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_ENCRYPT_BLOCK; + } + byte[] encryptedData = Base64Util.encodeBase64(out.toByteArray()); + out.close(); + + return StringUtils.isEmpty(charset) ? new String(encryptedData) + : new String(encryptedData, charset); + } catch (Exception e) { + throw new SopSignException("EncryptContent = " + content + ",charset = " + charset, + e); + } + } + + /** + * 私钥解密 + * + * @param content 待解密内容 + * @param privateKey 私钥 + * @param charset 字符集,如UTF-8, GBK, GB2312 + * @return 明文内容 + * @throws SopSignException + */ + public static String rsaDecrypt(String content, String privateKey, + String charset) throws SopSignException { + try { + PrivateKey priKey = getPrivateKeyFromPKCS8(SIGN_TYPE_RSA, + new ByteArrayInputStream(privateKey.getBytes())); + Cipher cipher = Cipher.getInstance(SIGN_TYPE_RSA); + cipher.init(Cipher.DECRYPT_MODE, priKey); + byte[] encryptedData = StringUtils.isEmpty(charset) + ? Base64Util.decodeBase64(content.getBytes()) + : Base64Util.decodeBase64(content.getBytes(charset)); + int inputLen = encryptedData.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // 对数据分段解密 + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_DECRYPT_BLOCK) { + cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); + } else { + cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_DECRYPT_BLOCK; + } + byte[] decryptedData = out.toByteArray(); + out.close(); + + return StringUtils.isEmpty(charset) ? new String(decryptedData) + : new String(decryptedData, charset); + } catch (Exception e) { + throw new SopSignException("EncodeContent = " + content + ",charset = " + charset, e); + } + } + +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/StreamUtil.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/StreamUtil.java new file mode 100644 index 00000000..6ef676af --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/StreamUtil.java @@ -0,0 +1,135 @@ +package com.gitee.sop.sdk.sign; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.io.StringWriter; +import java.io.Writer; + +/** + * + * @author runzhi + */ +public class StreamUtil { + private static final int DEFAULT_BUFFER_SIZE = 8192; + + public static void io(InputStream in, OutputStream out) throws IOException { + io(in, out, -1); + } + + public static void io(InputStream in, OutputStream out, int bufferSize) throws IOException { + if (bufferSize == -1) { + bufferSize = DEFAULT_BUFFER_SIZE; + } + + byte[] buffer = new byte[bufferSize]; + int amount; + + while ((amount = in.read(buffer)) >= 0) { + out.write(buffer, 0, amount); + } + } + + public static void io(Reader in, Writer out) throws IOException { + io(in, out, -1); + } + + public static void io(Reader in, Writer out, int bufferSize) throws IOException { + if (bufferSize == -1) { + bufferSize = DEFAULT_BUFFER_SIZE >> 1; + } + + char[] buffer = new char[bufferSize]; + int amount; + + while ((amount = in.read(buffer)) >= 0) { + out.write(buffer, 0, amount); + } + } + + public static OutputStream synchronizedOutputStream(OutputStream out) { + return new SynchronizedOutputStream(out); + } + + public static OutputStream synchronizedOutputStream(OutputStream out, Object lock) { + return new SynchronizedOutputStream(out, lock); + } + + public static String readText(InputStream in) throws IOException { + return readText(in, null, -1); + } + + public static String readText(InputStream in, String encoding) throws IOException { + return readText(in, encoding, -1); + } + + public static String readText(InputStream in, String encoding, int bufferSize) + throws IOException { + Reader reader = (encoding == null) ? new InputStreamReader(in) : new InputStreamReader(in, + encoding); + + return readText(reader, bufferSize); + } + + public static String readText(Reader reader) throws IOException { + return readText(reader, -1); + } + + public static String readText(Reader reader, int bufferSize) throws IOException { + StringWriter writer = new StringWriter(); + + io(reader, writer, bufferSize); + return writer.toString(); + } + + private static class SynchronizedOutputStream extends OutputStream { + private OutputStream out; + private Object lock; + + SynchronizedOutputStream(OutputStream out) { + this(out, out); + } + + SynchronizedOutputStream(OutputStream out, Object lock) { + this.out = out; + this.lock = lock; + } + + @Override + public void write(int datum) throws IOException { + synchronized (lock) { + out.write(datum); + } + } + + @Override + public void write(byte[] data) throws IOException { + synchronized (lock) { + out.write(data); + } + } + + @Override + public void write(byte[] data, int offset, int length) throws IOException { + synchronized (lock) { + out.write(data, offset, length); + } + } + + @Override + public void flush() throws IOException { + synchronized (lock) { + out.flush(); + } + } + + @Override + public void close() throws IOException { + synchronized (lock) { + out.close(); + } + } + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/StringUtils.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/StringUtils.java new file mode 100644 index 00000000..3cda1608 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/sign/StringUtils.java @@ -0,0 +1,171 @@ +package com.gitee.sop.sdk.sign; + +/** + * 字符串工具类。 + * + * @author carver.gu + * @since 1.0, Sep 12, 2009 + */ +public abstract class StringUtils { + + private StringUtils() {} + + /** + * 检查指定的字符串是否为空。 + *
    + *
  • SysUtils.isEmpty(null) = true
  • + *
  • SysUtils.isEmpty("") = true
  • + *
  • SysUtils.isEmpty(" ") = true
  • + *
  • SysUtils.isEmpty("abc") = false
  • + *
+ * + * @param value 待检查的字符串 + * @return true/false + */ + public static boolean isEmpty(String value) { + int strLen; + if (value == null || (strLen = value.length()) == 0) { + return true; + } + for (int i = 0; i < strLen; i++) { + if ((Character.isWhitespace(value.charAt(i)) == false)) { + return false; + } + } + return true; + } + + /** + * 检查对象是否为数字型字符串,包含负数开头的。 + */ + public static boolean isNumeric(Object obj) { + if (obj == null) { + return false; + } + char[] chars = obj.toString().toCharArray(); + int length = chars.length; + if(length < 1) { + return false; + } + + int i = 0; + if(length > 1 && chars[0] == '-') { + i = 1; + } + + for (; i < length; i++) { + if (!Character.isDigit(chars[i])) { + return false; + } + } + return true; + } + + /** + * 检查指定的字符串列表是否不为空。 + */ + public static boolean areNotEmpty(String... values) { + boolean result = true; + if (values == null || values.length == 0) { + result = false; + } else { + for (String value : values) { + result &= !isEmpty(value); + } + } + return result; + } + + /** + * 把通用字符编码的字符串转化为汉字编码。 + */ + public static String unicodeToChinese(String unicode) { + StringBuilder out = new StringBuilder(); + if (!isEmpty(unicode)) { + for (int i = 0; i < unicode.length(); i++) { + out.append(unicode.charAt(i)); + } + } + return out.toString(); + } + + /** + * 过滤不可见字符 + */ + public static String stripNonValidXMLCharacters(String input) { + if (input == null || ("".equals(input))) { + return ""; + } + StringBuilder out = new StringBuilder(); + char current; + for (int i = 0; i < input.length(); i++) { + current = input.charAt(i); + if ((current == 0x9) || (current == 0xA) || (current == 0xD) + || ((current >= 0x20) && (current <= 0xD7FF)) + || ((current >= 0xE000) && (current <= 0xFFFD)) + || ((current >= 0x10000) && (current <= 0x10FFFF))) { + out.append(current); + } + } + return out.toString(); + } + + public static String leftPad(String str, int size, char padChar) { + if (str == null) { + return null; + } else { + int pads = size - str.length(); + if (pads <= 0) { + return str; + } else { + return pads > 8192 ? leftPad(str, size, String.valueOf(padChar)) : padding(pads, padChar).concat(str); + } + } + } + + public static String leftPad(String str, int size, String padStr) { + if (str == null) { + return null; + } else { + if (isEmpty(padStr)) { + padStr = " "; + } + + int padLen = padStr.length(); + int strLen = str.length(); + int pads = size - strLen; + if (pads <= 0) { + return str; + } else if (padLen == 1 && pads <= 8192) { + return leftPad(str, size, padStr.charAt(0)); + } else if (pads == padLen) { + return padStr.concat(str); + } else if (pads < padLen) { + return padStr.substring(0, pads).concat(str); + } else { + char[] padding = new char[pads]; + char[] padChars = padStr.toCharArray(); + + for(int i = 0; i < pads; ++i) { + padding[i] = padChars[i % padLen]; + } + + return (new String(padding)).concat(str); + } + } + } + + private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException { + if (repeat < 0) { + throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat); + } else { + char[] buf = new char[repeat]; + + for(int i = 0; i < buf.length; ++i) { + buf[i] = padChar; + } + + return new String(buf); + } + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/Base64Util.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/Base64Util.java new file mode 100644 index 00000000..7b054a75 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/Base64Util.java @@ -0,0 +1,765 @@ +package com.gitee.sop.sdk.util; + +import java.math.BigInteger; + +/** + * Provides Base64 encoding and decoding as defined by RFC 2045. + * + *

+ * This class implements section 6.8. Base64 Content-Transfer-Encoding from RFC 2045 Multipurpose + * Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies by Freed and Borenstein. + *

+ *

+ * The class can be parameterized in the following manner with various constructors: + *

+ *
    + *
  • URL-safe mode: Default off.
  • + *
  • Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of + * 4 in the encoded data. + *
  • Line separator: Default is CRLF ("\r\n")
  • + *
+ *

+ * The URL-safe parameter is only applied to encode operations. Decoding seamlessly handles both modes. + *

+ *

+ * Since this class operates directly on byte streams, and not character streams, it is hard-coded to only + * encode/decode character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, + * UTF-8, etc). + *

+ *

+ * This class is thread-safe. + *

+ * + * @see RFC 2045 + * @since 1.0 + * @version $Id: Base64.java 1635986 2014-11-01 16:27:52Z tn $ + */ +public class Base64Util extends BaseNCodec { + + /** + * BASE32 characters are 6 bits in length. + * They are formed by taking a block of 3 octets to form a 24-bit string, + * which is converted into 4 BASE64 characters. + */ + private static final int BITS_PER_ENCODED_BYTE = 6; + private static final int BYTES_PER_UNENCODED_BLOCK = 3; + private static final int BYTES_PER_ENCODED_BLOCK = 4; + + /** + * Chunk separator per RFC 2045 section 2.1. + * + *

+ * N.B. The next major release may break compatibility and make this field private. + *

+ * + * @see RFC 2045 section 2.1 + */ + static final byte[] CHUNK_SEPARATOR = {'\r', '\n'}; + + /** + * This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" + * equivalents as specified in Table 1 of RFC 2045. + * + * Thanks to "commons" project in ws.apache.org for this code. + * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ + */ + private static final byte[] STANDARD_ENCODE_TABLE = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' + }; + + /** + * This is a copy of the STANDARD_ENCODE_TABLE above, but with + and / + * changed to - and _ to make the encoded Base64 results more URL-SAFE. + * This table is only used when the Base64's mode is set to URL-SAFE. + */ + private static final byte[] URL_SAFE_ENCODE_TABLE = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' + }; + + /** + * This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified + * in Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64 + * alphabet but fall within the bounds of the array are translated to -1. + * + * Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both + * URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit). + * + * Thanks to "commons" project in ws.apache.org for this code. + * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ + */ + private static final byte[] DECODE_TABLE = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63, 52, 53, 54, + 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, -1, -1, -1, -1, 63, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, + 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 + }; + + /** + * Base64 uses 6-bit fields. + */ + /** Mask used to extract 6 bits, used when encoding */ + private static final int MASK_6BITS = 0x3f; + + // The static final fields above are used for the original static byte[] methods on Base64. + // The private member fields below are used with the new streaming approach, which requires + // some state be preserved between calls of encode() and decode(). + + /** + * Encode table to use: either STANDARD or URL_SAFE. Note: the DECODE_TABLE above remains static because it is able + * to decode both STANDARD and URL_SAFE streams, but the encodeTable must be a member variable so we can switch + * between the two modes. + */ + private final byte[] encodeTable; + + // Only one decode table currently; keep for consistency with Base32 code + private final byte[] decodeTable = DECODE_TABLE; + + /** + * Line separator for encoding. Not used when decoding. Only used if lineLength > 0. + */ + private final byte[] lineSeparator; + + /** + * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. + * decodeSize = 3 + lineSeparator.length; + */ + private final int decodeSize; + + /** + * Convenience variable to help us determine when our buffer is going to run out of room and needs resizing. + * encodeSize = 4 + lineSeparator.length; + */ + private final int encodeSize; + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. + *

+ * When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE. + *

+ * + *

+ * When decoding all variants are supported. + *

+ */ + public Base64Util() { + this(0); + } + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode. + *

+ * When encoding the line length is 76, the line separator is CRLF, and the encoding table is STANDARD_ENCODE_TABLE. + *

+ * + *

+ * When decoding all variants are supported. + *

+ * + * @param urlSafe + * if true, URL-safe encoding is used. In most cases this should be set to + * false. + * @since 1.4 + */ + public Base64Util(final boolean urlSafe) { + this(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe); + } + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. + *

+ * When encoding the line length is given in the constructor, the line separator is CRLF, and the encoding table is + * STANDARD_ENCODE_TABLE. + *

+ *

+ * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. + *

+ *

+ * When decoding all variants are supported. + *

+ * + * @param lineLength + * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of + * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when + * decoding. + * @since 1.4 + */ + public Base64Util(final int lineLength) { + this(lineLength, CHUNK_SEPARATOR); + } + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. + *

+ * When encoding the line length and line separator are given in the constructor, and the encoding table is + * STANDARD_ENCODE_TABLE. + *

+ *

+ * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. + *

+ *

+ * When decoding all variants are supported. + *

+ * + * @param lineLength + * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of + * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when + * decoding. + * @param lineSeparator + * Each line of encoded data will end with this sequence of bytes. + * @throws IllegalArgumentException + * Thrown when the provided lineSeparator included some base64 characters. + * @since 1.4 + */ + public Base64Util(final int lineLength, final byte[] lineSeparator) { + this(lineLength, lineSeparator, false); + } + + /** + * Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. + *

+ * When encoding the line length and line separator are given in the constructor, and the encoding table is + * STANDARD_ENCODE_TABLE. + *

+ *

+ * Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data. + *

+ *

+ * When decoding all variants are supported. + *

+ * + * @param lineLength + * Each line of encoded data will be at most of the given length (rounded down to nearest multiple of + * 4). If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when + * decoding. + * @param lineSeparator + * Each line of encoded data will end with this sequence of bytes. + * @param urlSafe + * Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode + * operations. Decoding seamlessly handles both modes. + * Note: no padding is added when using the URL-safe alphabet. + * @throws IllegalArgumentException + * The provided lineSeparator included some base64 characters. That's not going to work! + * @since 1.4 + */ + public Base64Util(final int lineLength, final byte[] lineSeparator, final boolean urlSafe) { + super(BYTES_PER_UNENCODED_BLOCK, BYTES_PER_ENCODED_BLOCK, + lineLength, + lineSeparator == null ? 0 : lineSeparator.length); + // @see test case Base64Test.testConstructors() + if (lineSeparator != null) { + if (containsAlphabetOrPad(lineSeparator)) { + final String sep = newStringUtf8(lineSeparator); + throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]"); + } + if (lineLength > 0){ // null line-sep forces no chunking rather than throwing IAE + this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length; + this.lineSeparator = new byte[lineSeparator.length]; + System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length); + } else { + this.encodeSize = BYTES_PER_ENCODED_BLOCK; + this.lineSeparator = null; + } + } else { + this.encodeSize = BYTES_PER_ENCODED_BLOCK; + this.lineSeparator = null; + } + this.decodeSize = this.encodeSize - 1; + this.encodeTable = urlSafe ? URL_SAFE_ENCODE_TABLE : STANDARD_ENCODE_TABLE; + } + + /** + * Returns our current encode mode. True if we're URL-SAFE, false otherwise. + * + * @return true if we're in URL-SAFE mode, false otherwise. + * @since 1.4 + */ + public boolean isUrlSafe() { + return this.encodeTable == URL_SAFE_ENCODE_TABLE; + } + + /** + *

+ * Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with + * the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, to flush last + * remaining bytes (if not multiple of 3). + *

+ *

Note: no padding is added when encoding using the URL-safe alphabet.

+ *

+ * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. + * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ + *

+ * + * @param in + * byte[] array of binary data to base64 encode. + * @param inPos + * Position to start reading data from. + * @param inAvail + * Amount of bytes available from input for encoding. + * @param context + * the context to be used + */ + @Override + void encode(final byte[] in, int inPos, final int inAvail, final Context context) { + if (context.eof) { + return; + } + // inAvail < 0 is how we're informed of EOF in the underlying data we're + // encoding. + if (inAvail < 0) { + context.eof = true; + if (0 == context.modulus && lineLength == 0) { + return; // no leftovers to process and not using chunking + } + final byte[] buffer = ensureBufferSize(encodeSize, context); + final int savedPos = context.pos; + switch (context.modulus) { // 0-2 + case 0 : // nothing to do here + break; + case 1 : // 8 bits = 6 + 2 + // top 6 bits: + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 2) & MASK_6BITS]; + // remaining 2: + buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 4) & MASK_6BITS]; + // URL-SAFE skips the padding to further reduce size. + if (encodeTable == STANDARD_ENCODE_TABLE) { + buffer[context.pos++] = pad; + buffer[context.pos++] = pad; + } + break; + + case 2 : // 16 bits = 6 + 6 + 4 + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 10) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 4) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[(context.ibitWorkArea << 2) & MASK_6BITS]; + // URL-SAFE skips the padding to further reduce size. + if (encodeTable == STANDARD_ENCODE_TABLE) { + buffer[context.pos++] = pad; + } + break; + default: + throw new IllegalStateException("Impossible modulus "+context.modulus); + } + context.currentLinePos += context.pos - savedPos; // keep track of current line position + // if currentPos == 0 we are at the start of a line, so don't add CRLF + if (lineLength > 0 && context.currentLinePos > 0) { + System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); + context.pos += lineSeparator.length; + } + } else { + for (int i = 0; i < inAvail; i++) { + final byte[] buffer = ensureBufferSize(encodeSize, context); + context.modulus = (context.modulus+1) % BYTES_PER_UNENCODED_BLOCK; + int b = in[inPos++]; + if (b < 0) { + b += 256; + } + context.ibitWorkArea = (context.ibitWorkArea << 8) + b; // BITS_PER_BYTE + if (0 == context.modulus) { // 3 bytes = 24 bits = 4 * 6 bits to extract + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 18) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 12) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[(context.ibitWorkArea >> 6) & MASK_6BITS]; + buffer[context.pos++] = encodeTable[context.ibitWorkArea & MASK_6BITS]; + context.currentLinePos += BYTES_PER_ENCODED_BLOCK; + if (lineLength > 0 && lineLength <= context.currentLinePos) { + System.arraycopy(lineSeparator, 0, buffer, context.pos, lineSeparator.length); + context.pos += lineSeparator.length; + context.currentLinePos = 0; + } + } + } + } + } + + /** + *

+ * Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once + * with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1" + * call is not necessary when decoding, but it doesn't hurt, either. + *

+ *

+ * Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are + * silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in, + * garbage-out philosophy: it will not check the provided data for validity. + *

+ *

+ * Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach. + * http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ + *

+ * + * @param in + * byte[] array of ascii data to base64 decode. + * @param inPos + * Position to start reading data from. + * @param inAvail + * Amount of bytes available from input for encoding. + * @param context + * the context to be used + */ + @Override + void decode(final byte[] in, int inPos, final int inAvail, final Context context) { + if (context.eof) { + return; + } + if (inAvail < 0) { + context.eof = true; + } + for (int i = 0; i < inAvail; i++) { + final byte[] buffer = ensureBufferSize(decodeSize, context); + final byte b = in[inPos++]; + if (b == pad) { + // We're done. + context.eof = true; + break; + } else { + if (b >= 0 && b < DECODE_TABLE.length) { + final int result = DECODE_TABLE[b]; + if (result >= 0) { + context.modulus = (context.modulus+1) % BYTES_PER_ENCODED_BLOCK; + context.ibitWorkArea = (context.ibitWorkArea << BITS_PER_ENCODED_BYTE) + result; + if (context.modulus == 0) { + buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 16) & MASK_8BITS); + buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); + buffer[context.pos++] = (byte) (context.ibitWorkArea & MASK_8BITS); + } + } + } + } + } + + // Two forms of EOF as far as base64 decoder is concerned: actual + // EOF (-1) and first time '=' character is encountered in stream. + // This approach makes the '=' padding characters completely optional. + if (context.eof && context.modulus != 0) { + final byte[] buffer = ensureBufferSize(decodeSize, context); + + // We have some spare bits remaining + // Output all whole multiples of 8 bits and ignore the rest + switch (context.modulus) { +// case 0 : // impossible, as excluded above + case 1 : // 6 bits - ignore entirely + break; + case 2 : // 12 bits = 8 + 4 + context.ibitWorkArea = context.ibitWorkArea >> 4; // dump the extra 4 bits + buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); + break; + case 3 : // 18 bits = 8 + 8 + 2 + context.ibitWorkArea = context.ibitWorkArea >> 2; // dump 2 bits + buffer[context.pos++] = (byte) ((context.ibitWorkArea >> 8) & MASK_8BITS); + buffer[context.pos++] = (byte) ((context.ibitWorkArea) & MASK_8BITS); + break; + default: + throw new IllegalStateException("Impossible modulus "+context.modulus); + } + } + } + + /** + * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the + * method treats whitespace as valid. + * + * @param arrayOctet + * byte array to test + * @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; + * false, otherwise + * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0. + */ + @Deprecated + public static boolean isArrayByteBase64(final byte[] arrayOctet) { + return isBase64(arrayOctet); + } + + /** + * Returns whether or not the octet is in the base 64 alphabet. + * + * @param octet + * The value to test + * @return true if the value is defined in the the base 64 alphabet, false otherwise. + * @since 1.4 + */ + public static boolean isBase64(final byte octet) { + return octet == PAD_DEFAULT || (octet >= 0 && octet < DECODE_TABLE.length && DECODE_TABLE[octet] != -1); + } + + /** + * Tests a given String to see if it contains only valid characters within the Base64 alphabet. Currently the + * method treats whitespace as valid. + * + * @param base64 + * String to test + * @return true if all characters in the String are valid characters in the Base64 alphabet or if + * the String is empty; false, otherwise + * @since 1.5 + */ + public static boolean isBase64(final String base64) { + return isBase64(getBytesUtf8(base64)); + } + + /** + * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the + * method treats whitespace as valid. + * + * @param arrayOctet + * byte array to test + * @return true if all bytes are valid characters in the Base64 alphabet or if the byte array is empty; + * false, otherwise + * @since 1.5 + */ + public static boolean isBase64(final byte[] arrayOctet) { + for (int i = 0; i < arrayOctet.length; i++) { + if (!isBase64(arrayOctet[i]) && !isWhiteSpace(arrayOctet[i])) { + return false; + } + } + return true; + } + + /** + * Encodes binary data using the base64 algorithm but does not chunk the output. + * + * @param binaryData + * binary data to encode + * @return byte[] containing Base64 characters in their UTF-8 representation. + */ + public static byte[] encodeBase64(final byte[] binaryData) { + return encodeBase64(binaryData, false); + } + + /** + * Encodes binary data using the base64 algorithm but does not chunk the output. + * + * NOTE: We changed the behaviour of this method from multi-line chunking (commons-codec-1.4) to + * single-line non-chunking (commons-codec-1.5). + * + * @param binaryData + * binary data to encode + * @return String containing Base64 characters. + * @since 1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not). + */ + public static String encodeBase64String(final byte[] binaryData) { + return newStringUtf8(encodeBase64(binaryData, false)); + } + + /** + * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The + * url-safe variation emits - and _ instead of + and / characters. + * Note: no padding is added. + * @param binaryData + * binary data to encode + * @return byte[] containing Base64 characters in their UTF-8 representation. + * @since 1.4 + */ + public static byte[] encodeBase64URLSafe(final byte[] binaryData) { + return encodeBase64(binaryData, false, true); + } + + /** + * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The + * url-safe variation emits - and _ instead of + and / characters. + * Note: no padding is added. + * @param binaryData + * binary data to encode + * @return String containing Base64 characters + * @since 1.4 + */ + public static String encodeBase64URLSafeString(final byte[] binaryData) { + return newStringUtf8(encodeBase64(binaryData, false, true)); + } + + /** + * Encodes binary data using the base64 algorithm and chunks the encoded output into 76 character blocks + * + * @param binaryData + * binary data to encode + * @return Base64 characters chunked in 76 character blocks + */ + public static byte[] encodeBase64Chunked(final byte[] binaryData) { + return encodeBase64(binaryData, true); + } + + /** + * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. + * + * @param binaryData + * Array containing binary data to encode. + * @param isChunked + * if true this encoder will chunk the base64 output into 76 character blocks + * @return Base64-encoded data. + * @throws IllegalArgumentException + * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE} + */ + public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked) { + return encodeBase64(binaryData, isChunked, false); + } + + /** + * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. + * + * @param binaryData + * Array containing binary data to encode. + * @param isChunked + * if true this encoder will chunk the base64 output into 76 character blocks + * @param urlSafe + * if true this encoder will emit - and _ instead of the usual + and / characters. + * Note: no padding is added when encoding using the URL-safe alphabet. + * @return Base64-encoded data. + * @throws IllegalArgumentException + * Thrown when the input array needs an output array bigger than {@link Integer#MAX_VALUE} + * @since 1.4 + */ + public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe) { + return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE); + } + + /** + * Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks. + * + * @param binaryData + * Array containing binary data to encode. + * @param isChunked + * if true this encoder will chunk the base64 output into 76 character blocks + * @param urlSafe + * if true this encoder will emit - and _ instead of the usual + and / characters. + * Note: no padding is added when encoding using the URL-safe alphabet. + * @param maxResultSize + * The maximum result size to accept. + * @return Base64-encoded data. + * @throws IllegalArgumentException + * Thrown when the input array needs an output array bigger than maxResultSize + * @since 1.4 + */ + public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, + final boolean urlSafe, final int maxResultSize) { + if (binaryData == null || binaryData.length == 0) { + return binaryData; + } + + // Create this so can use the super-class method + // Also ensures that the same roundings are performed by the ctor and the code + final Base64Util b64 = isChunked ? new Base64Util(urlSafe) : new Base64Util(0, CHUNK_SEPARATOR, urlSafe); + final long len = b64.getEncodedLength(binaryData); + if (len > maxResultSize) { + throw new IllegalArgumentException("Input array too big, the output array would be bigger (" + + len + + ") than the specified maximum size of " + + maxResultSize); + } + + return b64.encode(binaryData); + } + + /** + * Decodes a Base64 String into octets. + *

+ * Note: this method seamlessly handles data encoded in URL-safe or normal mode. + *

+ * + * @param base64String + * String containing Base64 data + * @return Array containing decoded data. + * @since 1.4 + */ + public static byte[] decodeBase64(final String base64String) { + return new Base64Util().decode(base64String); + } + + /** + * Decodes Base64 data into octets. + *

+ * Note: this method seamlessly handles data encoded in URL-safe or normal mode. + *

+ * + * @param base64Data + * Byte array containing Base64 data + * @return Array containing decoded data. + */ + public static byte[] decodeBase64(final byte[] base64Data) { + return new Base64Util().decode(base64Data); + } + + // Implementation of the Encoder Interface + + // Implementation of integer encoding used for crypto + /** + * Decodes a byte64-encoded integer according to crypto standards such as W3C's XML-Signature. + * + * @param pArray + * a byte array containing base64 character data + * @return A BigInteger + * @since 1.4 + */ + public static BigInteger decodeInteger(final byte[] pArray) { + return new BigInteger(1, decodeBase64(pArray)); + } + + /** + * Encodes to a byte64-encoded integer according to crypto standards such as W3C's XML-Signature. + * + * @param bigInt + * a BigInteger + * @return A byte array containing base64 character data + * @throws NullPointerException + * if null is passed in + * @since 1.4 + */ + public static byte[] encodeInteger(final BigInteger bigInt) { + if (bigInt == null) { + throw new NullPointerException("encodeInteger called with null parameter"); + } + return encodeBase64(toIntegerBytes(bigInt), false); + } + + /** + * Returns a byte-array representation of a BigInteger without sign bit. + * + * @param bigInt + * BigInteger to be converted + * @return a byte array representation of the BigInteger parameter + */ + static byte[] toIntegerBytes(final BigInteger bigInt) { + int bitlen = bigInt.bitLength(); + // round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + final byte[] bigBytes = bigInt.toByteArray(); + + if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + // set up params for copying everything but sign bit + int startSrc = 0; + int len = bigBytes.length; + + // if bigInt is exactly byte-aligned, just skip signbit in copy + if ((bigInt.bitLength() % 8) == 0) { + startSrc = 1; + len--; + } + final int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec + final byte[] resizedBytes = new byte[bitlen / 8]; + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len); + return resizedBytes; + } + + /** + * Returns whether or not the octet is in the Base64 alphabet. + * + * @param octet + * The value to test + * @return true if the value is defined in the the Base64 alphabet false otherwise. + */ + @Override + protected boolean isInAlphabet(final byte octet) { + return octet >= 0 && octet < decodeTable.length && decodeTable[octet] != -1; + } + +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/BaseNCodec.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/BaseNCodec.java new file mode 100644 index 00000000..20305435 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/BaseNCodec.java @@ -0,0 +1,520 @@ +package com.gitee.sop.sdk.util; + +import java.nio.charset.Charset; +import java.util.Arrays; + +/** + * Abstract superclass for Base-N encoders and decoders. + * + *

+ * This class is thread-safe. + *

+ * + * @version $Id: BaseNCodec.java 1634404 2014-10-26 23:06:10Z ggregory $ + */ +public abstract class BaseNCodec { + + /** + * Holds thread context so classes can be thread-safe. + * + * This class is not itself thread-safe; each thread must allocate its own copy. + * + * @since 1.7 + */ + static class Context { + + /** + * Place holder for the bytes we're dealing with for our based logic. + * Bitwise operations store and extract the encoding or decoding from this variable. + */ + int ibitWorkArea; + + /** + * Place holder for the bytes we're dealing with for our based logic. + * Bitwise operations store and extract the encoding or decoding from this variable. + */ + long lbitWorkArea; + + /** + * Buffer for streaming. + */ + byte[] buffer; + + /** + * Position where next character should be written in the buffer. + */ + int pos; + + /** + * Position where next character should be read from the buffer. + */ + int readPos; + + /** + * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, + * and must be thrown away. + */ + boolean eof; + + /** + * Variable tracks how many characters have been written to the current line. Only used when encoding. We use + * it to make sure each encoded line never goes beyond lineLength (if lineLength > 0). + */ + int currentLinePos; + + /** + * Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This + * variable helps track that. + */ + int modulus; + + Context() { + } + + /** + * Returns a String useful for debugging (especially within a debugger.) + * + * @return a String useful for debugging. + */ + @SuppressWarnings("boxing") // OK to ignore boxing here + public String toString() { + return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, " + + "modulus=%s, pos=%s, readPos=%s]", this.getClass().getSimpleName(), Arrays.toString(buffer), + currentLinePos, eof, ibitWorkArea, lbitWorkArea, modulus, pos, readPos); + } + } + + /** + * EOF + * + * @since 1.7 + */ + static final int EOF = -1; + + /** + * MIME chunk size per RFC 2045 section 6.8. + * + *

+ * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any + * equal signs. + *

+ * + * @see RFC 2045 section 6.8 + */ + public static final int MIME_CHUNK_SIZE = 76; + + /** + * PEM chunk size per RFC 1421 section 4.3.2.4. + * + *

+ * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any + * equal signs. + *

+ * + * @see RFC 1421 section 4.3.2.4 + */ + public static final int PEM_CHUNK_SIZE = 64; + + private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2; + + /** + * Defines the default buffer size - currently {@value} + * - must be large enough for at least one encoded block+separator + */ + private static final int DEFAULT_BUFFER_SIZE = 8192; + + /** Mask used to extract 8 bits, used in decoding bytes */ + protected static final int MASK_8BITS = 0xff; + + /** + * Byte used to pad output. + */ + protected static final byte PAD_DEFAULT = '='; // Allow static access to default + + /** + * @deprecated Use {@link #pad}. Will be removed in 2.0. + */ + @Deprecated + protected final byte PAD = PAD_DEFAULT; // instance variable just in case it needs to vary later + + protected final byte pad; // instance variable just in case it needs to vary later + + /** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */ + private final int unencodedBlockSize; + + /** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */ + private final int encodedBlockSize; + + /** + * Chunksize for encoding. Not used when decoding. + * A value of zero or less implies no chunking of the encoded data. + * Rounded down to nearest multiple of encodedBlockSize. + */ + protected final int lineLength; + + /** + * Size of chunk separator. Not used unless {@link #lineLength} > 0. + */ + private final int chunkSeparatorLength; + + /** + * Note lineLength is rounded down to the nearest multiple of {@link #encodedBlockSize} + * If chunkSeparatorLength is zero, then chunking is disabled. + * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3) + * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4) + * @param lineLength if > 0, use chunking with a length lineLength + * @param chunkSeparatorLength the chunk separator length, if relevant + */ + protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, + final int lineLength, final int chunkSeparatorLength) { + this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, PAD_DEFAULT); + } + + /** + * Note lineLength is rounded down to the nearest multiple of {@link #encodedBlockSize} + * If chunkSeparatorLength is zero, then chunking is disabled. + * @param unencodedBlockSize the size of an unencoded block (e.g. Base64 = 3) + * @param encodedBlockSize the size of an encoded block (e.g. Base64 = 4) + * @param lineLength if > 0, use chunking with a length lineLength + * @param chunkSeparatorLength the chunk separator length, if relevant + * @param pad byte used as padding byte. + */ + protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, + final int lineLength, final int chunkSeparatorLength, final byte pad) { + this.unencodedBlockSize = unencodedBlockSize; + this.encodedBlockSize = encodedBlockSize; + final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0; + this.lineLength = useChunking ? (lineLength / encodedBlockSize) * encodedBlockSize : 0; + this.chunkSeparatorLength = chunkSeparatorLength; + + this.pad = pad; + } + + /** + * Returns true if this object has buffered data for reading. + * + * @param context the context to be used + * @return true if there is data still available for reading. + */ + boolean hasData(final Context context) { // package protected for access from I/O streams + return context.buffer != null; + } + + /** + * Returns the amount of buffered data available for reading. + * + * @param context the context to be used + * @return The amount of buffered data available for reading. + */ + int available(final Context context) { // package protected for access from I/O streams + return context.buffer != null ? context.pos - context.readPos : 0; + } + + /** + * Get the default buffer size. Can be overridden. + * + * @return {@link #DEFAULT_BUFFER_SIZE} + */ + protected int getDefaultBufferSize() { + return DEFAULT_BUFFER_SIZE; + } + + /** + * Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}. + * @param context the context to be used + */ + private byte[] resizeBuffer(final Context context) { + if (context.buffer == null) { + context.buffer = new byte[getDefaultBufferSize()]; + context.pos = 0; + context.readPos = 0; + } else { + final byte[] b = new byte[context.buffer.length * DEFAULT_BUFFER_RESIZE_FACTOR]; + System.arraycopy(context.buffer, 0, b, 0, context.buffer.length); + context.buffer = b; + } + return context.buffer; + } + + /** + * Ensure that the buffer has room for size bytes + * + * @param size minimum spare space required + * @param context the context to be used + * @return the buffer + */ + protected byte[] ensureBufferSize(final int size, final Context context){ + if ((context.buffer == null) || (context.buffer.length < context.pos + size)){ + return resizeBuffer(context); + } + return context.buffer; + } + + /** + * Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail + * bytes. Returns how many bytes were actually extracted. + *

+ * Package protected for access from I/O streams. + * + * @param b + * byte[] array to extract the buffered data into. + * @param bPos + * position in byte[] array to start extraction at. + * @param bAvail + * amount of bytes we're allowed to extract. We may extract fewer (if fewer are available). + * @param context + * the context to be used + * @return The number of bytes successfully extracted into the provided byte[] array. + */ + int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) { + if (context.buffer != null) { + final int len = Math.min(available(context), bAvail); + System.arraycopy(context.buffer, context.readPos, b, bPos, len); + context.readPos += len; + if (context.readPos >= context.pos) { + context.buffer = null; // so hasData() will return false, and this method can return -1 + } + return len; + } + return context.eof ? EOF : 0; + } + + /** + * Checks if a byte value is whitespace or not. + * Whitespace is taken to mean: space, tab, CR, LF + * @param byteToCheck + * the byte to check + * @return true if byte is whitespace, false otherwise + */ + protected static boolean isWhiteSpace(final byte byteToCheck) { + switch (byteToCheck) { + case ' ' : + case '\n' : + case '\r' : + case '\t' : + return true; + default : + return false; + } + } + + /** + * Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of + * the Encoder interface, and will throw an EncoderException if the supplied object is not of type byte[]. + * + * @param obj + * Object to encode + * @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied. + * @throws Exception + * if the parameter supplied is not of type byte[] + */ + public Object encode(final Object obj) throws Exception { + if (!(obj instanceof byte[])) { + throw new Exception("Parameter supplied to Base-N encode is not a byte[]"); + } + return encode((byte[]) obj); + } + + /** + * Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet. + * Uses UTF8 encoding. + * + * @param pArray + * a byte array containing binary data + * @return A String containing only Base-N character data + */ + public String encodeToString(final byte[] pArray) { + return newStringUtf8(encode(pArray)); + } + + /** + * Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet. + * Uses UTF8 encoding. + * + * @param pArray a byte array containing binary data + * @return String containing only character data in the appropriate alphabet. + */ + public String encodeAsString(final byte[] pArray){ + return newStringUtf8(encode(pArray)); + } + + /** + * Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of + * the Decoder interface, and will throw a DecoderException if the supplied object is not of type byte[] or String. + * + * @param obj + * Object to decode + * @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String + * supplied. + * @throws Exception + * if the parameter supplied is not of type byte[] + */ + public Object decode(final Object obj) throws Exception { + if (obj instanceof byte[]) { + return decode((byte[]) obj); + } else if (obj instanceof String) { + return decode((String) obj); + } else { + throw new Exception("Parameter supplied to Base-N decode is not a byte[] or a String"); + } + } + + /** + * Decodes a String containing characters in the Base-N alphabet. + * + * @param pArray + * A String containing Base-N character data + * @return a byte array containing binary data + */ + public byte[] decode(final String pArray) { + return decode(getBytesUtf8(pArray)); + } + + /** + * Decodes a byte[] containing characters in the Base-N alphabet. + * + * @param pArray + * A byte array containing Base-N character data + * @return a byte array containing binary data + */ + public byte[] decode(final byte[] pArray) { + if (pArray == null || pArray.length == 0) { + return pArray; + } + final Context context = new Context(); + decode(pArray, 0, pArray.length, context); + decode(pArray, 0, EOF, context); // Notify decoder of EOF. + final byte[] result = new byte[context.pos]; + readResults(result, 0, result.length, context); + return result; + } + + /** + * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet. + * + * @param pArray + * a byte array containing binary data + * @return A byte array containing only the basen alphabetic character data + */ + public byte[] encode(final byte[] pArray) { + if (pArray == null || pArray.length == 0) { + return pArray; + } + final Context context = new Context(); + encode(pArray, 0, pArray.length, context); + encode(pArray, 0, EOF, context); // Notify encoder of EOF. + final byte[] buf = new byte[context.pos - context.readPos]; + readResults(buf, 0, buf.length, context); + return buf; + } + + // package protected for access from I/O streams + abstract void encode(byte[] pArray, int i, int length, Context context); + + // package protected for access from I/O streams + abstract void decode(byte[] pArray, int i, int length, Context context); + + /** + * Returns whether or not the octet is in the current alphabet. + * Does not allow whitespace or pad. + * + * @param value The value to test + * + * @return true if the value is defined in the current alphabet, false otherwise. + */ + protected abstract boolean isInAlphabet(byte value); + + /** + * Tests a given byte array to see if it contains only valid characters within the alphabet. + * The method optionally treats whitespace and pad as valid. + * + * @param arrayOctet byte array to test + * @param allowWSPad if true, then whitespace and PAD are also allowed + * + * @return true if all bytes are valid characters in the alphabet or if the byte array is empty; + * false, otherwise + */ + public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) { + for (int i = 0; i < arrayOctet.length; i++) { + if (!isInAlphabet(arrayOctet[i]) && + (!allowWSPad || (arrayOctet[i] != pad) && !isWhiteSpace(arrayOctet[i]))) { + return false; + } + } + return true; + } + + /** + * Tests a given String to see if it contains only valid characters within the alphabet. + * The method treats whitespace and PAD as valid. + * + * @param basen String to test + * @return true if all characters in the String are valid characters in the alphabet or if + * the String is empty; false, otherwise + * @see #isInAlphabet(byte[], boolean) + */ + public boolean isInAlphabet(final String basen) { + return isInAlphabet(getBytesUtf8(basen), true); + } + + /** + * Tests a given byte array to see if it contains any characters within the alphabet or PAD. + * + * Intended for use in checking line-ending arrays + * + * @param arrayOctet + * byte array to test + * @return true if any byte is a valid character in the alphabet or PAD; false otherwise + */ + protected boolean containsAlphabetOrPad(final byte[] arrayOctet) { + if (arrayOctet == null) { + return false; + } + for (final byte element : arrayOctet) { + if (pad == element || isInAlphabet(element)) { + return true; + } + } + return false; + } + + /** + * Calculates the amount of space needed to encode the supplied array. + * + * @param pArray byte[] array which will later be encoded + * + * @return amount of space needed to encoded the supplied array. + * Returns a long since a max-len array will require > Integer.MAX_VALUE + */ + public long getEncodedLength(final byte[] pArray) { + // Calculate non-chunked size - rounded up to allow for padding + // cast to long is needed to avoid possibility of overflow + long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize; + if (lineLength > 0) { // We're using chunking + // Round up to nearest multiple + len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength; + } + return len; + } + + public static Charset UTF8 = Charset.forName("UTF-8"); + + public static String newStringUtf8(byte[] bytes) { + return newString(bytes, UTF8); + } + + private static String newString(final byte[] bytes, final Charset charset) { + return bytes == null ? null : new String(bytes, charset); + } + + public static byte[] getBytesUtf8(final String string) { + return getBytes(string, UTF8); + } + + private static byte[] getBytes(final String string, final Charset charset) { + if (string == null) { + return null; + } + return string.getBytes(charset); + } +} \ No newline at end of file diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/ClassUtil.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/ClassUtil.java new file mode 100644 index 00000000..b5c05931 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/ClassUtil.java @@ -0,0 +1,72 @@ +/* + * Copyright 2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.gitee.sop.sdk.util; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +/** + * @author tanghc + */ +public class ClassUtil { + + private static Map> classGenricTypeCache = new HashMap<>(16); + + /** + * 返回定义类时的泛型参数的类型.
+ * 如:定义一个BookManager类
+ * {@literal public BookManager extends GenricManager}{...} + *
+ * 调用getSuperClassGenricType(getClass(),0)将返回Book的Class类型
+ * 调用getSuperClassGenricType(getClass(),1)将返回Address的Class类型 + * + * @param clazz 从哪个类中获取 + * @param index 泛型参数索引,从0开始 + */ + public static Class getSuperClassGenricType(Class clazz, int index) throws IndexOutOfBoundsException { + String cacheKey = clazz.getName() + index; + Class cachedClass = classGenricTypeCache.get(cacheKey); + if (cachedClass != null) { + return cachedClass; + } + + Type genType = clazz.getGenericSuperclass(); + + // 没有泛型参数 + if (!(genType instanceof ParameterizedType)) { + throw new RuntimeException("class " + clazz.getName() + " 没有指定父类泛型"); + } else { + Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); + + if (index >= params.length || index < 0) { + throw new RuntimeException("泛型索引不正确,index:" + index); + } + if (!(params[index] instanceof Class)) { + throw new RuntimeException(params[index] + "不是Class类型"); + } + + Class retClass = (Class) params[index]; + // 缓存起来 + classGenricTypeCache.put(cacheKey, retClass); + + return retClass; + } + } + +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/FileUtil.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/FileUtil.java new file mode 100644 index 00000000..1b35f876 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/FileUtil.java @@ -0,0 +1,65 @@ +package com.gitee.sop.sdk.util; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +public class FileUtil { + + /** + * The default buffer size to use. + */ + private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; + private static final int EOF = -1; + + /** + * 将文件流转换成byte[] + * @param input + * @return + * @throws IOException + */ + public static byte[] toBytes(InputStream input) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + int n = 0; + byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; + + while (EOF != (n = input.read(buffer))) { + output.write(buffer, 0, n); + } + return output.toByteArray(); + } + + /** + * 将文件转换成数据流 + * @param file 文件 + * @return 返回数据流 + * @throws IOException + */ + public static byte[] toBytes(File file) throws IOException { + if (file.exists()) { + if (file.isDirectory()) { + throw new IOException("File '" + file + "' exists but is a directory"); + } + if (file.canRead() == false) { + throw new IOException("File '" + file + "' cannot be read"); + } + } else { + throw new FileNotFoundException("File '" + file + "' does not exist"); + } + InputStream input = null; + try { + input = new FileInputStream(file); + return toBytes(input); + } finally { + try { + if (input != null) { + input.close(); + } + } catch (IOException ioe) { + } + } + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/HexUtil.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/HexUtil.java new file mode 100644 index 00000000..c764ab5f --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/HexUtil.java @@ -0,0 +1,57 @@ +package com.gitee.sop.sdk.util; + +public class HexUtil { + private static final String ZERO = "0"; + private static final String CHARS = "0123456789ABCDEF"; + + /** + * 二进制转十六进制字符串 + * + * @param bytes + * @return + */ + public static String byte2hex(byte[] bytes) { + StringBuilder sign = new StringBuilder(); + for (int i = 0; i < bytes.length; i++) { + String hex = Integer.toHexString(bytes[i] & 0xFF); + if (hex.length() == 1) { + sign.append(ZERO); + } + sign.append(hex); + } + return sign.toString(); + } + + /** + * 十六进制字符串转二进制 + * + * @param hexString + * the hex string + * @return byte[] + */ + public static byte[] hex2bytes(String hexString) { + if (hexString == null || hexString.equals("")) { + return null; + } + hexString = hexString.toUpperCase(); + int length = hexString.length() / 2; + char[] hexChars = hexString.toCharArray(); + byte[] d = new byte[length]; + for (int i = 0; i < length; i++) { + int pos = i * 2; + d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); + } + return d; + } + + /** + * Convert char to byte + * + * @param c + * char + * @return byte + */ + private static byte charToByte(char c) { + return (byte) CHARS.indexOf(c); + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/JsonUtil.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/JsonUtil.java new file mode 100644 index 00000000..26551bc8 --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/JsonUtil.java @@ -0,0 +1,33 @@ +package com.gitee.sop.sdk.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +public class JsonUtil { + + /** + * 对象转json + * @param obj + * @return + */ + public static String toJSONString(Object obj) { + if(obj == null) { + return "{}"; + } + return JSON.toJSONString(obj); + } + + /** + * json转对象 + * @param json + * @param clazz + * @return + */ + public static T parseObject(String json, Class clazz) { + return JSON.parseObject(json, clazz); + } + + public static JSONObject parseJSONObject(String json) { + return JSON.parseObject(json); + } +} diff --git a/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/MD5Util.java b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/MD5Util.java new file mode 100644 index 00000000..985ba58a --- /dev/null +++ b/sop-sdk/sdk-java/src/main/java/com/gitee/sop/sdk/util/MD5Util.java @@ -0,0 +1,78 @@ +package com.gitee.sop.sdk.util; + +import java.security.MessageDigest; + +public class MD5Util { + + private static final String MD5 = "MD5"; + + /** + * 生成md5,全部大写 + * + * @param input + * @return + */ + public static String encryptUpper(String input) { + return encrypt(input).toUpperCase(); + } + + /** + * 生成md5,全部大写 + * + * @param input + * @return + */ + public static String encryptUpper(byte[] input) { + return encrypt(input).toUpperCase(); + } + + /** + * 生成md5,全部小写 + * + * @param input + * @return + */ + public static String encrypt(String input) { + if(input == null || "".equals(input)) { + throw new IllegalArgumentException("The argument input can not be empty."); + } + return encrypt(input.getBytes()); + } + + /** + * 返回长度16串,小写 + * @param input + * @return + */ + public static String encrypt16(String input) { + return encrypt(input).substring(8,24); + } + + /** + * 生成md5,全部小写 + * + * @param input + * @return + */ + public static String encrypt(byte[] input) { + if(input == null || input.length == 0) { + throw new IllegalArgumentException("The argument input can not be empty."); + } + try { + // 创建一个提供信息摘要算法的对象,初始化为md5算法对象 + MessageDigest md = MessageDigest.getInstance(MD5); + // 计算后获得字节数组,这就是那128位了 + byte[] buff = md.digest(input); + + // 把数组每一字节(一个字节占八位)换成16进制连成md5字符串 + return HexUtil.byte2hex(buff); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + + /*public static void main(String[] args) { + System.out.println(encrypt(encrypt("123456"))); + }*/ +} diff --git a/sop-sdk/sdk-java/src/main/resources/pri.key b/sop-sdk/sdk-java/src/main/resources/pri.key new file mode 100644 index 00000000..1ea9ba4e --- /dev/null +++ b/sop-sdk/sdk-java/src/main/resources/pri.key @@ -0,0 +1 @@ +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCXJv1pQFqWNA/++OYEV7WYXwexZK/J8LY1OWlP9X0T6wHFOvxNKRvMkJ5544SbgsJpVcvRDPrcxmhPbi/sAhdO4x2PiPKIz9Yni2OtYCCeaiE056B+e1O2jXoLeXbfi9fPivJZkxH/tb4xfLkH3bA8ZAQnQsoXA0SguykMRZntF0TndUfvDrLqwhlR8r5iRdZLB6F8o8qXH6UPDfNEnf/K8wX5T4EB1b8x8QJ7Ua4GcIUqeUxGHdQpzNbJdaQvoi06lgccmL+PHzminkFYON7alj1CjDN833j7QMHdPtS9l7B67fOU/p2LAAkPMtoVBfxQt9aFj7B8rEhGCz02iJIBAgMBAAECggEARqOuIpY0v6WtJBfmR3lGIOOokLrhfJrGTLF8CiZMQha+SRJ7/wOLPlsH9SbjPlopyViTXCuYwbzn2tdABigkBHYXxpDV6CJZjzmRZ+FY3S/0POlTFElGojYUJ3CooWiVfyUMhdg5vSuOq0oCny53woFrf32zPHYGiKdvU5Djku1onbDU0Lw8w+5tguuEZ76kZ/lUcccGy5978FFmYpzY/65RHCpvLiLqYyWTtaNT1aQ/9pw4jX9HO9NfdJ9gYFK8r/2f36ZE4hxluAfeOXQfRC/WhPmiw/ReUhxPznG/WgKaa/OaRtAx3inbQ+JuCND7uuKeRe4osP2jLPHPP6AUwQKBgQDUNu3BkLoKaimjGOjCTAwtp71g1oo+k5/uEInAo7lyEwpV0EuUMwLA/HCqUgR4K9pyYV+Oyb8d6f0+Hz0BMD92I2pqlXrD7xV2WzDvyXM3s63NvorRooKcyfd9i6ccMjAyTR2qfLkxv0hlbBbsPHz4BbU63xhTJp3Ghi0/ey/1HQKBgQC2VsgqC6ykfSidZUNLmQZe3J0p/Qf9VLkfrQ+xaHapOs6AzDU2H2osuysqXTLJHsGfrwVaTs00ER2z8ljTJPBUtNtOLrwNRlvgdnzyVAKHfOgDBGwJgiwpeE9voB1oAV/mXqSaUWNnuwlOIhvQEBwekqNyWvhLqC7nCAIhj3yvNQKBgQCqYbeec56LAhWP903Zwcj9VvG7sESqXUhIkUqoOkuIBTWFFIm54QLTA1tJxDQGb98heoCIWf5x/A3xNI98RsqNBX5JON6qNWjb7/dobitti3t99v/ptDp9u8JTMC7penoryLKK0Ty3bkan95Kn9SC42YxaSghzqkt+uvfVQgiNGQKBgGxU6P2aDAt6VNwWosHSe+d2WWXt8IZBhO9d6dn0f7ORvcjmCqNKTNGgrkewMZEuVcliueJquR47IROdY8qmwqcBAN7Vg2K7r7CPlTKAWTRYMJxCT1Hi5gwJb+CZF3+IeYqsJk2NF2s0w5WJTE70k1BSvQsfIzAIDz2yE1oPHvwVAoGAA6e+xQkVH4fMEph55RJIZ5goI4Y76BSvt2N5OKZKd4HtaV+eIhM3SDsVYRLIm9ZquJHMiZQGyUGnsvrKL6AAVNK7eQZCRDk9KQz+0GKOGqku0nOZjUbAu6A2/vtXAaAuFSFx1rUQVVjFulLexkXR3KcztL1Qu2k5pB6Si0K/uwQ= \ No newline at end of file diff --git a/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/1.txt b/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/1.txt new file mode 100644 index 00000000..14684f6b --- /dev/null +++ b/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/1.txt @@ -0,0 +1,2 @@ +回忆起 20多年来我们一起走过的日子,我就感到特别温馨、特别甜蜜。你第一次闯入我生命中的情景,仿佛就在眼前……第一次偶然相遇是1996年5月,那是一个夏风习习的夜晚,我刚从工地回来,同事就邀我一起去城建学院跳舞,踏进舞厅的一瞬间,在暗淡温柔的霓虹灯下,你那清新脱俗的靓影一下子就深深的嵌入了我的心里。 +记得大学时代,李春波的歌曲“小芳”响彻校园,那个叫小芳的村里姑娘,也深深的烙进了我的心底,成了我少年时的梦中偶像。二十多年来,我一直期盼着找到一个象歌曲中所唱的长得好看又善良、有着一双美丽的大眼睛和两条粗辫子的姑娘做我的爱人,但苦苦寻觅却难见芳踪,谁知众里寻她千百度,蓦然回首,那人却在灯火阑珊处……你就这样俏生生的突然出现在我眼前。当时,你穿着浅绿色的衬衣,正在与一位女同学翩翩起舞,两条又粗又长的辫子在身后灵巧的晃动。一曲终了,我急忙挤到你身边请你跳舞。当时的我还不太会跳舞,还好是一首慢四舞曲,我才没出洋相。拥着你在舞厅漫步,因为心情特别激动,又怕舞步不熟踩到你脚,我眼睛始终盯着脚下,不敢正视你的目光;好不容易平复心情与你搭讪,才打探到你是教育学院的学生舞曲就结束了。后面的舞曲不是我不会跳就是被你那“讨厌”的女同学捷足先登了,始终没有机会再次与你共舞,但我的心已经完完全全的被你牵走了。同事周云看我不再跳舞、心事重重的,就问我为什么,得知我心事后,自告奋勇的说下一曲他去邀请你同学,让我有机会请你跳舞。可没想到我那同事的“光头”会把你们吓跑,让上天给我们安排的第一次相遇就这样擦肩而过。 \ No newline at end of file diff --git a/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/2.txt b/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/2.txt new file mode 100644 index 00000000..63d15603 --- /dev/null +++ b/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/2.txt @@ -0,0 +1 @@ +红与青 时光如流水般,在我面前一闪而过,但我却只能暗暗叹息。 台灯下,小桌前,我坐在那儿,目光停在桌子上的那一个西瓜面前。十几年前的往事仿佛就在昨日。 小时候,我们兄弟几个围坐在一张破破的桌子前。一个勺子,半个西瓜,大家围着轮流舀着吃,大家的目光都聚焦在西瓜上,也许只有在这一刻,我们才不会那样的打闹。我们都想吃最中间的部分,最红的,最甜的部分,可是又如同大人世界般,我们显得那样腼腆。最后,总是你一小口我一小口,把那中间红红的果肉吞进肚子里,更埋下友谊的种子。 日子深一脚浅一脚的过,学习似乎成了我们唯一的公同语言,我们也从一个被别人称为“造反派”的顽童变为一个学子。甚至有时,在哪儿碰见也只会向对方点点头,丝毫没有了小时烈日下奔跑的情谊。家里的那张破破的桌子也不知去向,取而代之的是一张豪华的青瓷桌…… 小学毕业后那年暑假的最后一天,刚刚步入六年级的他们来送别我,我们围坐在桌边,夏日的炎热似乎把我们所有要诉说的话都给憋了回去,我们都沉默着。冰爽的西瓜成了我们释放的对象,我们不再像小时那样子吃西瓜,所有的西瓜都被切成了片,有红,有青。红红的那部分就在最上面,我们之间的友情就像这样火红。 没有告别仪式,只是如青般离开。 “悄悄,是别离的笙箫” 迈入初中,一切都是陌生,交流变少了,浑浑噩噩的梦中,我又梦见了他们。 关了台灯,寂静与黑暗容我沉思。 初一就要结束的几天里,夏天悄无声息得把炎热带来,家人们又带回来了西瓜,复习之余,我又捧起了半个西瓜,这一回就我一人沉默。握着勺子,一口一口舀着慢慢品味。“嗯?”与瓜皮连着的青色果肉吸引了我。“啊!原来他们比中间的果肉更惹人迷!” 我舀了一勺,“咔嚓”,是多么清脆。 “但我不能放歌”,时光荏苒,十几年前的往事似乎又模模糊糊。 他们如流水划过,留下一道青色的痕迹。青,是青。 \ No newline at end of file diff --git a/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/BaseTest.java b/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/BaseTest.java new file mode 100644 index 00000000..9798d2a1 --- /dev/null +++ b/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/BaseTest.java @@ -0,0 +1,8 @@ +package com.gitee.sop.sdk; + +import com.gitee.sop.sdk.client.OpenClient; +import junit.framework.TestCase; + +public class BaseTest extends TestCase { + +} diff --git a/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/SdkTest.java b/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/SdkTest.java new file mode 100644 index 00000000..04b49ece --- /dev/null +++ b/sop-sdk/sdk-java/src/test/java/com/gitee/sop/sdk/SdkTest.java @@ -0,0 +1,72 @@ +package com.gitee.sop.sdk; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.gitee.sop.sdk.client.OpenClient; +import com.gitee.sop.sdk.model.GetStoryModel; +import com.gitee.sop.sdk.request.CommonRequest; +import com.gitee.sop.sdk.request.GetStoryRequest; +import com.gitee.sop.sdk.response.CommonResponse; +import com.gitee.sop.sdk.response.GetStoryResponse; +import junit.framework.TestCase; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +public class SdkTest extends TestCase { + String url = "http://localhost:8081/api"; // zuul + String appId = "2019032617262200001"; + // 支付宝私钥 + String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCXJv1pQFqWNA/++OYEV7WYXwexZK/J8LY1OWlP9X0T6wHFOvxNKRvMkJ5544SbgsJpVcvRDPrcxmhPbi/sAhdO4x2PiPKIz9Yni2OtYCCeaiE056B+e1O2jXoLeXbfi9fPivJZkxH/tb4xfLkH3bA8ZAQnQsoXA0SguykMRZntF0TndUfvDrLqwhlR8r5iRdZLB6F8o8qXH6UPDfNEnf/K8wX5T4EB1b8x8QJ7Ua4GcIUqeUxGHdQpzNbJdaQvoi06lgccmL+PHzminkFYON7alj1CjDN833j7QMHdPtS9l7B67fOU/p2LAAkPMtoVBfxQt9aFj7B8rEhGCz02iJIBAgMBAAECggEARqOuIpY0v6WtJBfmR3lGIOOokLrhfJrGTLF8CiZMQha+SRJ7/wOLPlsH9SbjPlopyViTXCuYwbzn2tdABigkBHYXxpDV6CJZjzmRZ+FY3S/0POlTFElGojYUJ3CooWiVfyUMhdg5vSuOq0oCny53woFrf32zPHYGiKdvU5Djku1onbDU0Lw8w+5tguuEZ76kZ/lUcccGy5978FFmYpzY/65RHCpvLiLqYyWTtaNT1aQ/9pw4jX9HO9NfdJ9gYFK8r/2f36ZE4hxluAfeOXQfRC/WhPmiw/ReUhxPznG/WgKaa/OaRtAx3inbQ+JuCND7uuKeRe4osP2jLPHPP6AUwQKBgQDUNu3BkLoKaimjGOjCTAwtp71g1oo+k5/uEInAo7lyEwpV0EuUMwLA/HCqUgR4K9pyYV+Oyb8d6f0+Hz0BMD92I2pqlXrD7xV2WzDvyXM3s63NvorRooKcyfd9i6ccMjAyTR2qfLkxv0hlbBbsPHz4BbU63xhTJp3Ghi0/ey/1HQKBgQC2VsgqC6ykfSidZUNLmQZe3J0p/Qf9VLkfrQ+xaHapOs6AzDU2H2osuysqXTLJHsGfrwVaTs00ER2z8ljTJPBUtNtOLrwNRlvgdnzyVAKHfOgDBGwJgiwpeE9voB1oAV/mXqSaUWNnuwlOIhvQEBwekqNyWvhLqC7nCAIhj3yvNQKBgQCqYbeec56LAhWP903Zwcj9VvG7sESqXUhIkUqoOkuIBTWFFIm54QLTA1tJxDQGb98heoCIWf5x/A3xNI98RsqNBX5JON6qNWjb7/dobitti3t99v/ptDp9u8JTMC7penoryLKK0Ty3bkan95Kn9SC42YxaSghzqkt+uvfVQgiNGQKBgGxU6P2aDAt6VNwWosHSe+d2WWXt8IZBhO9d6dn0f7ORvcjmCqNKTNGgrkewMZEuVcliueJquR47IROdY8qmwqcBAN7Vg2K7r7CPlTKAWTRYMJxCT1Hi5gwJb+CZF3+IeYqsJk2NF2s0w5WJTE70k1BSvQsfIzAIDz2yE1oPHvwVAoGAA6e+xQkVH4fMEph55RJIZ5goI4Y76BSvt2N5OKZKd4HtaV+eIhM3SDsVYRLIm9ZquJHMiZQGyUGnsvrKL6AAVNK7eQZCRDk9KQz+0GKOGqku0nOZjUbAu6A2/vtXAaAuFSFx1rUQVVjFulLexkXR3KcztL1Qu2k5pB6Si0K/uwQ="; + + + // 声明一个就行 + OpenClient client = new OpenClient(url, appId, privateKey); + + // 标准用法 + @Test + public void testGet() { + // 创建请求对象 + GetStoryRequest request = new GetStoryRequest(); + // 请求参数 + GetStoryModel model = new GetStoryModel(); + model.setName("白雪公主"); + request.setBizModel(model); + + // 发送请求 + GetStoryResponse response = client.execute(request); + + if (response.isSuccess()) { + // 返回结果 + System.out.println(response); + } else { + System.out.println(response); + } + } + + + // 懒人版,如果不想添加Request,Response,Model。可以用这种方式,返回全部是String,后续自己处理json + @Test + public void testLazy() { + // 创建请求对象 + CommonRequest request = new CommonRequest("alipay.story.find"); + // 请求参数 + Map bizModel = new HashMap<>(); + bizModel.put("name", "白雪公主"); + request.setBizModel(bizModel); + + // 发送请求 + CommonResponse response = client.execute(request); + + if (response.isSuccess()) { + // 返回结果 + String body = response.getBody(); + JSONObject jsonObject = JSON.parseObject(body); + System.out.println(jsonObject); + } else { + System.out.println(response); + } + } + +}